Java Code Examples for org.eclipse.microprofile.metrics.Tag

The following examples show how to use org.eclipse.microprofile.metrics.Tag. 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: quarkus   Source File: QuarkusJaxRsMetricsFilter.java    License: Apache License 2.0 6 votes vote down vote up
private MetricID getMetricID(Class<?> resourceClass, Method resourceMethod) {
    Tag classTag = new Tag("class", resourceClass.getName());
    String methodName = resourceMethod.getName();
    String encodedParameterNames = Arrays.stream(resourceMethod.getParameterTypes())
            .map(clazz -> {
                if (clazz.isArray()) {
                    return clazz.getComponentType().getName() + "[]";
                } else {
                    return clazz.getName();
                }
            })
            .collect(Collectors.joining("_"));
    String methodTagValue = encodedParameterNames.isEmpty() ? methodName : methodName + "_" + encodedParameterNames;
    Tag methodTag = new Tag("method", methodTagValue);
    return new MetricID("REST.request", classTag, methodTag);
}
 
Example 2
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCounters() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Counter counterWithoutTags = registry.counter("mycounter");
    Counter counterRed = registry.counter("mycounter", new Tag("color", "red"));
    Counter counterBlue = registry.counter("mycounter", new Tag("color", "blue"), new Tag("foo", "bar"));

    counterWithoutTags.inc(1);
    counterRed.inc(2);
    counterBlue.inc(3);

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "mycounter").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    assertEquals(1, json.getInt("mycounter"));
    assertEquals(2, json.getInt("mycounter;color=red"));
    assertEquals(3, json.getInt("mycounter;color=blue;foo=bar"));
}
 
Example 3
Source Project: smallrye-metrics   Source File: JmxRegistrar.java    License: Apache License 2.0 6 votes vote down vote up
private ExtendedMetadataAndTags metadataOf(Map.Entry<String, List<MetricProperty>> metadataEntry) {
    String name = metadataEntry.getKey();
    Map<String, String> entryProperties = new HashMap<>();
    metadataEntry.getValue()
            .forEach(
                    prop -> entryProperties.put(prop.propertyKey, prop.propertyValue));
    List<Tag> tags = new ArrayList<>();
    if (entryProperties.containsKey("tags")) {
        final String labelDefs[] = entryProperties.get("tags").split(";");
        for (final String labelDef : labelDefs) {
            final String label[] = labelDef.split("=", 2);
            final Tag tag = new Tag(label[0], label[1]);
            tags.add(tag);
        }
    }

    ExtendedMetadata meta = new ExtendedMetadata(name, entryProperties.get("displayName"),
            entryProperties.get("description"),
            metricTypeOf(entryProperties.get("type")),
            entryProperties.get("unit"),
            entryProperties.get("mbean"),
            "true".equalsIgnoreCase(entryProperties.get("multi")));

    return new ExtendedMetadataAndTags(meta, tags);
}
 
Example 4
Source Project: quarkus   Source File: AgroalMetricsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsOfDefaultDS() throws SQLException {
    Counter acquireCount = registry.getCounters().get(new MetricID("agroal.acquire.count",
            new Tag("datasource", "default")));
    Gauge<?> maxUsed = registry.getGauges().get(new MetricID("agroal.max.used.count",
            new Tag("datasource", "default")));
    Assertions.assertNotNull(acquireCount, "Agroal metrics should be registered eagerly");
    Assertions.assertNotNull(maxUsed, "Agroal metrics should be registered eagerly");

    try (Connection connection = defaultDS.getConnection()) {
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1");
        }
    }

    Assertions.assertEquals(1L, acquireCount.getCount());
    Assertions.assertEquals(1L, maxUsed.getValue());
}
 
Example 5
Source Project: smallrye-metrics   Source File: JsonMetadataExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void exportByMetricNameWithMultipleMetrics() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));
    applicationRegistry.counter("counter1", new Tag("key1", "value2"));
    applicationRegistry.counter("counter1", new Tag("key1", "value3"));

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "counter1").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(3, outerTagsArray.size());

    JsonArray innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("key1=value1", innerArray1.getString(0));

    JsonArray innerArray2 = outerTagsArray.getJsonArray(1);
    assertEquals(1, innerArray2.size());
    assertEquals("key1=value2", innerArray2.getString(0));

    JsonArray innerArray3 = outerTagsArray.getJsonArray(2);
    assertEquals(1, innerArray3.size());
    assertEquals("key1=value3", innerArray3.getString(0));
}
 
Example 6
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSkippingOfScope() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = new ExtendedMetadata("foo",
            "foo",
            "FooDescription",
            MetricType.COUNTER,
            "volts",
            null,
            false,
            Optional.of(true),
            true,
            null);
    Tag tag = new Tag("a", "b");
    registry.counter(metadata, tag);

    String result = exporter.exportOneScope(MetricRegistry.Type.APPLICATION).toString();
    System.out.println(result);
    assertHasHelpLineExactlyOnce(result, "foo_total", "FooDescription");
    assertHasTypeLineExactlyOnce(result, "foo_total", "counter");
    assertHasValueLineExactlyOnce(result, "foo_total_volts", "0.0", tag);
}
 
Example 7
Source Project: smallrye-metrics   Source File: JaxRsMetricsFilter.java    License: Apache License 2.0 6 votes vote down vote up
private MetricID getMetricID(Class<?> resourceClass, Method resourceMethod) {
    Tag classTag = new Tag("class", resourceClass.getName());
    String methodName = resourceMethod.getName();
    String encodedParameterNames = Arrays.stream(resourceMethod.getParameterTypes())
            .map(clazz -> {
                if (clazz.isArray()) {
                    return clazz.getComponentType().getName() + "[]";
                } else {
                    return clazz.getName();
                }
            })
            .collect(Collectors.joining("_"));
    String methodTagValue = encodedParameterNames.isEmpty() ? methodName : methodName + "_" + encodedParameterNames;
    Tag methodTag = new Tag("method", methodTagValue);
    return new MetricID("REST.request", classTag, methodTag);
}
 
Example 8
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNameOverride() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = new ExtendedMetadata("voltage1",
            "Voltage",
            "Measures your electric potential",
            MetricType.GAUGE,
            "volts",
            null,
            false,
            Optional.of(true),
            false,
            "baz");
    Tag tag = new Tag("a", "b");
    registry.register(metadata, (Gauge<Long>) () -> 3L, tag);

    String result = exporter.exportOneScope(MetricRegistry.Type.APPLICATION).toString();
    System.out.println(result);
    assertHasHelpLineExactlyOnce(result, "application_baz", "Measures your electric potential");
    assertHasTypeLineExactlyOnce(result, "application_baz", "gauge");
    assertHasValueLineExactlyOnce(result, "application_baz", "3.0", tag);
}
 
Example 9
Source Project: apicurio-registry   Source File: RestMetricsInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
synchronized void init() {
    // Total counter
    final Metadata m1 = Metadata.builder()
            .withName(REST_REQUEST_COUNT)
            .withDescription(REST_REQUEST_COUNT_DESC + " Across all endpoints.")
            .withType(COUNTER)
            .build();
    final Tag[] tags1 = {new Tag("group", REST_GROUP_TAG), new Tag("metric", REST_REQUEST_COUNT)};
    counter = metricRegistry.counter(m1, tags1);
    // Concurrent gauge
    final Metadata m2 = Metadata.builder()
            .withName(REST_CONCURRENT_REQUEST_COUNT)
            .withDescription(REST_CONCURRENT_REQUEST_COUNT_DESC + " Across all endpoints.")
            .withType(CONCURRENT_GAUGE)
            .build();
    final Tag[] tags2 = {new Tag("group", REST_GROUP_TAG), new Tag("metric", REST_CONCURRENT_REQUEST_COUNT)};
    gauge = metricRegistry.concurrentGauge(m2, tags2);
    // Timer
    final Metadata m3 = Metadata.builder()
            .withName(REST_REQUEST_RESPONSE_TIME)
            .withDescription(REST_REQUEST_RESPONSE_TIME_DESC + " Across all endpoints.")
            .withType(TIMER)
            .withUnit(MILLISECONDS)
            .build();
    final Tag[] tags3 = {new Tag("group", REST_GROUP_TAG), new Tag("metric", REST_REQUEST_RESPONSE_TIME)};
    timer = metricRegistry.timer(m3, tags3);

    init = true;
}
 
Example 10
/**
 * Increase the number of currently logged in users
 *
 * @param keycloakEvent Login event
 */
@Override
public void recordLogin(KeycloakEvent keycloakEvent) {

    Event event = keycloakEvent.getEvent();
    String provider = getIdentityProvider(event);

    Tag[] tags = {
            tag(TAG_REALM, keycloakEvent.getRealmName()),
            tag(TAG_PROVIDER, provider),
            tag(TAG_CLIENT_ID, event.getClientId())
    };

    metricsRegistry.counter(totalLogins, tags).inc();
}
 
Example 11
/**
 * Increase the number of failed registered users attemps
 *
 * @param keycloakEvent RegisterError event
 */
@Override
public void recordRegistrationError(KeycloakEvent keycloakEvent) {

    Event event = keycloakEvent.getEvent();
    String provider = getIdentityProvider(event);

    Tag[] tags = {
            tag(TAG_REALM, keycloakEvent.getRealmName()),
            tag(TAG_PROVIDER, provider),
            tag(TAG_CLIENT_ID, event.getClientId())
    };

    metricsRegistry.counter(totalRegistrationsErrors, tags).inc();
}
 
Example 12
@Override
public void connectionPoolOpened(ConnectionPoolOpenedEvent event) {
    Tag[] tags = createTags(event.getServerId());

    registerGauge(SIZE_NAME, "the current size of the pool, including idle and and in-use members", tags);
    registerGauge(CHECKED_OUT_COUNT_NAME, "the current count of connections that are currently in use", tags);
}
 
Example 13
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNewlineCharacterInTagValue() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    registry.counter("counter1",
            new Tag("tag1", "i_have\n_two_lines"));

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "counter1").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    assertEquals("Newline chars in tag values should be escaped as \\n",
            "counter1;tag1=i_have\n_two_lines", json.keySet().stream().findFirst().get());
}
 
Example 14
@Test
public void test() {
    // metric should be created for the constructor
    assertTrue(
            registry.getCounters().containsKey(new MetricID("customName.BeanWithCounter_ClassLevel", new Tag("t1", "v1"))));

    // metrics should be created for public methods
    assertTrue(registry.getCounters().containsKey(new MetricID("customName.publicMethod", new Tag("t1", "v1"))));
    assertTrue(registry.getCounters().containsKey(new MetricID("customName.publicMethod2", new Tag("t1", "v1"))));

    // but not for private methods
    assertFalse(registry.getCounters().keySet().stream()
            .anyMatch(metricID -> metricID.getName().toLowerCase().contains("private")));
}
 
Example 15
@Test
public void test() {
    bean.colorBlue1();
    bean.colorBlue1();
    bean.colorBlue2();
    bean.colorRed1();
    bean.colorRed2();
    Assert.assertEquals(3,
            metricRegistry.getCounters().get(new MetricID("colorCounter", new Tag("color", "blue"))).getCount());
    Assert.assertEquals(2,
            metricRegistry.getCounters().get(new MetricID("colorCounter", new Tag("color", "red"))).getCount());
}
 
Example 16
@Test
public void test() {
    // force creating two instances of the bean
    bean.get();
    bean.get();
    Assert.assertEquals(4, metricRegistry.getCounters().get(new MetricID("mycounter", new Tag("k", "v1"))).getCount());
    Assert.assertEquals(6, metricRegistry.getCounters().get(new MetricID("mycounter", new Tag("k", "v2"))).getCount());
}
 
Example 17
Source Project: quarkus   Source File: JaegerProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void produceMetrics(BuildProducer<MetricBuildItem> producer) {
    producer.produce(
            metric("jaeger_tracer_baggage_restrictions_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(
            metric("jaeger_tracer_baggage_restrictions_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_baggage_truncations", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_baggage_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_baggage_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_finished_spans", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "dropped")));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_queries", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_sampler_queries", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_span_context_decoding_errors", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_started_spans", MetricType.COUNTER, null, new Tag("sampled", "n")));
    producer.produce(metric("jaeger_tracer_started_spans", MetricType.COUNTER, null, new Tag("sampled", "y")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "y"), new Tag("state", "joined")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "y"), new Tag("state", "started")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "n"), new Tag("state", "joined")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "n"), new Tag("state", "started")));
    producer.produce(
            metric("jaeger_tracer_reporter_queue_length", MetricType.GAUGE, new QuarkusJaegerMetricsFactory.JaegerGauge()));
}
 
Example 18
private void registerGauge(String metricName, String description, Tag[] tags) {
    getMetricRegistry().remove(new MetricID(metricName, tags));

    Metadata metaData = Metadata.builder().withName(metricName).withType(MetricType.GAUGE)
            .withDescription(description).build();
    getMetricRegistry().register(metaData, new ConnectionPoolGauge(), tags);
}
 
Example 19
Source Project: smallrye-metrics   Source File: JsonMetadataExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void exportByScopeWithMultipleMetrics() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));
    applicationRegistry.counter("counter1", new Tag("key1", "value2"));
    applicationRegistry.counter("counter2", new Tag("color", "red"));

    String result = exporter.exportOneScope(MetricRegistry.Type.APPLICATION).toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    // check items for counter1
    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(2, outerTagsArray.size());

    JsonArray innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("key1=value1", innerArray1.getString(0));

    JsonArray innerArray2 = outerTagsArray.getJsonArray(1);
    assertEquals(1, innerArray2.size());
    assertEquals("key1=value2", innerArray2.getString(0));

    // check items for counter2
    outerTagsArray = json.getJsonObject("counter2").getJsonArray("tags");
    assertEquals(1, outerTagsArray.size());

    innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("color=red", innerArray1.getString(0));
}
 
Example 20
Source Project: quarkus   Source File: JaxRsMetricsTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTakingList() {
    when()
            .get("/a/b/c/list")
            .then()
            .statusCode(200);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "list_java.util.List"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example 21
Source Project: quarkus   Source File: JaxRsMetricsTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodReturningServerError() throws InterruptedException {
    when()
            .get("/error")
            .then()
            .statusCode(500);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "error"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example 22
Source Project: quarkus   Source File: JaxRsMetricsTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() {
    when()
            .get("/hello/joe")
            .then()
            .statusCode(200);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "hello_java.lang.String"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example 23
Source Project: smallrye-metrics   Source File: JsonMetadataExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void exportByMetricNameWithOneMetricSingleTag() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "counter1").toString();

    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();
    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(1, outerTagsArray.size());
    JsonArray innerArray = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray.size());
    assertEquals("key1=value1", innerArray.getString(0));
}
 
Example 24
Source Project: quarkus   Source File: JaxRsMetricsTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodThrowingException() {
    when()
            .get("/exception")
            .then()
            .statusCode(500);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "exception"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example 25
Source Project: smallrye-metrics   Source File: TagsUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Tag parseTag(String kvString) {
    if (kvString == null || kvString.isEmpty() || !kvString.contains("=")) {
        throw SmallRyeMetricsMessages.msg.notAKeyValuePair(kvString);
    }
    String[] kv = kvString.split("=");
    if (kv.length != 2) {
        throw SmallRyeMetricsMessages.msg.notAKeyValuePair(kvString);
    }
    String key = kv[0].trim();
    String value = kv[1].trim();
    return new Tag(key, value);
}
 
Example 26
Source Project: smallrye-metrics   Source File: TagsUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Tag[] parseTagsAsArray(String[] kvStrings) {
    Tag[] result = new Tag[kvStrings.length];
    int i = 0;
    for (String kvString : kvStrings) {
        result[i] = parseTag(kvString);
        i++;
    }
    return result;
}
 
Example 27
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSemicolonInTagValue() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    registry.counter("counter1",
            new Tag("tag1", "i;have;semicolons"),
            new Tag("tag2", "i;have;semicolons;as;well"));

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "counter1").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    assertNotNull("Semicolons in tag values should be converted to underscores",
            json.getJsonNumber("counter1;tag1=i_have_semicolons;tag2=i_have_semicolons_as_well"));
}
 
Example 28
Source Project: smallrye-metrics   Source File: JmxRegistrarTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReplaceMultipleWildcards() {
    assertThat(getMetadataCalled("test_key")).hasSize(1);

    final ExtendedMetadataAndTags extendedMetadata = getSingleMatch("test_key");
    assertThat(extendedMetadata.getMetadata().getName()).isEqualTo("test_key");
    assertThat(extendedMetadata.getMetadata().getDescription()).isEqualTo("Description %s1-%s2");
    assertThat(extendedMetadata.getMetadata().getDisplayName()).isEqualTo("Display Name %s1-%s2");
    assertThat(extendedMetadata.getMetadata().getMbean()).isEqualTo("java.nio:name=%s2,type=%s1/ObjectName");
    assertThat(extendedMetadata.getTags()).contains(
            new Tag("type", "%s1"),
            new Tag("name", "%s2"));
    assertThat(extendedMetadata.getMetadata().getType()).isEqualTo("counter");
    assertThat(extendedMetadata.getMetadata().getUnit()).isEqualTo("none");

    final List<ExtendedMetadataAndTags> metadataList = Lists.list(extendedMetadata);

    JmxWorker.instance().expandMultiValueEntries(metadataList);

    final ExtendedMetadataAndTags extendedMetadata1 = metadataList.get(0);
    assertThat(extendedMetadata1.getMetadata().getDescription()).isEqualTo("Description BufferPool-mapped");
    assertThat(extendedMetadata1.getMetadata().getDisplayName()).isEqualTo("Display Name BufferPool-mapped");
    assertThat(extendedMetadata1.getMetadata().getMbean()).isEqualTo("java.nio:name=mapped,type=BufferPool/ObjectName");
    assertThat(extendedMetadata1.getTags()).contains(
            new Tag("type", "BufferPool"),
            new Tag("name", "mapped"));

    final ExtendedMetadataAndTags extendedMetadata2 = metadataList.get(1);
    assertThat(extendedMetadata2.getMetadata().getDescription()).isEqualTo("Description BufferPool-direct");
    assertThat(extendedMetadata2.getMetadata().getDisplayName()).isEqualTo("Display Name BufferPool-direct");
    assertThat(extendedMetadata2.getMetadata().getMbean()).isEqualTo("java.nio:name=direct,type=BufferPool/ObjectName");
    assertThat(extendedMetadata2.getTags()).contains(
            new Tag("type", "BufferPool"),
            new Tag("name", "direct"));
}
 
Example 29
/**
 * One set of threads is registering new metrics and removing them after a short while,
 * at the same time, another set of threads is retrieving a list of metrics conforming to a filter.
 * None of the threads should be getting any exceptions.
 */
@Test
public void tryRegisteringRemovingAndReadingAtTheSameTime() throws InterruptedException {
    for (int i = 0; i < 20; i++) {
        cleanup();
        final ExecutorService executor = Executors.newFixedThreadPool(10);
        final CompletableFuture[] futures = IntStream.range(0, 200)
                .parallel()
                .mapToObj(j -> CompletableFuture.runAsync(
                        () -> {
                            try {
                                if (j % 2 == 0) {
                                    MetricID metricID = new MetricID("mycounter", new Tag("number", String.valueOf(j)));
                                    registry.counter("mycounter", new Tag("number", String.valueOf(j)));
                                    registry.remove(metricID);
                                } else {
                                    registry.getCounters(MetricFilter.ALL);
                                }
                            } catch (Throwable t) {
                                t.printStackTrace();
                                throw t;
                            }
                        }, executor))
                .toArray(CompletableFuture[]::new);
        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.SECONDS);

        assertEquals("All threads should finish without exceptions",
                0, Arrays.stream(futures).filter(CompletableFuture::isCompletedExceptionally).count());
    }
}
 
Example 30
Source Project: smallrye-metrics   Source File: MetadataMismatchTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void reusingMetadata() {
    Metadata metadata1 = Metadata.builder().withName("myhistogram").withDescription("description1").build();

    Histogram histogram1 = registry.histogram(metadata1);
    Histogram histogram2 = registry.histogram("myhistogram", new Tag("color", "blue"));

    assertNotEquals(histogram1, histogram2);
    assertEquals(2, registry.getMetrics().size());
    assertThat(registry.getMetadata().get("myhistogram").description().get(), equalTo("description1"));
}