Java 类com.codahale.metrics.Counter 实例源码

项目:verify-hub    文件:AttributeQueryRequestRunnable.java   
public AttributeQueryRequestRunnable(
        SessionId sessionId,
        AttributeQueryContainerDto attributeQueryContainerDto,
        ExecuteAttributeQueryRequest executeAttributeQueryRequest,
        @MatchingServiceRequestExecutorBacklog Counter counter,
        TimeoutEvaluator timeoutEvaluator,
        HubMatchingServiceResponseReceiverProxy hubMatchingServiceResponseReceiverProxy,
        ServiceInfoConfiguration serviceInfo,
        EventSinkProxy eventSinkProxy) {
    this.counter = counter;
    this.sessionId = sessionId;
    this.attributeQueryContainerDto = attributeQueryContainerDto;
    this.executeAttributeQueryRequest = executeAttributeQueryRequest;
    this.timeoutEvaluator = timeoutEvaluator;
    this.hubMatchingServiceResponseReceiverProxy = hubMatchingServiceResponseReceiverProxy;
    this.serviceInfo = serviceInfo;
    this.eventSinkProxy = eventSinkProxy;
    this.counter.inc();
}
项目:jboot    文件:JbootMetricConterAopInterceptor.java   
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {

    EnableMetricCounter annotation = methodInvocation.getThis().getClass().getAnnotation(EnableMetricCounter.class);

    String name = StringUtils.isBlank(annotation.value())
            ? methodInvocation.getThis().getClass().getName() + "." + methodInvocation.getMethod().getName()
            : annotation.value();

    Counter counter = Jboot.me().getMetric().counter(name);
    try {
        counter.inc();
        return methodInvocation.proceed();
    } finally {
        counter.dec();
    }

}
项目:ja-micro    文件:JsonHandlerTest.java   
@Before
public void setup() throws RpcCallException {
    handlerDictionary = new MethodHandlerDictionary();
    handlerDictionary.put("a", null);
    ServiceMethodHandlerUnderTest mockHandlerThrowsRpcCallEx = new ServiceMethodHandlerUnderTest();

    handlerDictionary.put("jsonRpcWithException", mockHandlerThrowsRpcCallEx);

    metricRegistry = mock(MetricRegistry.class);
    when(metricRegistry.counter(anyString())).thenReturn(mock(Counter.class));
    when(metricRegistry.timer(anyString())).thenReturn(mock(Timer.class));

    handlerMetrics = mock(RpcHandlerMetrics.class);
    when(handlerMetrics.getMethodTimer(any(), any(), any())).thenReturn(mock(GoTimer.class));

    servlet = new JsonHandler(handlerDictionary, metricRegistry, handlerMetrics, new ServiceProperties(), null);
}
项目:dropwizard-influxdb-reporter    文件:InfluxDbMeasurementReporter.java   
@Override
public void report(final SortedMap<String, Gauge> gauges,
                   final SortedMap<String, Counter> counters,
                   final SortedMap<String, Histogram> histograms,
                   final SortedMap<String, Meter> meters,
                   final SortedMap<String, Timer> timers) {
  final long timestamp = clock.instant().toEpochMilli();

  final ImmutableList<InfluxDbMeasurement> influxDbMeasurements = ImmutableList.<InfluxDbMeasurement>builder()
    .addAll(transformer.fromGauges(gauges, timestamp))
    .addAll(transformer.fromCounters(counters, timestamp))
    .addAll(transformer.fromHistograms(histograms, timestamp))
    .addAll(transformer.fromMeters(meters, timestamp))
    .addAll(transformer.fromTimers(timers, timestamp))
    .build();

  sender.send(influxDbMeasurements);
}
项目:dropwizard-influxdb-reporter    文件:DropwizardTransformerTest.java   
@Test
public void testFromCounters_Grouped() {
  final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
  final DropwizardTransformer transformer = transformerWithParser(parser, true);

  final List<Counter> counters = ImmutableList.of(new Counter(), new Counter());
  counters.get(0).inc(15L);
  counters.get(1).inc(6L);

  final Map<String, Counter> cMap = ImmutableMap.of(
    "some.stuff.queued", counters.get(0),
    "some.stuff.processed", counters.get(1)
  );

  when(parser.parse("some.stuff")).thenReturn(
    DropwizardMeasurement.create("some.stuff", MEASUREMENT_TAGS, Optional.empty())
  );

  final List<InfluxDbMeasurement> expected = ImmutableList.of(
    InfluxDbMeasurement.create("some.stuff", ALL_TAGS, ImmutableMap.of("queued", "15i", "processed", "6i"), 90210L)
  );

  final List<InfluxDbMeasurement> measurements = transformer.fromCounters(cMap, 90210L);
  assertEquals("should group counters by tags and prefix", expected, measurements);
}
项目:athena    文件:MetricCodecTest.java   
/**
 * Tests encoding of a Metric object.
 */
@Test
public void testMetricEncode() {
    Counter counter = new Counter();
    Meter meter = new Meter();
    Timer timer = new Timer();

    counter.inc();
    meter.mark();
    timer.update(1, TimeUnit.MILLISECONDS);

    ObjectNode counterJson = metricCodec.encode(counter, context);
    assertThat(counterJson.get("counter"), matchesMetric(counter));

    ObjectNode meterJson = metricCodec.encode(meter, context);
    assertThat(meterJson.get("meter"), matchesMetric(meter));

    ObjectNode timerJson = metricCodec.encode(timer, context);
    assertThat(timerJson.get("timer"), matchesMetric(timer));
}
项目:lambda-monitoring    文件:LambdaMetricSetTest.java   
@Test
public void testMetricSetAnnotations() {
    Map<String, Metric> metrics = new TestLambdaMetricSet().getMetrics();

    // Prove that the defaults fall back to the classname as namespace, and field name as metric name.
    assertThat(metrics.get("io.symphonia.lambda.metrics.LambdaMetricSetTest.TestLambdaMetricSet/fooCounter"),
            instanceOf(Counter.class));

    // Prove we can override the name via the annotation
    assertThat(metrics.get("io.symphonia.lambda.metrics.LambdaMetricSetTest.TestLambdaMetricSet/myBarCounter"),
            instanceOf(Counter.class));

    // Prove we can override the namespace via the annotation
    assertThat(metrics.get("test.namespace/bazCounter"), instanceOf(Counter.class));

    // Prove we can override the namespace and name via the annotation
    assertThat(metrics.get("test.namespace/myBingCounter"), instanceOf(Counter.class));

    // Prove we can override the namespace via a class-level annotation
    assertThat(new NamespaceTestLambdaMetricSet().getMetrics().get("test.namespace/fooCounter"),
            instanceOf(Counter.class));
}
项目:semantic-metrics    文件:MetricTypesExample.java   
/**
 * A counter is just a gauge for an AtomicLong instance. You can increment or decrement its
 * value. We want a more efficient way of measuring the pending job in a queue
 */
private static void reportCounter() {
    // Create or fetch (if it is already created) the metric.
    final Counter counter = registry.counter(APP_PREFIX.tagged("what", "job-count"));

    // Somewhere in your code where you are adding new jobs to the queue you increment the
    // counter as well
    counter.inc();

    // Oh look! Another job!
    counter.inc();

    // Somewhere in your code the job is going to be removed from the queue you decrement the
    // counter
    counter.dec();

    // That's it! The rest will be automatically done inside semantic metrics library. The
    // reported measurements will be kept in the registry.
    // Every time the reporter wants to report, the current value of the counter will be read
    // and
    // a datapoint will be created and reported.
}
项目:ugc-bot-redux    文件:MetricsService.java   
private void initDiscordHealthChecks() {
    healthCheckRegistry.register(MetricNames.HEALTH_DISCORD_WS, new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            Counter restartCounter = metricRegistry.counter(MetricNames.DISCORD_WS_RESTARTS);
            Optional<Incident> incident = incidentService.getLastIncidentFromGroup(IncidentService.DISCORD_RESTART);
            ZonedDateTime time = incident.isPresent() ? incident.get().getCreatedDate() : null;
            String reason = incident.isPresent() ? incident.get().getName() : null;
            long restarts = restartCounter.getCount();
            if (restarts > 0) {
                return Result.unhealthy(String.format("%d restart%s, last one on %s (%s)",
                    restarts, restarts == 1 ? "" : "s", time, reason));
            } else {
                return Result.healthy("OK");
            }
        }
    });
}
项目:dropwizard-hadoop-metrics2    文件:HadoopMetrics2ReporterTest.java   
@Test public void testCounterReporting() {
  final Counter counter = new Counter();

  TreeMap<String,Counter> counters = new TreeMap<>();
  counters.put("my_counter", counter);
  // Add the metrics objects to the internal "queues" by hand
  metrics2Reporter.setDropwizardCounters(counters);

  // Set some values
  counter.inc(5L);

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

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

  metrics2Reporter.getMetrics(collector, true);

  verify(recordBuilder).addCounter(Interns.info("my_counter", ""), 5L);
  verifyRecordBuilderUnits(recordBuilder);

  // Should not be the same instance we gave before. Our map should have gotten swapped out.
  assertTrue("Should not be the same map instance after collection",
      counters != metrics2Reporter.getDropwizardCounters());
}
项目:metrics-circonus    文件:CirconusReporterTest.java   
@Test
public void reportsWithCallback() throws Exception {
  List<String> dynamicTags = new ArrayList<String>();
  dynamicTags.add("status:active");
  dynamicTags.add("speed:29");

  when(callback.getTags()).thenReturn(dynamicTags);

  final Counter counter = mock(Counter.class);
  when(counter.getCount()).thenReturn(100L);

  reporterWithCallback.report(this.<Gauge>map(),
          this.<Counter>map("counter", counter),
          this.<Histogram>map(),
          this.<Meter>map(),
          this.<Timer>map());

  verify(request).addGauge(new CirconusGauge("counter", 100L, timestamp, HOST, dynamicTags));
}
项目:hawkular-dropwizard-reporter    文件:HawkularReporterITest.java   
@Test
public void shouldReportCounter() throws IOException {
    String metricName = randomName();
    HawkularReporter reporter = HawkularReporter.builder(registry, defaultTenant)
            .basicAuth(USERNAME, PASSWORD)
            .build();

    final Counter counter = registry.counter(metricName);
    counter.inc(5);
    reporter.report();

    HawkularHttpResponse response = defaultClient.readMetric("counters", metricName);

    assertThat(response.getResponseCode()).isEqualTo(200);
    JSONArray result = new JSONArray(response.getContent());
    assertThat(result).extracting(intExtractor).containsExactly(5);

    counter.inc(8);
    reporter.report();

    response = defaultClient.readMetric("counters", metricName);

    assertThat(response.getResponseCode()).isEqualTo(200);
    result = new JSONArray(response.getContent());
    assertThat(result).extracting(intExtractor).containsExactly(13, 5);
}
项目:Camel    文件:CounterProducer.java   
@Override
protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception {
    Message in = exchange.getIn();
    Counter counter = registry.counter(metricsName);
    Long increment = endpoint.getIncrement();
    Long decrement = endpoint.getDecrement();
    Long finalIncrement = getLongHeader(in, HEADER_COUNTER_INCREMENT, increment);
    Long finalDecrement = getLongHeader(in, HEADER_COUNTER_DECREMENT, decrement);
    if (finalIncrement != null) {
        counter.inc(finalIncrement);
    } else if (finalDecrement != null) {
        counter.dec(finalDecrement);
    } else {
        counter.inc();
    }
}
项目:replicator    文件:HBaseApplier.java   
/**
 * HBaseApplier constructor.
 * @param config config
 * @param mainProgressIndicator mainProgressIndicator
 * @param validationService validationService
 */
public HBaseApplier(
    com.booking.replication.Configuration config,
    Counter mainProgressIndicator,
    ValidationService validationService
) {
    configuration = config;

    hbaseApplierWriter =
        new HBaseApplierWriter(
                POOL_SIZE,
                configuration,
                mainProgressIndicator,
                validationService
        );

    hbaseSchemaManager = new HBaseSchemaManager(
            configuration.getHBaseQuorum(), configuration.isDryRunMode());
}
项目:riposte    文件:SignalFxAwareCodahaleMetricsCollectorTest.java   
@DataProvider(value = {
    "null",
    "0",
    "1",
    "2"
}, splitBy = "\\|")
@Test
public void getNamedCounter_with_varargs_dimensions_creates_dimensioned_counter_using_sfx_mechanisms(
    Integer numDimensions
) {
    // given
    String counterName = UUID.randomUUID().toString();
    Pair<String, String>[] varargDims = generateVarargDimensions(numDimensions);
    List<Pair<String, String>> dimsAsList = (varargDims == null) ? null : Arrays.asList(varargDims);

    // when
    Counter result = sfxImpl.getNamedCounter(counterName, varargDims);

    // then
    verifyMetricCreation(MetricBuilder.COUNTERS, counterTaggerMock, counterName, dimsAsList, counterMock, result);
}
项目:monitoring-center    文件:GraphiteMetricFormatter.java   
public String format(SortedMap<String, Metric> metricsByNames) {
    Preconditions.checkNotNull(metricsByNames);

    final long timestamp = System.nanoTime() / 1000;

    StringBuilder outputBuilder = new StringBuilder();
    for (Map.Entry<String, Metric> entry : metricsByNames.entrySet()) {
        String metricOutput = null;
        if (Counter.class.isInstance(entry.getValue())) {
            metricOutput = formatCounter(entry.getKey(), Counter.class.cast(entry.getValue()), timestamp);
        } else if (Gauge.class.isInstance(entry.getValue())) {
            metricOutput = formatGauge(entry.getKey(), Gauge.class.cast(entry.getValue()), timestamp);
        } else if (Timer.class.isInstance(entry.getValue())) {
            metricOutput = formatTimer(entry.getKey(), Timer.class.cast(entry.getValue()), timestamp);
        } else if (Meter.class.isInstance(entry.getValue())) {
            metricOutput = formatMetered(entry.getKey(), Meter.class.cast(entry.getValue()), timestamp);
        } else if (Histogram.class.isInstance(entry.getValue())) {
            metricOutput = formatHistogram(entry.getKey(), Histogram.class.cast(entry.getValue()), timestamp);
        }

        if (metricOutput != null) {
            outputBuilder.append(metricOutput);
        }
    }
    return outputBuilder.toString();
}
项目:mongoose-base    文件:CustomMetricRegistry.java   
private void notifyListenerOfAddedMetric(
    final MetricRegistryListener listener, final Metric metric, final String 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("Unsupported metric type: " + metric.getClass());
    }
}
项目:hawkular-dropwizard-reporter    文件:HawkularReporterTest.java   
@Test
public void shouldReportSimpleCounterWithoutTag() {
    HawkularReporter reporter = HawkularReporter.builder(registry, "unit-test").useHttpClient(uri -> client).build();

    final Counter counter = registry.counter("my.counter");
    counter.inc();
    reporter.report();

    assertThat(client.getMetricsRestCalls()).hasSize(1);
    JSONObject metrics = new JSONObject(client.getMetricsRestCalls().get(0));
    assertThat(metrics.keySet()).containsExactly("counters");
    JSONArray json = metrics.getJSONArray("counters");
    assertThat(json).extracting(idFromRoot).containsExactly("my.counter");
    assertThat(json).extracting(valueFromRoot).containsExactly(1);
    assertThat(client.getTagsRestCalls()).isEmpty();
}
项目:verify-hub    文件:AttributeQueryRequestRunnableFactory.java   
public Runnable create(final SessionId sessionId, final AttributeQueryContainerDto attributeQueryContainerDto) {
    return new AttributeQueryRequestRunnable(
            sessionId,
            attributeQueryContainerDto,
            injector.getInstance(ExecuteAttributeQueryRequest.class),
            injector.getInstance(Key.get(Counter.class, MatchingServiceRequestExecutorBacklog.class)),
            injector.getInstance(TimeoutEvaluator.class),
            injector.getInstance(HubMatchingServiceResponseReceiverProxy.class),
            injector.getInstance(ServiceInfoConfiguration.class),
            injector.getInstance(EventSinkProxy.class)
    );
}
项目:JInsight    文件:ApptuitReporter.java   
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
    SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
    SortedMap<String, Timer> timers) {

  DataPointCollector collector = new DataPointCollector(System.currentTimeMillis() / 1000);

  buildReportTimer.time(() -> {
    debug("################");

    debug(">>>>>>>> Guages <<<<<<<<<");
    gauges.forEach(collector::collectGauge);
    debug(">>>>>>>> Counters <<<<<<<<<");
    counters.forEach(collector::collectCounter);
    debug(">>>>>>>> Histograms <<<<<<<<<");
    histograms.forEach(collector::collectHistogram);
    debug(">>>>>>>> Meters <<<<<<<<<");
    meters.forEach(collector::collectMeter);
    debug(">>>>>>>> Timers <<<<<<<<<");
    timers.forEach(collector::collectTimer);

    debug("################");
  });

  sendReportTimer.time(() -> {
    Collection<DataPoint> dataPoints = collector.dataPoints;
    dataPointsReporter.put(dataPoints);
    //dataPoints.forEach(System.out::println);
  });
}
项目:JInsight    文件:ApptuitReporterTest.java   
@Test
public void testReporter() throws Exception {

  UUID uuid = UUID.randomUUID();
  String metricName = "ApptuitReporterTest.testReporter." + uuid.toString();
  int expectedCount=2;

  AtomicBoolean foundMetric = new AtomicBoolean(false);
  AtomicInteger lastSeenCount = new AtomicInteger(-1);
  PutListener listener = dataPoints -> {
    dataPoints.forEach(dataPoint -> {
      if (!metricName.equals(dataPoint.getMetric()))
        return;
      int i = dataPoint.getValue().intValue();
      lastSeenCount.set(i);
      if (i != 2)
        return;
      foundMetric.set(true);
    });
  };
  putClient.addPutListener(listener);

  Counter counter = registry.counter(metricName);
  counter.inc();
  counter.inc();


  await().atMost(period*3, TimeUnit.SECONDS).untilTrue(foundMetric);
  putClient.removePutListener(listener);

  assertEquals(expectedCount, lastSeenCount.intValue());
}
项目:dropwizard-influxdb-reporter    文件:DropwizardTransformerTest.java   
@Test
public void testFromCounters_Ungrouped() {
  final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
  final DropwizardTransformer transformer = transformerWithParser(parser, false);

  final List<Counter> counters = ImmutableList.of(new Counter(), new Counter());
  counters.get(0).inc(15L);
  counters.get(1).inc(6L);

  final Map<String, Counter> cMap = ImmutableMap.of(
    "some.stuff.queued", counters.get(0),
    "some.stuff.processed", counters.get(1)
  );

  when(parser.parse("some.stuff.queued")).thenReturn(
    DropwizardMeasurement.create("some.stuff.queued", MEASUREMENT_TAGS, Optional.empty())
  );

  when(parser.parse("some.stuff.processed")).thenReturn(
    DropwizardMeasurement.create("some.stuff.processed", MEASUREMENT_TAGS, Optional.empty())
  );

  final List<InfluxDbMeasurement> expected = ImmutableList.of(
    InfluxDbMeasurement.create("some.stuff.queued", ALL_TAGS, ImmutableMap.of("count", "15i"), 90210L),
    InfluxDbMeasurement.create("some.stuff.processed", ALL_TAGS, ImmutableMap.of("count", "6i"), 90210L)
  );

  final List<InfluxDbMeasurement> measurements = transformer.fromCounters(cMap, 90210L);
  assertEquals("should not group counter measurements", expected, measurements);
}
项目:r2cloud    文件:RRD4JReporterTest.java   
@Test
public void testCounterResumeFromLast() throws Exception {
    String name = UUID.randomUUID().toString();
    Counter c = registry.counter(name);
    c.inc(2);
    report(name, c);
    // simulate restart
    reporter.close();
    registry.remove(name);

    c = registry.counter(name);
    c.inc(1);
    Thread.sleep(1000);
    report(name, c);

    File f = new File(basepath, name + ".rrd");
    assertTrue(f.exists());
    RrdDb db = new RrdDb(f.getAbsolutePath());
    assertEquals(3.0, db.getLastDatasourceValue("data"), 0.0);
    db.close();
    c.inc(1);
    Thread.sleep(1000);
    report(name, c);

    db = new RrdDb(f.getAbsolutePath());
    assertEquals(4.0, db.getLastDatasourceValue("data"), 0.0);
    db.close();
}
项目:r2cloud    文件:RRD4JReporterTest.java   
@Test
public void testSimpleCounter() throws Exception {
    String name = UUID.randomUUID().toString();
    Counter c = registry.counter(name);
    c.inc();
    report(name, c);

    File f = new File(basepath, name + ".rrd");
    assertTrue(f.exists());
    RrdDb db = new RrdDb(f.getAbsolutePath());
    assertEquals(1.0, db.getLastDatasourceValue("data"), 0.0);
    db.close();
}
项目:Lagerta    文件:AdvancedReporter.java   
@Override public void report(
    SortedMap<String, Gauge> gauges,
    SortedMap<String, Counter> counters,
    SortedMap<String, Histogram> histograms,
    SortedMap<String, Meter> meters,
    SortedMap<String, Timer> timers
) {
    if (firstReportTime < 0) {
        firstReportTime = System.currentTimeMillis();
    }
    if (System.currentTimeMillis() - firstReportTime < warmupDuration) {
        return;
    }
    reportStatistics(gauges, counters, histograms, meters, timers);
}
项目:Lagerta    文件:AdvancedReporter.java   
protected abstract void reportStatistics(
    SortedMap<String, Gauge> gauges,
    SortedMap<String, Counter> counters,
    SortedMap<String, Histogram> histograms,
    SortedMap<String, Meter> meters,
    SortedMap<String, Timer> timers
);
项目:hadoop    文件:SLSWebApp.java   
public SLSWebApp(ResourceSchedulerWrapper wrapper, int metricsAddressPort) {
  this.wrapper = wrapper;
  metrics = wrapper.getMetrics();
  handleOperTimecostHistogramMap =
          new HashMap<SchedulerEventType, Histogram>();
  queueAllocatedMemoryCounterMap = new HashMap<String, Counter>();
  queueAllocatedVCoresCounterMap = new HashMap<String, Counter>();
  schedulerMetrics = wrapper.getSchedulerMetrics();
  port = metricsAddressPort;
}
项目:dropwizard-prometheus    文件:DropwizardMetricsExporter.java   
/**
 * Export counter as Prometheus <a href="https://prometheus.io/docs/concepts/metric_types/#gauge">Gauge</a>.
 */
public void writeCounter(String dropwizardName, Counter counter) throws IOException {
    String name = sanitizeMetricName(dropwizardName);
    writer.writeHelp(name, getHelpMessage(dropwizardName, counter));
    writer.writeType(name, MetricType.GAUGE);
    writer.writeSample(name, emptyMap(), counter.getCount());
}
项目:athena    文件:MetricsResourceTest.java   
/**
 * Tests GetAllMetrics method.
 */
@Test
public void testGetAllMetrics() {
    Counter onosCounter = new Counter();
    onosCounter.inc();

    Meter onosMeter = new Meter();
    onosMeter.mark();

    Timer onosTimer = new Timer();
    onosTimer.update(1, TimeUnit.MILLISECONDS);

    ImmutableMap<String, Metric> metrics =
            new ImmutableMap.Builder<String, Metric>()
                    .put("onosCounter", onosCounter)
                    .put("onosMeter", onosMeter)
                    .put("onosTimer", onosTimer)
                    .build();

    expect(mockMetricsService.getMetrics())
            .andReturn(metrics)
            .anyTimes();

    replay(mockMetricsService);

    WebTarget wt = target();
    String response = wt.path("metrics").request().get(String.class);
    assertThat(response, containsString("{\"metrics\":["));

    JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    JsonArray jsonMetrics = result.get("metrics").asArray();
    assertThat(jsonMetrics, notNullValue());
    assertThat(jsonMetrics.size(), is(3));

    assertTrue(matchesMetric(metrics.get("onosCounter")).matchesSafely(jsonMetrics.get(0).asObject()));
    assertTrue(matchesMetric(metrics.get("onosMeter")).matchesSafely(jsonMetrics.get(1).asObject()));
    assertTrue(matchesMetric(metrics.get("onosTimer")).matchesSafely(jsonMetrics.get(2).asObject()));
}
项目:athena    文件:MetricsListCommand.java   
/**
 * Creates a json object for a certain metric.
 *
 * @param metric metric object
 * @return json object
 */
private ObjectNode json(Metric metric) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode objectNode = mapper.createObjectNode();
    ObjectNode dataNode = mapper.createObjectNode();

    if (metric instanceof Counter) {
        dataNode.put(COUNTER, ((Counter) metric).getCount());
        objectNode.set(COUNTER, dataNode);
    } else if (metric instanceof Gauge) {
        objectNode.put(VALUE, ((Gauge) metric).getValue().toString());
        objectNode.set(GAUGE, dataNode);
    } else if (metric instanceof Meter) {
        dataNode.put(COUNTER, ((Meter) metric).getCount());
        dataNode.put(MEAN_RATE, ((Meter) metric).getMeanRate());
        dataNode.put(ONE_MIN_RATE, ((Meter) metric).getOneMinuteRate());
        dataNode.put(FIVE_MIN_RATE, ((Meter) metric).getFiveMinuteRate());
        dataNode.put(FIFT_MIN_RATE, ((Meter) metric).getFifteenMinuteRate());
        objectNode.set(METER, dataNode);
    } else if (metric instanceof Histogram) {
        dataNode.put(COUNTER, ((Histogram) metric).getCount());
        dataNode.put(MEAN, ((Histogram) metric).getSnapshot().getMean());
        dataNode.put(MIN, ((Histogram) metric).getSnapshot().getMin());
        dataNode.put(MAX, ((Histogram) metric).getSnapshot().getMax());
        dataNode.put(STDDEV, ((Histogram) metric).getSnapshot().getStdDev());
        objectNode.set(HISTOGRAM, dataNode);
    } else if (metric instanceof Timer) {
        dataNode.put(COUNTER, ((Timer) metric).getCount());
        dataNode.put(MEAN_RATE, ((Timer) metric).getMeanRate());
        dataNode.put(ONE_MIN_RATE, ((Timer) metric).getOneMinuteRate());
        dataNode.put(FIVE_MIN_RATE, ((Timer) metric).getFiveMinuteRate());
        dataNode.put(FIFT_MIN_RATE, ((Timer) metric).getFifteenMinuteRate());
        dataNode.put(MEAN, nanoToMs(((Timer) metric).getSnapshot().getMean()));
        dataNode.put(MIN, nanoToMs(((Timer) metric).getSnapshot().getMin()));
        dataNode.put(MAX, nanoToMs(((Timer) metric).getSnapshot().getMax()));
        dataNode.put(STDDEV, nanoToMs(((Timer) metric).getSnapshot().getStdDev()));
        objectNode.set(TIMER, dataNode);
    }
    return objectNode;
}
项目:anodot-metrics-bridge    文件:Anodot3RegistryFactoryTest.java   
@Test
public void addingSameMetricAgainReturnsSameMetric() throws Exception {
    metricRegistry.counter(NAME).inc();
    final Counter c1 = getCounter(NAME);
    metricRegistry.counter(NAME).inc();
    final Counter c2 = getCounter(NAME);
    assertThat(c1, sameInstance(c2));
}
项目:aliyun-oss-hadoop-fs    文件:SLSWebApp.java   
public SLSWebApp(SchedulerWrapper wrapper, int metricsAddressPort) {
  this.wrapper = wrapper;
  metrics = wrapper.getMetrics();
  handleOperTimecostHistogramMap =
          new HashMap<SchedulerEventType, Histogram>();
  queueAllocatedMemoryCounterMap = new HashMap<String, Counter>();
  queueAllocatedVCoresCounterMap = new HashMap<String, Counter>();
  schedulerMetrics = wrapper.getSchedulerMetrics();
  port = metricsAddressPort;
}
项目:monitoring-center    文件:CompositeForwardingCounter.java   
public CompositeForwardingCounter(Counter mainDelegate, MetricProvider<Counter> supplementaryMetricProvider) {
    Preconditions.checkNotNull(mainDelegate);
    Preconditions.checkNotNull(supplementaryMetricProvider);

    this.mainDelegate = mainDelegate;
    this.supplementaryMetricProvider = supplementaryMetricProvider;
}
项目:dcos-commons    文件:MetricsTest.java   
@Test
public void incrementDeclinesShort() {
    Counter counter = Metrics.getRegistry().counter(Metrics.DECLINE_SHORT);
    long val = counter.getCount();
    Metrics.incrementDeclinesShort(5);
    Assert.assertEquals(5, counter.getCount() - val);
}
项目:graylog-plugin-metrics-reporter    文件:RegexMetricFilterTest.java   
@Test
public void matchesReturnsTrueIfMetricNameIsMatched() throws Exception {
    final Set<Pattern> patterns = Collections.singleton(Pattern.compile("foobar"));
    final RegexMetricFilter regexMetricFilter = new RegexMetricFilter(patterns);

    final Counter counter1 = metricRegistry.counter("foobar.counter");
    metricRegistry.counter("foobaz.counter");

    final SortedMap<String, Counter> counters = metricRegistry.getCounters(regexMetricFilter);
    assertEquals(1, counters.size());
    assertEquals(counter1, counters.get("foobar.counter"));
}
项目:metrics-circonus    文件:CirconusReporterTest.java   
@Test
public void reportsFloatGaugeValues() throws Exception {
  reporter.report(map("gauge", gauge(1.1f)),
                  this.<Counter>map(),
                  this.<Histogram>map(),
                  this.<Meter>map(),
                  this.<Timer>map());

  gaugeTestHelper("gauge", 1.1f, timestamp, HOST, tags);
}
项目:graylog-plugin-metrics-reporter    文件:CollectorRegistryProviderTest.java   
@Test
public void getReturnsCollectorRegistryWithDropwizardMetrics() throws Exception {
    final MetricRegistry registry = new MetricRegistry();
    final Counter counter = registry.counter("test.counter");
    counter.inc(42L);
    final DropwizardExports dropwizardExports = new DropwizardExports(registry);
    final CollectorRegistryProvider provider = new CollectorRegistryProvider(dropwizardExports);
    final CollectorRegistry collectorRegistry = provider.get();

    assertEquals(new Double(42.0d), collectorRegistry.getSampleValue("test_counter"));
}
项目:helium    文件:TramitacioServiceImpl.java   
public void deleteExpedient(
        String entorn,
        String usuari,
        String processInstanceId) throws TramitacioException {
    Entorn e = findEntornAmbCodi(entorn);
    if (e == null)
        throw new TramitacioException("No existeix cap entorn amb el codi '" + entorn + "'");
    final Timer timerTotal = metricRegistry.timer(
            MetricRegistry.name(
                    TramitacioService.class,
                    "expedientEsborrar"));
    final Timer.Context contextTotal = timerTotal.time();
    Counter countTotal = metricRegistry.counter(
            MetricRegistry.name(
                    TramitacioService.class,
                    "expedientEsborrar.count"));
    countTotal.inc();
    final Timer timerEntorn = metricRegistry.timer(
            MetricRegistry.name(
                    TramitacioService.class,
                    "expedientEsborrar",
                    e.getCodi()));
    final Timer.Context contextEntorn = timerEntorn.time();
    Counter countEntorn = metricRegistry.counter(
            MetricRegistry.name(
                    TramitacioService.class,
                    "expedientEsborrar.count",
                    e.getCodi()));
    countEntorn.inc();
    try {
        Authentication authentication =  new UsernamePasswordAuthenticationToken(usuari, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        ExpedientDto expedient = expedientService.findExpedientAmbProcessInstanceId(processInstanceId);
        expedientService.delete(e.getId(), expedient.getId());
    } finally {
        contextTotal.stop();
        contextEntorn.stop();
    }
}
项目:metrics-circonus    文件:CirconusReporterTest.java   
@Test
public void reportsMeters() 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);

  reporter.report(this.<Gauge>map(),
                  this.<Counter>map(),
                  this.<Histogram>map(),
                  this.<Meter>map("meter", meter),
                  this.<Timer>map());

  final InOrder inOrder = inOrder(transport, request);
  inOrder.verify(transport).prepare();
  inOrder.verify(request).addGauge(new CirconusGauge("meter.count", 1L, timestamp, HOST, tags));
  inOrder.verify(request).addGauge(new CirconusGauge("meter.1MinuteRate", 2.0, timestamp, HOST, tags));
  inOrder.verify(request).addGauge(new CirconusGauge("meter.5MinuteRate", 3.0, timestamp, HOST, tags));
  inOrder.verify(request).addGauge(new CirconusGauge("meter.15MinuteRate", 4.0, timestamp, HOST, tags));
  inOrder.verify(request).addGauge(new CirconusGauge("meter.meanRate", 5.0, timestamp, HOST, tags));
  inOrder.verify(request).send();

  verify(transport).prepare();
  verify(request).send();
  verifyNoMoreInteractions(transport, request);
}
项目:Scientist4J    文件:ExperimentTest.java   
@Test
public void candidateExceptionsAreCounted() throws Exception {
    MetricRegistry metrics = new MetricRegistry();
    Experiment<Integer> exp = new Experiment<>("test", metrics);

    exp.run(() -> 1, this::exceptionThrowingFunction);

    Counter result = metrics.getCounters().get("scientist.test.candidate.exception");
    assertThat(result.getCount()).isEqualTo(1);
}