Use JmxReporter.Builder.filter to handle exclusion rules

Since the support for excluding some metrics from being reported was
added in Ib4da8ba8ad5d6ba3f1cbb0b3f83375cfcef3af67, this metric reporter
was broken: it computed the set of metrics to be exposed once and then
exposed this fixed (sub)set forever. Any newly added metrics were not
exposed. For example: if a plugin which exposes metrics loads after this
plugin, these metrics would be exposed via JMX. Further, even some
metrics bound via a MetricModule in Gerrit core wouldn't be reported by
this plugin if that MetricModule (which is also a LifeCycleModule)
happens to receive its start() call after this plugin already computed
the snapshot of exposed metrics.

Instead of copying the set of exposed metrics in a new MetricRegistry,
apply a MetricFilter to the MetricRegistry instance from Gerrit core.
Handle exclusion rules through that filter.

Change-Id: Iaf0b4fa03293ccc2313ab0332f70a3a41ea30a25
diff --git a/src/main/java/com/googlesource/gerrit/plugins/metricsreporterjmx/GerritJmxReporter.java b/src/main/java/com/googlesource/gerrit/plugins/metricsreporterjmx/GerritJmxReporter.java
index 9474814..c845362 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/metricsreporterjmx/GerritJmxReporter.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/metricsreporterjmx/GerritJmxReporter.java
@@ -14,14 +14,13 @@
 
 package com.googlesource.gerrit.plugins.metricsreporterjmx;
 
-import com.codahale.metrics.Metric;
-import com.codahale.metrics.MetricFilter;
 import com.codahale.metrics.MetricRegistry;
 import com.codahale.metrics.jmx.JmxReporter;
 import com.google.gerrit.extensions.annotations.Listen;
 import com.google.gerrit.extensions.events.LifecycleListener;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
+import java.util.function.Predicate;
 
 @Listen
 @Singleton
@@ -30,25 +29,10 @@
 
   @Inject
   public GerritJmxReporter(MetricRegistry registry, Configuration config) {
-
-    /* Copy the registry to avoid filtering the global one */
-    MetricRegistry filteredRegistry = new MetricRegistry();
-    filteredRegistry.registerAll(registry);
-
-    config
-        .getExcludes()
-        .forEach(
-            exclude -> {
-              filteredRegistry.removeMatching(
-                  new MetricFilter() {
-                    @Override
-                    public boolean matches(String name, Metric metric) {
-                      return name.matches(exclude);
-                    }
-                  });
-            });
-
-    this.reporter = JmxReporter.forRegistry(filteredRegistry).build();
+    Predicate<String> exclusionFilter =
+        s -> config.getExcludes().stream().anyMatch(e -> s.matches(e));
+    this.reporter =
+        JmxReporter.forRegistry(registry).filter((n, m) -> !exclusionFilter.test(n)).build();
   }
 
   @Override