Java Code Examples for com.codahale.metrics.Counter

The following examples show how to use com.codahale.metrics.Counter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: vertx-dropwizard-metrics   Source File: TCPMetricsImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void disconnected(Long ctx, SocketAddress remoteAddress) {
  openConnections.dec();
  connections.update(System.nanoTime() - ctx, TimeUnit.NANOSECONDS);

  // On network outage the remoteAddress can be null.
  // Do not report the open-connections when it's null
  if (remoteAddress != null) {
    // Remote address connection metrics
    Counter counter = counter("open-connections", remoteAddress.host());
    counter.dec();
    if (counter.getCount() == 0) {
      remove("open-connections", remoteAddress.host());
    }
  }

  // A little clunky, but it's possible we got here after closed has been called
  if (closed) {
    removeAll();
  }
}
 
Example 2
Source Project: resilience4j   Source File: TimeLimiterMetrics.java    License: Apache License 2.0 6 votes vote down vote up
private TimeLimiterMetrics(String prefix, Iterable<TimeLimiter> timeLimiters,
    MetricRegistry metricRegistry) {
    requireNonNull(prefix, PREFIX_NULL);
    requireNonNull(timeLimiters, ITERABLE_NULL);
    requireNonNull(metricRegistry);
    this.metricRegistry = metricRegistry;
    timeLimiters.forEach(timeLimiter -> {
            String name = timeLimiter.getName();
            Counter successes = metricRegistry.counter(name(prefix, name, SUCCESSFUL));
            Counter failures = metricRegistry.counter(name(prefix, name, FAILED));
            Counter timeouts = metricRegistry.counter(name(prefix, name, TIMEOUT));
            timeLimiter.getEventPublisher().onSuccess(event -> successes.inc());
            timeLimiter.getEventPublisher().onError(event -> failures.inc());
            timeLimiter.getEventPublisher().onTimeout(event -> timeouts.inc());
        }
    );
}
 
Example 3
@Test
public void test_incoming_versioned_connects() {
    embeddedChannel.writeInbound(new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv3_1_1).withClientIdentifier("clientID1").build());
    embeddedChannel.writeInbound(new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv3_1).withClientIdentifier("clientID2").build());
    embeddedChannel.writeInbound(new CONNECT.Mqtt5Builder().withClientIdentifier("clientID3").build());
    embeddedChannel.writeInbound(new CONNECT.Mqtt5Builder().withClientIdentifier("clientID4").build());

    final Counter totalIncoming = getCounter(HiveMQMetrics.INCOMING_CONNECT_COUNT.name());

    final Counter totalIncomingMessages = getCounter(HiveMQMetrics.INCOMING_MESSAGE_COUNT.name());

    assertEquals(4, totalIncoming.getCount());
    assertEquals(4, totalIncomingMessages.getCount());

    assertEquals(0, getCounter(HiveMQMetrics.OUTGOING_MESSAGE_COUNT.name()).getCount());
}
 
Example 4
Source Project: dcos-commons   Source File: MetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void taskStatuses() {
    Counter runningCounter = Metrics.getRegistry().counter("task_status.task_running");
    Counter lostCounter = Metrics.getRegistry().counter("task_status.task_lost");

    long runningVal = runningCounter.getCount();
    Metrics.record(Protos.TaskStatus.newBuilder()
            .setState(Protos.TaskState.TASK_RUNNING)
            .setTaskId(TestConstants.TASK_ID)
            .build());
    Assert.assertEquals(1, runningCounter.getCount() - runningVal);

    long lostVal = lostCounter.getCount();
    Metrics.record(Protos.TaskStatus.newBuilder()
            .setState(Protos.TaskState.TASK_LOST)
            .setTaskId(TestConstants.TASK_ID)
            .build());
    Assert.assertEquals(1, lostCounter.getCount() - lostVal);
}
 
Example 5
Source Project: semantic-metrics   Source File: SemanticMetricRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private void notifyListenerOfAddedMetric(
    final SemanticMetricRegistryListener listener, final Metric metric, final MetricId 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 if (metric instanceof DerivingMeter) {
        listener.onDerivingMeterAdded(name, (DerivingMeter) metric);
    } else {
        throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
    }
}
 
Example 6
Source Project: opencensus-java   Source File: DropWizardMetrics.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@code Metric} collected from {@link Counter}.
 *
 * @param dropwizardName the metric name.
 * @param counter the counter object to collect.
 * @return a {@code Metric}.
 */
private Metric collectCounter(String dropwizardName, Counter counter) {
  String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "counter");
  String metricDescription =
      DropWizardUtils.generateFullMetricDescription(dropwizardName, counter);

  MetricDescriptor metricDescriptor =
      MetricDescriptor.create(
          metricName,
          metricDescription,
          DEFAULT_UNIT,
          Type.GAUGE_INT64,
          Collections.<LabelKey>emptyList());
  TimeSeries timeSeries =
      TimeSeries.createWithOnePoint(
          Collections.<LabelValue>emptyList(),
          Point.create(Value.longValue(counter.getCount()), clock.now()),
          null);
  return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
}
 
Example 7
Source Project: quarks   Source File: MetricsBaseTest.java    License: Apache License 2.0 6 votes vote down vote up
private final void counter(String[] data) throws Exception {
    Topology t = newTopology();
    TStream<String> s = t.strings(data);
    s = Metrics.counter(s);

    waitUntilComplete(t, s, data);

    if (metricRegistry != null) {
        SortedMap<String, Counter> counters = metricRegistry.getCounters();
        assertEquals(1, counters.size());
        Collection<Counter> values = counters.values();
        for (Counter v : values) {
            assertEquals(data.length, v.getCount());
        }
    }
}
 
Example 8
@Test
public void verifyDefaultProviderChainIsUsed() throws Exception {
    System.setProperty("aws.accessKeyId", "fake");
    System.setProperty("aws.secretKey", "fake");
    try {
        CloudWatchReporterFactory factory = new CloudWatchReporterFactory();

        MetricRegistry registry = new MetricRegistry();
        Counter counter = registry.counter(MetricRegistry.name(this.getClass(), "test machine=123*"));
        counter.inc();
        factory.build(registry).report();
        // expecting a 403
    } finally {
        System.clearProperty("aws.accessKeyId");
        System.clearProperty("aws.secretKey");
    }
}
 
Example 9
Source Project: prebid-server-java   Source File: MetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyCreatesConfiguredCounterType(Consumer<Metrics> metricsConsumer) {
    final EnumMap<CounterType, Class<? extends Metric>> counterTypeClasses = new EnumMap<>(CounterType.class);
    counterTypeClasses.put(CounterType.counter, Counter.class);
    counterTypeClasses.put(CounterType.flushingCounter, ResettingCounter.class);
    counterTypeClasses.put(CounterType.meter, Meter.class);

    final SoftAssertions softly = new SoftAssertions();

    for (CounterType counterType : CounterType.values()) {
        // given
        metricRegistry = new MetricRegistry();

        // when
        metricsConsumer.accept(new Metrics(metricRegistry, CounterType.valueOf(counterType.name()),
                accountMetricsVerbosity, bidderCatalog));

        // then
        softly.assertThat(metricRegistry.getMetrics()).hasValueSatisfying(new Condition<>(
                metric -> metric.getClass() == counterTypeClasses.get(counterType),
                null));
    }

    softly.assertAll();
}
 
Example 10
Source Project: kylin   Source File: HadoopMetrics2ReporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void metrics2CycleIsNonDestructive() {
    metrics2Reporter.setDropwizardCounters(Collections.unmodifiableSortedMap(new TreeMap<String, Counter>()));
    metrics2Reporter.setDropwizardGauges(Collections.unmodifiableSortedMap(new TreeMap<String, Gauge>()));
    metrics2Reporter.setDropwizardHistograms(Collections.unmodifiableSortedMap(new TreeMap<String, Histogram>()));
    metrics2Reporter.setDropwizardMeters(Collections.unmodifiableSortedMap(new TreeMap<String, Meter>()));
    metrics2Reporter.setDropwizardTimers(Collections.unmodifiableSortedMap(new TreeMap<String, Timer>()));

    MetricsCollector collector = mock(MetricsCollector.class);
    MetricsRecordBuilder recordBuilder = mock(MetricsRecordBuilder.class);

    Mockito.when(collector.addRecord(recordName)).thenReturn(recordBuilder);

    metrics2Reporter.getMetrics(collector, true);
}
 
Example 11
Source Project: resilience4j   Source File: TimeLimiterMetricsPublisher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void publishMetrics(TimeLimiter timeLimiter) {

    String name = timeLimiter.getName();
    String successfulName = name(prefix, name, SUCCESSFUL);
    String failedName = name(prefix, name, FAILED);
    String timeoutName = name(prefix, name, TIMEOUT);

    Counter successes = metricRegistry.counter(successfulName);
    Counter failures = metricRegistry.counter(failedName);
    Counter timeouts = metricRegistry.counter(timeoutName);

    timeLimiter.getEventPublisher().onSuccess(event -> successes.inc());
    timeLimiter.getEventPublisher().onError(event -> failures.inc());
    timeLimiter.getEventPublisher().onTimeout(event -> timeouts.inc());

    List<String> metricNames = Arrays.asList(successfulName, failedName, timeoutName);
    metricsNameMap.put(name, new HashSet<>(metricNames));
}
 
Example 12
@Test
public void testInit() throws StageException {

  MetricRegistry metrics = metricAggregationProcessor.getMetrics();
  SortedMap<String, Timer> timers = metrics.getTimers();

  Assert.assertEquals(5, timers.size()); // 1 each for 4 stages, 1 for pipeline

  SortedMap<String, Counter> counters = metrics.getCounters();
  Assert.assertEquals(24, counters.size()); // 4 each for 4 stages, 5 for pipeline, one each for 3 output lanes

  SortedMap<String, Meter> meters = metrics.getMeters();
  Assert.assertEquals(24, meters.size()); // 4 each for 4 stages, 5 for pipeline, one each for 3 output lanes

  SortedMap<String, Histogram> histograms = metrics.getHistograms();
  Assert.assertEquals(20, histograms.size()); // 4 each for 4 stages, 4 for pipeline
}
 
Example 13
Source Project: signalfx-java   Source File: MetricMetadataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveMissing() {
    MetricRegistry metricRegistry = new MetricRegistry();
    MetricMetadata metadata = new MetricMetadataImpl();
    Counter counter = metricRegistry.counter("counter");
    assertFalse(metadata.removeMetric(counter, metricRegistry));
}
 
Example 14
Source Project: riposte   Source File: CodahaleMetricsCollector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T, U> void counted(@NotNull BiConsumer<T, U> bc, T arg1, U arg2, @NotNull String counterName, long delta) {
    final Counter counter = getNamedCounter(counterName);
    try {
        bc.accept(arg1, arg2);
    }
    finally {
        processCounter(counter, delta);
    }
}
 
Example 15
Source Project: sofa-jraft   Source File: StatsCollector.java    License: Apache License 2.0 5 votes vote down vote up
public long getRegionBytesWritten(final Region region, final boolean reset) {
    final Counter counter = KVMetrics.counter(KVMetricNames.REGION_BYTES_WRITTEN, String.valueOf(region.getId()));
    final long value = counter.getCount();
    if (reset) {
        counter.dec(value);
    }
    return value;
}
 
Example 16
Source Project: vertx-dropwizard-metrics   Source File: AbstractMetrics.java    License: Apache License 2.0 5 votes vote down vote up
protected Counter counter(String... names) {
  try {
    return registry.counter(nameOf(names));
  } catch (Exception e) {
    return new Counter();
  }
}
 
Example 17
@Test
@InSequence(1)
public void countedMethodNotCalledYet() {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Make sure that the counter hasn't been called yet
    assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
}
 
Example 18
Source Project: metrics-cdi   Source File: CountedMethodBeanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(4)
public void removeCounterFromRegistry() {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Remove the counter from metrics registry
    registry.remove(COUNTER_NAME);

    try {
        // Call the counted method and assert an exception is thrown
        bean.countedMethod(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return null;
            }
        });
    } catch (Exception cause) {
        assertThat(cause, is(instanceOf(IllegalStateException.class)));
        assertThat(cause.getMessage(), is(equalTo("No counter with name [" + COUNTER_NAME + "] found in registry [" + registry + "]")));
        // Make sure that the counter hasn't been called
        assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example 19
Source Project: metrics-cdi   Source File: CountedMethodBeanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void countedMethodNotCalledYet() {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Make sure that the counter hasn't been called yet
    assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
}
 
Example 20
Source Project: datacollector   Source File: TestMetricsConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateStageCounter() {
  MetricRegistry metrics = new MetricRegistry();
  MetricsConfigurator.createStageCounter(metrics, "a", "name", "0");
  MetricsConfigurator.createStageCounter(metrics, "a", "name", "0");

  // There should be only one metric object
  Assert.assertEquals(1, metrics.getCounters().size());
  Map.Entry<String, Counter> entry = metrics.getCounters().entrySet().iterator().next();
  Assert.assertEquals("a.counter", entry.getKey());
}
 
Example 21
Source Project: incubator-gobblin   Source File: TaskState.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update record-level metrics.
 *
 * @param recordsWritten number of records written by the writer
 * @param branchIndex fork branch index
 *
 * @deprecated see {@link org.apache.gobblin.instrumented.writer.InstrumentedDataWriterBase}.
 */
public synchronized void updateRecordMetrics(long recordsWritten, int branchIndex) {
  TaskMetrics metrics = TaskMetrics.get(this);
  // chopping branch index from metric name
  // String forkBranchId = ForkOperatorUtils.getForkId(this.taskId, branchIndex);
  String forkBranchId = TaskMetrics.taskInstanceRemoved(this.taskId);

  Counter taskRecordCounter = metrics.getCounter(MetricGroup.TASK.name(), forkBranchId, RECORDS);
  long inc = recordsWritten - taskRecordCounter.getCount();
  taskRecordCounter.inc(inc);
  metrics.getMeter(MetricGroup.TASK.name(), forkBranchId, RECORDS_PER_SECOND).mark(inc);
  metrics.getCounter(MetricGroup.JOB.name(), this.jobId, RECORDS).inc(inc);
  metrics.getMeter(MetricGroup.JOB.name(), this.jobId, RECORDS_PER_SECOND).mark(inc);
}
 
Example 22
Source Project: riposte   Source File: CodahaleMetricsCollector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T, U, R> R counted(@NotNull BiFunction<T, U, R> bf, T arg1, U arg2, @NotNull String counterName, long delta) {
    final Counter counter = getNamedCounter(counterName);
    try {
        return bf.apply(arg1, arg2);
    }
    finally {
        processCounter(counter, delta);
    }
}
 
Example 23
Source Project: incubator-gobblin   Source File: MetricTypeFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void matchesTest() {
  Counter counter = mock(Counter.class);
  Gauge gauge = mock(Gauge.class);
  Histogram histogram = mock(Histogram.class);
  Meter meter = mock(Meter.class);
  Timer timer = mock(Timer.class);

  MetricTypeFilter noMetricTypeFilter = new MetricTypeFilter(null);
  Assert.assertTrue(noMetricTypeFilter.matches("", counter));
  Assert.assertTrue(noMetricTypeFilter.matches("", gauge));
  Assert.assertTrue(noMetricTypeFilter.matches("", histogram));
  Assert.assertTrue(noMetricTypeFilter.matches("", meter));
  Assert.assertTrue(noMetricTypeFilter.matches("", timer));

  MetricTypeFilter counterMetricTypeFilter = new MetricTypeFilter("COUNTER");
  Assert.assertTrue(counterMetricTypeFilter.matches("", counter));
  Assert.assertFalse(counterMetricTypeFilter.matches("", gauge));
  Assert.assertFalse(counterMetricTypeFilter.matches("", histogram));
  Assert.assertFalse(counterMetricTypeFilter.matches("", meter));
  Assert.assertFalse(counterMetricTypeFilter.matches("", timer));

  MetricTypeFilter allMetricTypeFilter = new MetricTypeFilter("COUNTER,GAUGE,HISTOGRAM,METER,TIMER");
  Assert.assertTrue(allMetricTypeFilter.matches("", counter));
  Assert.assertTrue(allMetricTypeFilter.matches("", gauge));
  Assert.assertTrue(allMetricTypeFilter.matches("", histogram));
  Assert.assertTrue(allMetricTypeFilter.matches("", meter));
  Assert.assertTrue(allMetricTypeFilter.matches("", timer));
}
 
Example 24
Source Project: chassis   Source File: MetricsCloudWatchReporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public void report(
        SortedMap<String, Gauge> gauges,
        SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms,
        SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

    logger.info("Starting metrics publishing to AWS CloudWatch.");

    LinkedList<PutMetricDataRequest> requests = new LinkedList<>();

    addMetricData(gauges, counters, histograms, meters, timers, requests, new Date());

    if (requests.isEmpty()) {
        logger.debug("No metric data to send to AWS.");
        return;
    }

    for (PutMetricDataRequest request : requests) {
        try {
            for (MetricDatum datum : request.getMetricData()) {
                logger.debug("Sending metric " + datum);
            }
            cloudWatch.putMetricData(request);
        } catch (Exception e) {
            logger.error("Failed to log metrics to CloudWatch discarding metrics for this attempt...",e);
            return;
        }
    }
    logger.info("Finished metrics publishing to AWS CloudWatch.");
}
 
Example 25
Source Project: jstorm   Source File: AsmCounter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void updateSnapshot(int window) {
    Counter counter = counterMap.get(window);
    if (counter != null) {
        AsmSnapshot snapshot = new AsmCounterSnapshot().setValue(counter.getCount())
                .setTs(System.currentTimeMillis()).setMetricId(metricId);
        snapshots.put(window, snapshot);
    }
}
 
Example 26
Source Project: onos   Source File: PacketStatsUiMessageHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(ObjectNode payload) {
    MetricsService service = get(MetricsService.class);
    Map<String, Counter> counters = service.getCounters(filter);
    Counter vlanCounter = counters.get("packetStatisticsComponent.vlanFeature.vlanPC");
    long vlanCount = vlanCounter.getCount();
    ObjectNode vlanJson = objectNode();
    vlanJson.put("VlanCounter", vlanCount);
    log.info("Received VLAN Request");
    sendMessage(VLAN_RESP, vlanJson);
}
 
Example 27
Source Project: onos   Source File: PacketStatsUiMessageHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(ObjectNode payload) {
    MetricsService service = get(MetricsService.class);
    Map<String, Counter> counters = service.getCounters(filter);
    Counter pimCounter =  counters.get("packetStatisticsComponent.pimFeature.pimPC");
    long pimCount = pimCounter.getCount();
    ObjectNode pimJson = objectNode();
    pimJson.put("PimCounter", pimCount);
    log.info("Received PIM Request");
    sendMessage(PIM_RESP, pimJson);
}
 
Example 28
Source Project: lucene-solr   Source File: MetricUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert a single instance of metric into a map or flattened object.
 * @param n metric name
 * @param metric metric instance
 * @param propertyFilter limit what properties of a metric are returned
 * @param skipHistograms discard any {@link Histogram}-s and histogram parts of {@link Timer}-s.
 * @param skipAggregateValues discard internal values of {@link AggregateMetric}-s.
 * @param compact use compact representation for counters and gauges.
 * @param simple use simplified representation for complex metrics - instead of a (name, map)
 *             only the selected (name "." key, value) pairs will be produced.
 * @param consumer consumer that accepts produced objects
 */
public static void convertMetric(String n, Metric metric, PropertyFilter propertyFilter, boolean skipHistograms, boolean skipAggregateValues,
                            boolean compact, boolean simple, String separator, BiConsumer<String, Object> consumer) {
  if (metric instanceof Counter) {
    Counter counter = (Counter) metric;
    convertCounter(n, counter, propertyFilter, compact, consumer);
  } else if (metric instanceof Gauge) {
    @SuppressWarnings({"rawtypes"})
    Gauge gauge = (Gauge) metric;
    try {
      convertGauge(n, gauge, propertyFilter, simple, compact, separator, consumer);
    } catch (InternalError ie) {
      if (n.startsWith("memory.") && ie.getMessage().contains("Memory Pool not found")) {
        log.warn("Error converting gauge '{}', possible JDK bug: SOLR-10362", n, ie);
        consumer.accept(n, null);
      } else {
        throw ie;
      }
    }
  } else if (metric instanceof Meter) {
    Meter meter = (Meter) metric;
    convertMeter(n, meter, propertyFilter, simple, separator, consumer);
  } else if (metric instanceof Timer) {
    Timer timer = (Timer) metric;
    convertTimer(n, timer, propertyFilter, skipHistograms, simple, separator, consumer);
  } else if (metric instanceof Histogram) {
    if (!skipHistograms) {
      Histogram histogram = (Histogram) metric;
      convertHistogram(n, histogram, propertyFilter, simple, separator, consumer);
    }
  } else if (metric instanceof AggregateMetric) {
    convertAggregateMetric(n, (AggregateMetric)metric, propertyFilter, skipAggregateValues, simple, separator, consumer);
  }
}
 
Example 29
public Counter getCounter(final String meterName) {
    final Set<Map.Entry<String, Counter>> entries = metricRegistry.getCounters(new MetricFilter() {
        @Override
        public boolean matches(final String name, final Metric metric) {
            return name.equals(meterName);
        }
    }).entrySet();
    Preconditions.checkState(entries.size() == 1);
    return entries.iterator().next().getValue();
}
 
Example 30
@Test
public void testInitialization() throws Exception {
   /* Test each default metric to ensure that it is initialized to 0l */
   CassandraAuditor.DEFAULT_METRICS_COUNTERS.stream()
      .forEach(s -> assertEquals(0L, 
            ((Counter) METRICS.getMetrics().get(String.format("%s.%s",CassandraAuditor.SERVICE_NAME,s))).getCount()));

}