├── .github
├── workflows
│ ├── release.yml
│ └── build.yml
├── project.yml
└── dependabot.yml
├── CODEOWNERS
├── doc
├── antora.yml
├── modules
│ └── ROOT
│ │ ├── nav.adoc
│ │ └── pages
│ │ ├── index.adoc
│ │ ├── metric-registry-lifecycle.adoc
│ │ ├── cdi-extension.adoc
│ │ ├── jaxrs-metrics.adoc
│ │ ├── base-and-vendor-metrics.adoc
│ │ └── extended-metadata.adoc
└── antora-playbook.yml
├── testsuite
├── api-tck
│ └── src
│ │ ├── main
│ │ └── resources
│ │ │ └── META-INF
│ │ │ └── services
│ │ │ └── org.jboss.arquillian.core.spi.LoadableExtension
│ │ └── test
│ │ └── resources
│ │ └── logging.properties
├── extra
│ ├── src
│ │ ├── main
│ │ │ ├── resources
│ │ │ │ └── META-INF
│ │ │ │ │ └── services
│ │ │ │ │ └── org.jboss.arquillian.core.spi.LoadableExtension
│ │ │ └── java
│ │ │ │ └── io
│ │ │ │ └── smallrye
│ │ │ │ └── metrics
│ │ │ │ └── test
│ │ │ │ ├── HelloService.java
│ │ │ │ └── MetricsSummary.java
│ │ └── test
│ │ │ └── java
│ │ │ └── io
│ │ │ └── smallrye
│ │ │ └── metrics
│ │ │ └── test
│ │ │ ├── stereotype
│ │ │ ├── CountedClass.java
│ │ │ ├── stereotypes
│ │ │ │ └── CountMe.java
│ │ │ └── StereotypeCountedClassTest.java
│ │ │ ├── dependent
│ │ │ ├── DependentScopedBeanWithGauge.java
│ │ │ ├── DependentScopedBeanWithMetrics.java
│ │ │ └── GaugeInDependentScopedBeanTest.java
│ │ │ ├── reusability
│ │ │ ├── ReuseMetricWithDifferingTagsBean.java
│ │ │ └── ReuseMetricWithDifferingTagsTest.java
│ │ │ ├── initialization
│ │ │ ├── Initialization_Meter_Method_Test.java
│ │ │ ├── Initialization_Counter_Constructor_Test.java
│ │ │ ├── Initialization_Counter_Method_Test.java
│ │ │ ├── Initialization_ConcurrentGauge_Method_Test.java
│ │ │ ├── Initialization_Counter_Method_Reused_Test.java
│ │ │ ├── Initialization_Timer_Method_Test.java
│ │ │ ├── Initialization_SimpleTimer_Method_Test.java
│ │ │ ├── Initialization_Injection_Test.java
│ │ │ ├── Initialization_Gauge_Method_Test.java
│ │ │ └── Initialization_Counter_ClassLevel_Test.java
│ │ │ ├── inject
│ │ │ ├── NonReusableMetricInjectionBean.java
│ │ │ └── NonReusableMetricInjectionTest.java
│ │ │ └── registry
│ │ │ ├── AllMetricsOfGivenTypeTest.java
│ │ │ └── MetricRegistryInjectionTest.java
│ └── pom.xml
├── rest-tck
│ └── src
│ │ └── test
│ │ ├── resources
│ │ ├── META-INF
│ │ │ └── services
│ │ │ │ └── org.jboss.arquillian.core.spi.LoadableExtension
│ │ ├── WEB-INF
│ │ │ └── jboss-web.xml
│ │ └── logging.properties
│ │ └── java
│ │ └── io
│ │ └── smallrye
│ │ └── metrics
│ │ └── tck
│ │ └── rest
│ │ ├── MetricsExtension.java
│ │ ├── MetricsHttpServlet.java
│ │ ├── ArchiveProcessor.java
│ │ └── SmallRyeBeanArchiveHandler.java
├── optional-tck
│ └── src
│ │ └── test
│ │ ├── resources
│ │ ├── META-INF
│ │ │ ├── services
│ │ │ │ └── org.jboss.arquillian.core.spi.LoadableExtension
│ │ │ └── jboss-deployment-structure.xml
│ │ └── WEB-INF
│ │ │ ├── jboss-web.xml
│ │ │ └── web.xml
│ │ └── java
│ │ └── io
│ │ └── smallrye
│ │ └── metrics
│ │ └── tck
│ │ └── optional
│ │ ├── JaxRsMetricsExtension.java
│ │ ├── MetricsHttpServlet.java
│ │ └── JaxRsMetricsActivatingProcessor.java
├── common
│ ├── src
│ │ └── main
│ │ │ ├── resources
│ │ │ └── io
│ │ │ │ └── smallrye
│ │ │ │ └── metrics
│ │ │ │ └── vendor-metrics.properties
│ │ │ └── java
│ │ │ └── io
│ │ │ └── smallrye
│ │ │ └── metrics
│ │ │ └── testsuite
│ │ │ ├── MetricsExtension.java
│ │ │ ├── MetricsInitializer.java
│ │ │ └── ArchiveProcessor.java
│ └── pom.xml
└── pom.xml
├── implementation
└── src
│ ├── main
│ ├── resources
│ │ ├── META-INF
│ │ │ └── services
│ │ │ │ └── jakarta.enterprise.inject.spi.Extension
│ │ └── project.properties
│ └── java
│ │ └── io
│ │ └── smallrye
│ │ └── metrics
│ │ ├── interceptors
│ │ ├── MetricsParameter.java
│ │ ├── MetricsBinding.java
│ │ ├── MetricName.java
│ │ ├── MetricNameFactory.java
│ │ ├── CountedInterceptor.java
│ │ ├── MeteredInterceptor.java
│ │ └── SimplyTimedInterceptor.java
│ │ ├── elementdesc
│ │ ├── MemberType.java
│ │ ├── adapter
│ │ │ ├── BeanInfoAdapter.java
│ │ │ ├── MemberInfoAdapter.java
│ │ │ ├── AnnotationInfoAdapter.java
│ │ │ └── cdi
│ │ │ │ ├── CDIBeanInfoAdapter.java
│ │ │ │ ├── CDIAnnotationInfoAdapter.java
│ │ │ │ ├── CDIMemberInfoAdapter.java
│ │ │ │ └── CDIBeanInfo.java
│ │ ├── AnnotationInfo.java
│ │ ├── BeanInfo.java
│ │ ├── MemberInfo.java
│ │ ├── RawAnnotationInfo.java
│ │ └── RawBeanInfo.java
│ │ ├── exporters
│ │ ├── JsonProviderHolder.java
│ │ ├── Exporter.java
│ │ └── ExporterUtil.java
│ │ ├── mbean
│ │ ├── MGaugeImpl.java
│ │ └── MCounterImpl.java
│ │ ├── ExtendedMetadataAndTags.java
│ │ ├── MetadataList.java
│ │ ├── app
│ │ ├── CounterImpl.java
│ │ ├── Reservoir.java
│ │ ├── Clock.java
│ │ └── HistogramImpl.java
│ │ ├── OriginAndMetadata.java
│ │ ├── setup
│ │ ├── AnnotatedTypeDecorator.java
│ │ └── AnnotatedDecorator.java
│ │ ├── UnspecifiedMetadata.java
│ │ ├── MetricRegistries.java
│ │ └── SmallRyeMetricsLogging.java
│ └── test
│ ├── resources
│ ├── logging.properties
│ └── base-metrics.properties
│ └── java
│ └── io
│ └── smallrye
│ └── metrics
│ ├── app
│ └── WeightedSnapshotTest.java
│ ├── histogram
│ ├── ExponentiallyWeightedReservoirTest.java
│ └── TestingClock.java
│ ├── exporters
│ ├── SomeHistogram.java
│ ├── SomeMeter.java
│ ├── SomeSnapshot.java
│ ├── ExporterUtilTest.java
│ ├── SomeTimer.java
│ └── OpenMetricsUnitScalingTest.java
│ ├── ExtendedMetadataBuilderTest.java
│ └── registration
│ ├── MetricTypeMismatchTest.java
│ └── MetadataMismatchTest.java
├── release
└── pom.xml
├── api
└── pom.xml
├── .gitignore
├── README.adoc
└── coverage
└── pom.xml
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/CODEOWNERS:
--------------------------------------------------------------------------------
1 | .github @smallrye/metrics
2 |
--------------------------------------------------------------------------------
/.github/project.yml:
--------------------------------------------------------------------------------
1 | name: SmallRye Metrics
2 | release:
3 | current-version: 4.0.0
4 | next-version: 4.0.1-SNAPSHOT
5 |
--------------------------------------------------------------------------------
/doc/antora.yml:
--------------------------------------------------------------------------------
1 | name: smallrye-metrics
2 | title: SmallRye Metrics
3 | version: 3.0.0
4 | nav:
5 | - modules/ROOT/nav.adoc
6 |
--------------------------------------------------------------------------------
/testsuite/api-tck/src/main/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension:
--------------------------------------------------------------------------------
1 | io.smallrye.metrics.testsuite.MetricsExtension
--------------------------------------------------------------------------------
/testsuite/extra/src/main/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension:
--------------------------------------------------------------------------------
1 | io.smallrye.metrics.testsuite.MetricsExtension
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension:
--------------------------------------------------------------------------------
1 | io.smallrye.metrics.tck.rest.MetricsExtension
--------------------------------------------------------------------------------
/implementation/src/main/resources/META-INF/services/jakarta.enterprise.inject.spi.Extension:
--------------------------------------------------------------------------------
1 | io.smallrye.metrics.setup.MetricCdiInjectionExtension
2 |
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension:
--------------------------------------------------------------------------------
1 | io.smallrye.metrics.tck.optional.JaxRsMetricsExtension
--------------------------------------------------------------------------------
/implementation/src/test/resources/logging.properties:
--------------------------------------------------------------------------------
1 | handlers = java.util.logging.ConsoleHandler
2 | java.util.logging.ConsoleHandler.level = FINE
3 | io.smallrye.metrics.level = FINE
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/resources/WEB-INF/jboss-web.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | /
4 |
--------------------------------------------------------------------------------
/doc/modules/ROOT/nav.adoc:
--------------------------------------------------------------------------------
1 | * xref:index.adoc[Index]
2 | * Features on top of the specification
3 | ** xref:extended-metadata.adoc[Extended metadata]
4 | * Integrating SmallRye Metrics into runtimes
5 | ** xref:cdi-extension.adoc[CDI Extension]
6 | ** xref:base-and-vendor-metrics.adoc[Base and vendor metrics]
7 | ** xref:metric-registry-lifecycle.adoc[Metric registry lifecycle]
8 | ** xref:jaxrs-metrics.adoc[JAX-RS metrics]
--------------------------------------------------------------------------------
/doc/antora-playbook.yml:
--------------------------------------------------------------------------------
1 | # partial playbook just for this project to be able to compile documentation without pushing it to GitHub
2 | # usage: antora generate antora-playbook.yml
3 | site:
4 | title: SmallRye Metrics only documentation
5 | start_page: smallrye-metrics::index.adoc
6 | content:
7 | sources:
8 | - url: ..
9 | start_path: doc
10 | branches: HEAD
11 | ui:
12 | bundle:
13 | url: https://github.com/smallrye/smallrye-antora-ui/blob/main/build/ui-bundle.zip?raw=true
14 | snapshot: true
15 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "maven"
4 | directory: "/"
5 | schedule:
6 | interval: "daily"
7 | open-pull-requests-limit: 10
8 |
9 | - package-ecosystem: "maven"
10 | directory: "/"
11 | schedule:
12 | interval: "daily"
13 | target-branch: "micrometer"
14 | open-pull-requests-limit: 10
15 | # Avoid any Dependabot branch name collisions
16 | pull-request-branch-name:
17 | separator: "-"
18 | labels:
19 | - "micrometer"
20 | - "dependencies"
21 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/app/WeightedSnapshotTest.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.app;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import java.util.Collections;
6 |
7 | import org.junit.Test;
8 |
9 | /**
10 | * @author helloween
11 | */
12 | public class WeightedSnapshotTest {
13 |
14 | @Test
15 | public void init() {
16 | WeightedSnapshot.WeightedSample sample = new WeightedSnapshot.WeightedSample(1L, 0.0);
17 | WeightedSnapshot snapshot = new WeightedSnapshot(Collections.singletonList(sample));
18 | assertFalse(Double.isNaN(snapshot.getMean()));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/release/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | io.smallrye
7 | smallrye-metrics-parent
8 | 4.0.1-SNAPSHOT
9 |
10 |
11 | smallrye-metrics-release
12 |
13 | Empty Release Project to Avoid Maven Bug
14 | Empty Release Project to Avoid Maven Bug
15 |
16 | pom
17 |
18 |
19 |
--------------------------------------------------------------------------------
/doc/modules/ROOT/pages/index.adoc:
--------------------------------------------------------------------------------
1 | [[index]]
2 | = SmallRye Metrics Documentation
3 |
4 | SmallRye Metrics 3.0 is an implementation of the MicroProfile Metrics 3.0 specification.
5 |
6 | Runtimes that currently use it as their metrics implementation include:
7 |
8 | * https://quarkus.io/[Quarkus]
9 | * https://wildfly.org/[WildFly]
10 | * https://thorntail.io/[Thorntail]
11 |
12 |
13 | [[more-resources]]
14 | == More Resources
15 |
16 | * https://github.com/smallrye/smallrye-metrics/[SmallRye Metrics GitHub project repository]
17 | * https://github.com/eclipse/microprofile-metrics/[Eclipse MicroProfile Metrics repository]
18 | * https://download.eclipse.org/microprofile/microprofile-metrics-3.0/microprofile-metrics-spec-3.0.html[MicroProfile Metrics 3.0 specification text]
19 |
20 |
--------------------------------------------------------------------------------
/implementation/src/main/resources/project.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | # and other contributors as indicated by the @author tags.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 | #
17 |
18 | smallrye.metrics.version=${project.version}
--------------------------------------------------------------------------------
/doc/modules/ROOT/pages/metric-registry-lifecycle.adoc:
--------------------------------------------------------------------------------
1 | [[metric-registry-lifecycle]]
2 | = Metric registry lifecycle
3 |
4 | Lifecycle of metric registries is controlled by the `io.smallrye.metrics.MetricRegistries` application-scoped bean.
5 | If it is necessary to drop and recreate a metric registry during runtime, it is possible to call
6 | `MetricRegistries.drop(MetricRegistry.Type)` to drop one particular registry, or `MetricRegistries.dropAll()`.
7 | After a metric registry is dropped, a new empty registry will be automatically initialized when a reference to the
8 | particular registry type is being requested.
9 |
10 | The `io.smallrye.metrics.MetricRegistries` class is also meant to be public API, so applications are allowed
11 | to use its static method `get` to obtain references
12 | to metric registries without having to inject them using CDI.
13 |
--------------------------------------------------------------------------------
/testsuite/common/src/main/resources/io/smallrye/metrics/vendor-metrics.properties:
--------------------------------------------------------------------------------
1 | BufferPool_used_memory_%s.mbean: java.nio:type=BufferPool,name=%s/MemoryUsed
2 | BufferPool_used_memory_%s.description: The memory used by the NIO pool: %s
3 | BufferPool_used_memory_%s.multi: true
4 | BufferPool_used_memory_%s.type: gauge
5 | BufferPool_used_memory_%s.unit: bytes
6 | memoryPool.%s.usage.mbean: java.lang:type=MemoryPool,name=%s/Usage#used
7 | memoryPool.%s.usage.unit: bytes
8 | memoryPool.%s.usage.description: Current usage of the %s memory pool
9 | memoryPool.%s.usage.multi: true
10 | memoryPool.%s.usage.type: gauge
11 | memoryPool.%s.usage.max.mbean: java.lang:type=MemoryPool,name=%s/PeakUsage#used
12 | memoryPool.%s.usage.max.unit: bytes
13 | memoryPool.%s.usage.max.description: Peak usage of the %s memory pool
14 | memoryPool.%s.usage.max.multi: true
15 | memoryPool.%s.usage.max.type: gauge
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/resources/WEB-INF/jboss-web.xml:
--------------------------------------------------------------------------------
1 |
17 |
18 |
19 | /
20 |
--------------------------------------------------------------------------------
/doc/modules/ROOT/pages/cdi-extension.adoc:
--------------------------------------------------------------------------------
1 | [[cdi-extension]]
2 | = CDI Extension for eager registration of annotated application metrics
3 |
4 | SmallRye Metrics provides a CDI extension which takes care of the annotation scanning and then registering
5 | all detected metrics at deployment time. If your runtime supports CDI extensions, just make sure that
6 | the `io.smallrye.metrics.setup.MetricCdiInjectionExtension` extension is active. It is mandatory
7 | to register metrics beforehand, because the metric interceptors expect metrics to already exist when
8 | the interceptor is invoked (with the exception of Gauges, where registration is performed in a
9 | `@PostConstruct` method of the interceptor, that means when the owning bean is being instantiated).
10 |
11 | If the target runtime does not support CDI extensions, a different strategy must be devised
12 | for scanning the deployment and registering annotated metrics.
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/MetricsParameter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.interceptors;
17 |
18 | /* package-private */ enum MetricsParameter {
19 |
20 | useAbsoluteName
21 | }
22 |
--------------------------------------------------------------------------------
/testsuite/api-tck/src/test/resources/logging.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | # and other contributors as indicated by the @author tags.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 | #
17 |
18 | handlers = java.util.logging.ConsoleHandler
19 | java.util.logging.ConsoleHandler.level = FINE
20 | io.smallrye.metrics.level = FINE
21 | org.jboss.weld.level = WARN
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/resources/logging.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | # and other contributors as indicated by the @author tags.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 | #
17 |
18 | handlers = java.util.logging.ConsoleHandler
19 | java.util.logging.ConsoleHandler.level = FINE
20 | io.smallrye.metrics.level = FINE
21 | org.jboss.weld.level = WARN
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/MemberType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc;
19 |
20 | public enum MemberType {
21 |
22 | CONSTRUCTOR,
23 | METHOD,
24 | FIELD
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/api/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | smallrye-metrics-parent
5 | io.smallrye
6 | 4.0.1-SNAPSHOT
7 |
8 | 4.0.0
9 |
10 | smallrye-metrics-api
11 | SmallRye Metrics external API
12 |
13 |
14 |
15 | io.smallrye.common
16 | smallrye-common-annotation
17 |
18 |
19 | org.eclipse.microprofile.metrics
20 | microprofile-metrics-api
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/BeanInfoAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter;
19 |
20 | import io.smallrye.metrics.elementdesc.BeanInfo;
21 |
22 | public interface BeanInfoAdapter {
23 |
24 | BeanInfo convert(T input);
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/MemberInfoAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter;
19 |
20 | import io.smallrye.metrics.elementdesc.MemberInfo;
21 |
22 | public interface MemberInfoAdapter {
23 |
24 | MemberInfo convert(T input);
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/AnnotationInfoAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter;
19 |
20 | import io.smallrye.metrics.elementdesc.AnnotationInfo;
21 |
22 | public interface AnnotationInfoAdapter {
23 |
24 | AnnotationInfo convert(I input);
25 | }
26 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/stereotype/CountedClass.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.stereotype;
19 |
20 | import io.smallrye.metrics.test.stereotype.stereotypes.CountMe;
21 |
22 | @CountMe
23 | public class CountedClass {
24 |
25 | public void foo() {
26 |
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/exporters/JsonProviderHolder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.exporters;
19 |
20 | import jakarta.json.spi.JsonProvider;
21 |
22 | class JsonProviderHolder {
23 |
24 | private static final JsonProvider INSTANCE = JsonProvider.provider();
25 |
26 | static JsonProvider get() {
27 | return INSTANCE;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/histogram/ExponentiallyWeightedReservoirTest.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.histogram;
2 |
3 | import static org.hamcrest.CoreMatchers.equalTo;
4 | import static org.hamcrest.CoreMatchers.not;
5 |
6 | import org.eclipse.microprofile.metrics.Histogram;
7 | import org.junit.Assert;
8 | import org.junit.Test;
9 |
10 | import io.smallrye.metrics.app.ExponentiallyDecayingReservoir;
11 | import io.smallrye.metrics.app.HistogramImpl;
12 |
13 | public class ExponentiallyWeightedReservoirTest {
14 |
15 | @Test
16 | public void removeZeroWeightsInSamplesToPreventNaNInMeanValues() {
17 | final TestingClock clock = new TestingClock();
18 | final ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(1028, 0.015, clock);
19 | Histogram histogram = new HistogramImpl(reservoir);
20 |
21 | histogram.update(100);
22 |
23 | for (int i = 1; i < 48; i++) {
24 | clock.addHours(1);
25 | Assert.assertThat(reservoir.getSnapshot().getMean(), not(equalTo(Double.NaN)));
26 | }
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/resources/META-INF/jboss-deployment-structure.xml:
--------------------------------------------------------------------------------
1 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/AnnotationInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc;
19 |
20 | public interface AnnotationInfo {
21 |
22 | String name();
23 |
24 | boolean absolute();
25 |
26 | String[] tags();
27 |
28 | String unit();
29 |
30 | String description();
31 |
32 | String displayName();
33 |
34 | String annotationName();
35 |
36 | }
--------------------------------------------------------------------------------
/doc/modules/ROOT/pages/jaxrs-metrics.adoc:
--------------------------------------------------------------------------------
1 | [[jaxrs-metrics]]
2 | = JAX-RS metrics
3 |
4 | SmallRye Metrics 3.0 supports the optional JAX-RS metrics as defined in the specification. To enable collection of
5 | JAX-RS metrics for an application, it is necessary to apply two filters:
6 |
7 | - `io.smallrye.metrics.jaxrs.JaxRsMetricsFilter` - a JAX-RS `ContainerRequestFilter`
8 | - `io.smallrye.metrics.jaxrs.JaxRsMetricsServletFilter` - a servlet filter
9 |
10 | The reason for using two filters is that unfortunately, JAX-RS specification does not require `ContainerResponseFilter`-s
11 | to be invoked when request handling ended in an unmapped exception. That's why we need to use a servlet filter instead
12 | to be able to hook into the responses even in these cases.
13 |
14 | If the target runtime does not support servlets, a different mechanism needs to be used that will be able to hook into
15 | JAX-RS responses and will mimic the functionality of `JaxRsMetricsServletFilter`.
16 |
17 | At the moment, there is no general mechanism to register JAX-RS metrics eagerly at deployment time - metric for each JAX-RS method
18 | is registered as soon as that method is invoked.
19 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/dependent/DependentScopedBeanWithGauge.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.smallrye.metrics.test.dependent;
18 |
19 | import org.eclipse.microprofile.metrics.MetricUnits;
20 | import org.eclipse.microprofile.metrics.annotation.Gauge;
21 |
22 | public class DependentScopedBeanWithGauge {
23 |
24 | @Gauge(name = "gauge", absolute = true, unit = MetricUnits.DAYS)
25 | public Long gaugedMethod() {
26 | return 42L;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/MetricsBinding.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.interceptors;
17 |
18 | import java.lang.annotation.ElementType;
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.RetentionPolicy;
21 | import java.lang.annotation.Target;
22 |
23 | import jakarta.interceptor.InterceptorBinding;
24 |
25 | @InterceptorBinding
26 | @Target({ ElementType.TYPE })
27 | @Retention(RetentionPolicy.RUNTIME)
28 | public @interface MetricsBinding {
29 | }
30 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/cdi/CDIBeanInfoAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter.cdi;
19 |
20 | import io.smallrye.metrics.elementdesc.BeanInfo;
21 | import io.smallrye.metrics.elementdesc.adapter.BeanInfoAdapter;
22 |
23 | public class CDIBeanInfoAdapter implements BeanInfoAdapter> {
24 |
25 | @Override
26 | public BeanInfo convert(Class> input) {
27 | return new CDIBeanInfo(input);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/java/io/smallrye/metrics/tck/rest/MetricsExtension.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.tck.rest;
17 |
18 | import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor;
19 | import org.jboss.arquillian.core.spi.LoadableExtension;
20 |
21 | public class MetricsExtension implements LoadableExtension {
22 |
23 | @Override
24 | public void register(ExtensionBuilder extensionBuilder) {
25 | extensionBuilder.service(ProtocolArchiveProcessor.class, ArchiveProcessor.class);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: SmallRye Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | paths-ignore:
8 | - '.gitignore'
9 | - 'CODEOWNERS'
10 | - 'LICENSE'
11 | - 'NOTICE'
12 | - 'README*'
13 | pull_request:
14 | paths-ignore:
15 | - '.gitignore'
16 | - 'CODEOWNERS'
17 | - 'LICENSE'
18 | - 'NOTICE'
19 | - 'README*'
20 |
21 | jobs:
22 | build:
23 | runs-on: ubuntu-latest
24 | strategy:
25 | matrix:
26 | java: [11, 17, 21]
27 | name: build with jdk ${{matrix.java}}
28 |
29 | steps:
30 | - uses: actions/checkout@v4
31 | name: checkout
32 |
33 | - uses: actions/setup-java@v4
34 | name: set up jdk ${{matrix.java}}
35 | with:
36 | distribution: 'temurin'
37 | java-version: ${{matrix.java}}
38 | cache: 'maven'
39 | cache-dependency-path: '**/pom.xml'
40 |
41 | - name: build with maven
42 | run: mvn -B formatter:validate verify --file pom.xml
43 |
44 | - uses: actions/upload-artifact@v4
45 | name: tck-report
46 | with:
47 | name: tck-report
48 | path: testsuite/tck/target/surefire-reports-*
49 |
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/java/io/smallrye/metrics/tck/optional/JaxRsMetricsExtension.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.tck.optional;
17 |
18 | import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor;
19 | import org.jboss.arquillian.core.spi.LoadableExtension;
20 |
21 | public class JaxRsMetricsExtension implements LoadableExtension {
22 |
23 | @Override
24 | public void register(ExtensionBuilder extensionBuilder) {
25 | extensionBuilder.service(ProtocolArchiveProcessor.class, JaxRsMetricsActivatingProcessor.class);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # ignore .svn metadata files
2 | .svn
3 | # ignore Maven generated target folders
4 | ~
5 | target
6 | # ignore downloaded maven
7 | /tools/maven
8 | /tools/maven.zip
9 | # ignore eclipse files
10 | .project
11 | .classpath
12 | .settings
13 | .metadata
14 | .checkstyle
15 | # ignore m2e annotation processing files
16 | .factorypath
17 | # ignore IDEA files
18 | *.iml
19 | *.ipr
20 | *.iws
21 | .idea
22 | # ignore NetBeans files
23 | nbactions.xml
24 | nb-configuration.xml
25 | catalog.xml
26 | #
27 | maven-ant-tasks.jar
28 | test-output
29 | transaction.log
30 | # vim files
31 | *.swp
32 | /.gitk-tmp.*
33 | atlassian-ide-plugin.xml
34 | # temp files
35 | *~
36 | # maven versions plugin
37 | pom.xml.versionsBackup
38 | # hprof dumps
39 | /*.hprof
40 | # ignore 'randomly' strewn around logs
41 | server.log
42 | # ignore java crashes
43 | hs_err_pid*.log
44 | # H2 databases produced by tests
45 | *.h2.db
46 | # JBoss transaction generated files
47 | PutObjectStoreDirHere
48 | # ignore mvn-rpmbuild repo
49 | /.m2
50 | # ignore eap repo
51 | local-repo-eap
52 |
53 | #These keep hanging around
54 | arquillian/*/server.log*
55 | client/shade/dependency-reduced-pom.xml
56 |
57 | #OS X stuff
58 | .DS_Store
59 |
60 | # Zanata files
61 | **/.zanata-cache/
62 |
63 | .cache
64 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/MetricName.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.interceptors;
17 |
18 | import jakarta.enterprise.inject.spi.AnnotatedMember;
19 | import jakarta.enterprise.inject.spi.InjectionPoint;
20 |
21 | public interface MetricName {
22 |
23 | String of(InjectionPoint point);
24 |
25 | String of(AnnotatedMember> member);
26 |
27 | // TODO: expose an SPI so that external strategies can be provided. For example, Camel CDI could provide a property placeholder resolution strategy.
28 | String of(String attribute);
29 | }
30 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/MetricNameFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.interceptors;
17 |
18 | import java.util.Collections;
19 |
20 | import jakarta.enterprise.context.ApplicationScoped;
21 | import jakarta.enterprise.inject.Produces;
22 | import jakarta.enterprise.inject.spi.BeanManager;
23 |
24 | @ApplicationScoped
25 | public class MetricNameFactory {
26 |
27 | @Produces
28 | @ApplicationScoped
29 | MetricName metricName(BeanManager manager) {
30 | return new SeMetricName(Collections.emptySet()); // TODO
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/cdi/CDIAnnotationInfoAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter.cdi;
19 |
20 | import java.lang.annotation.Annotation;
21 |
22 | import io.smallrye.metrics.elementdesc.AnnotationInfo;
23 | import io.smallrye.metrics.elementdesc.adapter.AnnotationInfoAdapter;
24 |
25 | public class CDIAnnotationInfoAdapter implements AnnotationInfoAdapter {
26 |
27 | @Override
28 | public AnnotationInfo convert(Annotation annotation) {
29 | return new CDIAnnotationInfo(annotation);
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/BeanInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc;
19 |
20 | import java.lang.annotation.Annotation;
21 |
22 | public interface BeanInfo {
23 |
24 | String getSimpleName();
25 |
26 | String getPackageName();
27 |
28 | AnnotationInfo getAnnotation(Class metric);
29 |
30 | boolean isAnnotationPresent(Class metric);
31 |
32 | /**
33 | * Returns BeanInfo of its superclass or null if there is no superclass.
34 | */
35 | BeanInfo getSuperclass();
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/MemberInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc;
19 |
20 | import java.lang.annotation.Annotation;
21 |
22 | public interface MemberInfo {
23 |
24 | MemberType getMemberType();
25 |
26 | String getDeclaringClassName();
27 |
28 | String getDeclaringClassSimpleName();
29 |
30 | String getName();
31 |
32 | boolean isAnnotationPresent(Class metric);
33 |
34 | AnnotationInfo getAnnotation(Class metric);
35 |
36 | String[] getParameterTypeNames();
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/cdi/CDIMemberInfoAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter.cdi;
19 |
20 | import java.lang.reflect.AnnotatedElement;
21 | import java.lang.reflect.Member;
22 |
23 | import io.smallrye.metrics.elementdesc.MemberInfo;
24 | import io.smallrye.metrics.elementdesc.adapter.MemberInfoAdapter;
25 |
26 | public class CDIMemberInfoAdapter implements MemberInfoAdapter {
27 |
28 | @Override
29 | public MemberInfo convert(T input) {
30 | return new CDIMemberInfo(input);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/testsuite/common/src/main/java/io/smallrye/metrics/testsuite/MetricsExtension.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.testsuite;
17 |
18 | import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
19 | import org.jboss.arquillian.core.spi.LoadableExtension;
20 |
21 | /**
22 | *
23 | * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
24 | *
25 | * Date: 6/25/18
26 | */
27 | public class MetricsExtension implements LoadableExtension {
28 |
29 | @Override
30 | public void register(ExtensionBuilder extensionBuilder) {
31 | extensionBuilder.service(ApplicationArchiveProcessor.class, ArchiveProcessor.class);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/stereotype/stereotypes/CountMe.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.stereotype.stereotypes;
19 |
20 | import java.lang.annotation.ElementType;
21 | import java.lang.annotation.Retention;
22 | import java.lang.annotation.RetentionPolicy;
23 | import java.lang.annotation.Target;
24 |
25 | import jakarta.enterprise.inject.Stereotype;
26 |
27 | import org.eclipse.microprofile.metrics.annotation.Counted;
28 |
29 | @Stereotype
30 | @Retention(RetentionPolicy.RUNTIME)
31 | @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
32 | @Counted
33 | public @interface CountMe {
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/histogram/TestingClock.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.histogram;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import io.smallrye.metrics.app.Clock;
6 |
7 | public class TestingClock extends Clock {
8 | private final long initialTicksInNanos;
9 | long ticksInNanos;
10 |
11 | public TestingClock(long initialTicksInNanos) {
12 | this.initialTicksInNanos = initialTicksInNanos;
13 | this.ticksInNanos = initialTicksInNanos;
14 | }
15 |
16 | public TestingClock() {
17 | this(0L);
18 | }
19 |
20 | public synchronized void addNanos(long nanos) {
21 | ticksInNanos += nanos;
22 | }
23 |
24 | public synchronized void addSeconds(long seconds) {
25 | ticksInNanos += TimeUnit.SECONDS.toNanos(seconds);
26 | }
27 |
28 | public synchronized void addMillis(long millis) {
29 | ticksInNanos += TimeUnit.MILLISECONDS.toNanos(millis);
30 | }
31 |
32 | public synchronized void addHours(long hours) {
33 | ticksInNanos += TimeUnit.HOURS.toNanos(hours);
34 | }
35 |
36 | @Override
37 | public synchronized long getTick() {
38 | return ticksInNanos;
39 | }
40 |
41 | @Override
42 | public synchronized long getTime() {
43 | return TimeUnit.NANOSECONDS.toMillis(ticksInNanos - initialTicksInNanos);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/mbean/MGaugeImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Copyright 2017 Red Hat, Inc, and individual contributors.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | * /
17 | */
18 | package io.smallrye.metrics.mbean;
19 |
20 | import org.eclipse.microprofile.metrics.Gauge;
21 |
22 | import io.smallrye.metrics.JmxWorker;
23 |
24 | /**
25 | * @author hrupp
26 | */
27 | public class MGaugeImpl implements Gauge {
28 |
29 | private final String mBeanExpression;
30 | private final JmxWorker worker;
31 |
32 | public MGaugeImpl(JmxWorker worker, String mBeanExpression) {
33 | this.worker = worker;
34 | this.mBeanExpression = mBeanExpression;
35 | }
36 |
37 | @Override
38 | public Number getValue() {
39 | return worker.getValue(mBeanExpression);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/testsuite/common/src/main/java/io/smallrye/metrics/testsuite/MetricsInitializer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.testsuite;
17 |
18 | import java.io.IOException;
19 |
20 | import jakarta.enterprise.context.ApplicationScoped;
21 | import jakarta.enterprise.context.Initialized;
22 | import jakarta.enterprise.event.Observes;
23 |
24 | import io.smallrye.metrics.setup.JmxRegistrar;
25 |
26 | /**
27 | * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
28 | *
29 | * Date: 6/29/18
30 | */
31 | @ApplicationScoped
32 | public class MetricsInitializer {
33 | void init(@Observes @Initialized(ApplicationScoped.class) Object ignored) throws IOException {
34 | JmxRegistrar registrar = new JmxRegistrar();
35 | registrar.init();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/resources/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
24 |
25 | jaxrsmetrics
26 | io.smallrye.metrics.jaxrs.JaxRsMetricsServletFilter
27 | true
28 |
29 |
30 | jaxrsmetrics
31 | /*
32 |
33 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/exporters/SomeHistogram.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.exporters;
19 |
20 | import org.eclipse.microprofile.metrics.Histogram;
21 | import org.eclipse.microprofile.metrics.Snapshot;
22 |
23 | public class SomeHistogram implements Histogram {
24 |
25 | private Snapshot snapshot = new SomeSnapshot();
26 |
27 | @Override
28 | public void update(int value) {
29 | }
30 |
31 | @Override
32 | public void update(long value) {
33 | }
34 |
35 | @Override
36 | public long getCount() {
37 | return 0;
38 | }
39 |
40 | @Override
41 | public long getSum() {
42 | return 0;
43 | }
44 |
45 | @Override
46 | public Snapshot getSnapshot() {
47 | return snapshot;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/reusability/ReuseMetricWithDifferingTagsBean.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.reusability;
19 |
20 | import org.eclipse.microprofile.metrics.annotation.Counted;
21 |
22 | public class ReuseMetricWithDifferingTagsBean {
23 |
24 | @Counted(name = "colorCounter", absolute = true, tags = { "color=blue" })
25 | public void colorBlue1() {
26 | }
27 |
28 | @Counted(name = "colorCounter", absolute = true, tags = { "color=red" })
29 | public void colorRed1() {
30 | }
31 |
32 | @Counted(name = "colorCounter", absolute = true, tags = { "color=blue" })
33 | public void colorBlue2() {
34 | }
35 |
36 | @Counted(name = "colorCounter", absolute = true, tags = { "color=red" })
37 | public void colorRed2() {
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/testsuite/extra/src/main/java/io/smallrye/metrics/test/HelloService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.test;
17 |
18 | import jakarta.enterprise.context.ApplicationScoped;
19 |
20 | import org.eclipse.microprofile.metrics.MetricUnits;
21 | import org.eclipse.microprofile.metrics.annotation.Counted;
22 | import org.eclipse.microprofile.metrics.annotation.Timed;
23 |
24 | @ApplicationScoped
25 | public class HelloService {
26 |
27 | @Counted(name = "hello-count", absolute = true, displayName = "Hello Count", description = "Number of hello invocations")
28 | public String hello() {
29 | return "Hello from counted method";
30 | }
31 |
32 | @Timed(unit = MetricUnits.MILLISECONDS, name = "howdy-time", absolute = true, displayName = "Howdy Time", description = "Time of howdy invocations")
33 | public String howdy() {
34 | return "Howdy from timed method";
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/exporters/Exporter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.exporters;
19 |
20 | import org.eclipse.microprofile.metrics.MetricID;
21 | import org.eclipse.microprofile.metrics.MetricRegistry;
22 |
23 | /**
24 | * @author hrupp
25 | */
26 | public interface Exporter {
27 |
28 | StringBuilder exportOneScope(MetricRegistry.Type scope);
29 |
30 | StringBuilder exportAllScopes();
31 |
32 | String getContentType();
33 |
34 | /**
35 | * Exports just one metric obtained from a scope using its MetricID.
36 | */
37 | StringBuilder exportOneMetric(MetricRegistry.Type scope, MetricID metricID);
38 |
39 | /**
40 | * Exports all metrics with the given name inside the given scope.
41 | */
42 | StringBuilder exportMetricsByName(MetricRegistry.Type scope, String name);
43 | }
44 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/dependent/DependentScopedBeanWithMetrics.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.smallrye.metrics.test.dependent;
18 |
19 | import org.eclipse.microprofile.metrics.annotation.ConcurrentGauge;
20 | import org.eclipse.microprofile.metrics.annotation.Counted;
21 | import org.eclipse.microprofile.metrics.annotation.Metered;
22 | import org.eclipse.microprofile.metrics.annotation.Timed;
23 |
24 | public class DependentScopedBeanWithMetrics {
25 |
26 | @Counted(name = "counter", absolute = true)
27 | public void countedMethod() {
28 |
29 | }
30 |
31 | @Metered(name = "meter", absolute = true)
32 | public void meteredMethod() {
33 |
34 | }
35 |
36 | @Timed(name = "timer", absolute = true)
37 | public void timedMethod() {
38 |
39 | }
40 |
41 | @ConcurrentGauge(name = "cgauge", absolute = true)
42 | public void cGaugedMethod() {
43 |
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/ExtendedMetadataAndTags.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics;
19 |
20 | import java.util.List;
21 |
22 | import org.eclipse.microprofile.metrics.Tag;
23 |
24 | public class ExtendedMetadataAndTags {
25 |
26 | private final ExtendedMetadata metadata;
27 |
28 | private final List tags;
29 |
30 | public ExtendedMetadataAndTags(ExtendedMetadata metadata, List tags) {
31 | this.metadata = metadata;
32 | this.tags = tags;
33 | }
34 |
35 | public ExtendedMetadata getMetadata() {
36 | return metadata;
37 | }
38 |
39 | public List getTags() {
40 | return tags;
41 | }
42 |
43 | @Override
44 | public String toString() {
45 | return "ExtendedMetadataAndTags{" +
46 | "metadata=" + metadata +
47 | ", tags=" + tags +
48 | '}';
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/exporters/SomeMeter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.exporters;
19 |
20 | import org.eclipse.microprofile.metrics.Meter;
21 |
22 | /**
23 | * Provides a second (useless) Meter implementation
24 | */
25 | public class SomeMeter implements Meter {
26 | @Override
27 | public void mark() {
28 |
29 | }
30 |
31 | @Override
32 | public void mark(long l) {
33 |
34 | }
35 |
36 | @Override
37 | public long getCount() {
38 | return 0;
39 | }
40 |
41 | @Override
42 | public double getFifteenMinuteRate() {
43 | return 0;
44 | }
45 |
46 | @Override
47 | public double getFiveMinuteRate() {
48 | return 0;
49 | }
50 |
51 | @Override
52 | public double getMeanRate() {
53 | return 0;
54 | }
55 |
56 | @Override
57 | public double getOneMinuteRate() {
58 | return 0;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/mbean/MCounterImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * Copyright 2017 Red Hat, Inc, and individual contributors.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | * /
17 | */
18 | package io.smallrye.metrics.mbean;
19 |
20 | import org.eclipse.microprofile.metrics.Counter;
21 |
22 | import io.smallrye.metrics.JmxWorker;
23 | import io.smallrye.metrics.SmallRyeMetricsMessages;
24 |
25 | /**
26 | * @author hrupp
27 | */
28 | public class MCounterImpl implements Counter {
29 | private final String mbeanExpression;
30 | private final JmxWorker worker;
31 |
32 | public MCounterImpl(JmxWorker worker, String mbeanExpression) {
33 | this.mbeanExpression = mbeanExpression;
34 | this.worker = worker;
35 | }
36 |
37 | @Override
38 | public void inc() {
39 | throw SmallRyeMetricsMessages.msg.mustNotBeCalled();
40 | }
41 |
42 | @Override
43 | public void inc(long n) {
44 | throw SmallRyeMetricsMessages.msg.mustNotBeCalled();
45 | }
46 |
47 | @Override
48 | public long getCount() {
49 | return worker.getValue(mbeanExpression).longValue();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/README.adoc:
--------------------------------------------------------------------------------
1 | :microprofile-metrics: https://github.com/eclipse/microprofile-metrics/
2 | :ci: https://github.com/smallrye/smallrye-metrics/actions?query=workflow%3A%22SmallRye+Build%22
3 | :sonar: https://sonarcloud.io/dashboard?id=smallrye_smallrye-metrics
4 |
5 | image:https://github.com/smallrye/smallrye-metrics/workflows/SmallRye%20Build/badge.svg?branch=main[link={ci}]
6 | image:https://sonarcloud.io/api/project_badges/measure?project=smallrye_smallrye-metrics&metric=alert_status["Quality Gate Status", link={sonar}]
7 | image:https://img.shields.io/github/license/smallrye/smallrye-metrics.svg["License", link="http://www.apache.org/licenses/LICENSE-2.0"]
8 | image:https://img.shields.io/maven-central/v/io.smallrye/smallrye-metrics?color=green[]
9 |
10 | = SmallRye Metrics (Deprecated)
11 |
12 | SmallRye Metrics is no longer under development and was replaced by OpenTelemetry Metrics. In the future,
13 | please refer to SmallRye OpenTelemetry: https://github.com/smallrye/smallrye-opentelemetry
14 |
15 | SmallRye Metrics is an implementation of {microprofile-metrics}[Eclipse MicroProfile Metrics].
16 |
17 | == Instructions
18 |
19 | Compile and install this project:
20 |
21 | [source,bash]
22 | ----
23 | mvn clean install
24 | ----
25 |
26 | === Project structure
27 |
28 | * link:implementation[] - Implementation of the Eclipse MicroProfile Metrics API.
29 | * link:tck[] - Test suite to run the implementation against the Eclipse MicroProfile Metrics TCK.
30 |
31 | === Contributing
32 |
33 | Please refer to our Wiki for the https://github.com/smallrye/smallrye-parent/wiki[Contribution Guidelines].
34 |
35 | === Links
36 |
37 | * http://github.com/smallrye/smallrye-metrics/[Project Homepage]
38 | * {microprofile-metrics}[Eclipse MicroProfile Metrics]
39 |
40 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/exporters/SomeSnapshot.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.exporters;
19 |
20 | import java.io.OutputStream;
21 |
22 | import org.eclipse.microprofile.metrics.Snapshot;
23 |
24 | public class SomeSnapshot extends Snapshot {
25 | @Override
26 | public double getValue(double quantile) {
27 | return 0;
28 | }
29 |
30 | @Override
31 | public long[] getValues() {
32 | return new long[0];
33 | }
34 |
35 | @Override
36 | public int size() {
37 | return 0;
38 | }
39 |
40 | @Override
41 | public long getMax() {
42 | return 0;
43 | }
44 |
45 | @Override
46 | public double getMean() {
47 | return 0;
48 | }
49 |
50 | @Override
51 | public long getMin() {
52 | return 0;
53 | }
54 |
55 | @Override
56 | public double getStdDev() {
57 | return 0;
58 | }
59 |
60 | @Override
61 | public void dump(OutputStream output) {
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Meter_Method_Test.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.test.initialization;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertTrue;
5 |
6 | import jakarta.inject.Inject;
7 |
8 | import org.eclipse.microprofile.metrics.MetricID;
9 | import org.eclipse.microprofile.metrics.MetricRegistry;
10 | import org.eclipse.microprofile.metrics.annotation.Metered;
11 | import org.jboss.arquillian.container.test.api.Deployment;
12 | import org.jboss.arquillian.junit.Arquillian;
13 | import org.jboss.shrinkwrap.api.ShrinkWrap;
14 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
15 | import org.jboss.shrinkwrap.api.spec.WebArchive;
16 | import org.junit.Test;
17 | import org.junit.runner.RunWith;
18 |
19 | @RunWith(Arquillian.class)
20 | public class Initialization_Meter_Method_Test {
21 |
22 | @Deployment
23 | public static WebArchive deployment() {
24 | return ShrinkWrap.create(WebArchive.class)
25 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
26 | .addClasses(BeanWithMeter_Method.class);
27 | }
28 |
29 | @Inject
30 | MetricRegistry registry;
31 |
32 | @Inject
33 | BeanWithMeter_Method bean;
34 |
35 | @Test
36 | public void test() {
37 | assertTrue(registry.getMeters().containsKey(new MetricID("meter_method")));
38 | bean.meterMethod();
39 | assertEquals(1, registry.getMeters().get(new MetricID("meter_method")).getCount());
40 | }
41 |
42 | public static class BeanWithMeter_Method {
43 |
44 | @Metered(name = "meter_method", absolute = true)
45 | public void meterMethod() {
46 |
47 | }
48 |
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/exporters/ExporterUtilTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.exporters;
18 |
19 | import org.eclipse.microprofile.metrics.MetricUnits;
20 | import org.junit.Assert;
21 | import org.junit.Test;
22 |
23 | /**
24 | *
25 | * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
26 | *
27 | * Date: 3/23/18
28 | */
29 | public class ExporterUtilTest {
30 | @Test
31 | public void shouldScaleNanosToSecods() {
32 | Double out = ExporterUtil.convertNanosTo(1.0, MetricUnits.MINUTES);
33 | Assert.assertEquals(out, 0.0, 1e-10);
34 | }
35 |
36 | @Test
37 | public void shouldScaleNanosToMillis() {
38 | Double out = ExporterUtil.convertNanosTo(1.0, MetricUnits.MILLISECONDS);
39 | Assert.assertEquals(out, 0.000001, 1e-10);
40 | }
41 |
42 | @Test
43 | public void testScaleHoursToSeconds() {
44 | String foo = MetricUnits.HOURS;
45 | Double out = ExporterUtil.convertNanosTo(3 * 3600 * 1000_000_000., foo);
46 | Assert.assertEquals(out, 3., 1e-10);
47 | }
48 | }
--------------------------------------------------------------------------------
/testsuite/common/src/main/java/io/smallrye/metrics/testsuite/ArchiveProcessor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.testsuite;
17 |
18 | import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
19 | import org.jboss.arquillian.test.spi.TestClass;
20 | import org.jboss.shrinkwrap.api.Archive;
21 | import org.jboss.shrinkwrap.api.container.ResourceContainer;
22 |
23 | /**
24 | * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
25 | *
26 | * Date: 6/19/18
27 | */
28 | public class ArchiveProcessor implements ApplicationArchiveProcessor {
29 |
30 | @Override
31 | public void process(Archive> applicationArchive, TestClass testClass) {
32 | if (applicationArchive instanceof ResourceContainer) {
33 | ResourceContainer archive = (ResourceContainer) applicationArchive;
34 | archive.addAsResource("io/smallrye/metrics/base-metrics.properties",
35 | "/io/smallrye/metrics/base-metrics.properties");
36 | } else {
37 | throw new IllegalStateException(this.getClass().getCanonicalName() + " works only with ResourceContainers");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/testsuite/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
20 | 4.0.0
21 |
22 |
23 | io.smallrye
24 | smallrye-metrics-parent
25 | 4.0.1-SNAPSHOT
26 |
27 |
28 | smallrye-metrics-testsuite-parent
29 | pom
30 |
31 | SmallRye: MicroProfile Metrics Test Suite Parent
32 |
33 |
34 | common
35 | api-tck
36 | extra
37 | rest-tck
38 | optional-tck
39 |
40 |
41 |
42 |
43 |
44 | org.sonatype.plugins
45 | nexus-staging-maven-plugin
46 |
47 | true
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/testsuite/extra/src/main/java/io/smallrye/metrics/test/MetricsSummary.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.test;
17 |
18 | import jakarta.enterprise.context.ApplicationScoped;
19 | import jakarta.inject.Inject;
20 |
21 | import org.eclipse.microprofile.metrics.MetricRegistry;
22 | import org.eclipse.microprofile.metrics.annotation.RegistryType;
23 |
24 | @ApplicationScoped
25 | public class MetricsSummary {
26 |
27 | @Inject
28 | @RegistryType(type = MetricRegistry.Type.BASE)
29 | private MetricRegistry baseMetrics;
30 |
31 | @Inject
32 | @RegistryType(type = MetricRegistry.Type.VENDOR)
33 | private MetricRegistry vendorMetrics;
34 |
35 | @Inject
36 | @RegistryType(type = MetricRegistry.Type.APPLICATION)
37 | private MetricRegistry appMetrics;
38 |
39 | @Inject
40 | private MetricRegistry defaultMetrics;
41 |
42 | public MetricRegistry getBaseMetrics() {
43 | return baseMetrics;
44 | }
45 |
46 | public MetricRegistry getVendorMetrics() {
47 | return vendorMetrics;
48 | }
49 |
50 | public MetricRegistry getAppMetrics() {
51 | return appMetrics;
52 | }
53 |
54 | public MetricRegistry getDefaultMetrics() {
55 | return defaultMetrics;
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/inject/NonReusableMetricInjectionBean.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.inject;
19 |
20 | import jakarta.inject.Inject;
21 |
22 | import org.eclipse.microprofile.metrics.Counter;
23 | import org.eclipse.microprofile.metrics.annotation.Counted;
24 | import org.eclipse.microprofile.metrics.annotation.Metric;
25 |
26 | public class NonReusableMetricInjectionBean {
27 |
28 | @Counted(name = "mycounter", absolute = true, tags = { "k=v1" })
29 | public void counter() {
30 | }
31 |
32 | @Counted(name = "mycounter", absolute = true, tags = { "k=v2" })
33 | public void counter2() {
34 | }
35 |
36 | // each time this bean gets constructed and injected, change the values of metrics to verify that
37 | // we can inject metrics using an annotated method parameter
38 | @Inject
39 | public void increaseCountersOnInjecting(
40 | @Metric(name = "mycounter", absolute = true, tags = { "k=v1" }) Counter counter1,
41 | @Metric(name = "mycounter", absolute = true, tags = { "k=v2" }) Counter counter2) {
42 | counter1.inc(2);
43 | counter2.inc(3);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/testsuite/common/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
20 | 4.0.0
21 |
22 |
23 | io.smallrye
24 | smallrye-metrics-testsuite-parent
25 | 4.0.1-SNAPSHOT
26 |
27 |
28 | smallrye-metrics-testsuite-common
29 |
30 | SmallRye: MicroProfile Metrics Test Suite Common
31 |
32 |
33 |
34 | io.smallrye
35 | smallrye-metrics
36 | ${project.version}
37 |
38 |
39 | jakarta.enterprise
40 | jakarta.enterprise.cdi-api
41 | provided
42 |
43 |
44 | org.jboss.arquillian.container
45 | arquillian-container-test-spi
46 | provided
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Counter_Constructor_Test.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.test.initialization;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 |
6 | import jakarta.inject.Inject;
7 |
8 | import org.eclipse.microprofile.metrics.Counter;
9 | import org.eclipse.microprofile.metrics.MetricID;
10 | import org.eclipse.microprofile.metrics.MetricRegistry;
11 | import org.eclipse.microprofile.metrics.annotation.Counted;
12 | import org.jboss.arquillian.container.test.api.Deployment;
13 | import org.jboss.arquillian.junit.Arquillian;
14 | import org.jboss.shrinkwrap.api.ShrinkWrap;
15 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
16 | import org.jboss.shrinkwrap.api.spec.WebArchive;
17 | import org.junit.Test;
18 | import org.junit.runner.RunWith;
19 |
20 | @RunWith(Arquillian.class)
21 | public class Initialization_Counter_Constructor_Test {
22 |
23 | @Deployment
24 | public static WebArchive deployment() {
25 | return ShrinkWrap.create(WebArchive.class)
26 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
27 | .addClasses(BeanWithCounter_Constructor.class);
28 | }
29 |
30 | @Inject
31 | MetricRegistry registry;
32 |
33 | @Test
34 | public void test() {
35 | Counter metricFromConstructor = registry.getCounters()
36 | .get(new MetricID(
37 | "io.smallrye.metrics.test.initialization.Initialization_Counter_Constructor_Test" +
38 | "$BeanWithCounter_Constructor.BeanWithCounter_Constructor"));
39 | assertNotNull(metricFromConstructor);
40 | assertEquals(1, registry.getCounters().size());
41 | }
42 |
43 | private static class BeanWithCounter_Constructor {
44 |
45 | @Counted
46 | public BeanWithCounter_Constructor() {
47 |
48 | }
49 |
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/ExtendedMetadataBuilderTest.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics;
2 |
3 | import org.eclipse.microprofile.metrics.MetricType;
4 | import org.junit.Assert;
5 | import org.junit.Test;
6 |
7 | public class ExtendedMetadataBuilderTest {
8 |
9 | @Test
10 | public void testBuilder() {
11 | //given
12 | String displayName = "display name";
13 | String name = "name";
14 | String description = "description";
15 | String mbean = "mbean";
16 | String openMetricsKeyOverride = "openMetricsKeyOverride";
17 | String unit = "unit";
18 |
19 | //when
20 | ExtendedMetadata extendedMetadata = ExtendedMetadata.builder()
21 | .withType(MetricType.CONCURRENT_GAUGE)
22 | .withDisplayName(displayName)
23 | .withName(name)
24 | .withDescription(description)
25 | .withMbean(mbean)
26 | .withOpenMetricsKeyOverride(openMetricsKeyOverride)
27 | .withUnit(unit)
28 | .skipsScopeInOpenMetricsExportCompletely(false)
29 | .prependsScopeToOpenMetricsName(false)
30 | .multi(false)
31 | .build();
32 |
33 | //then
34 | Assert.assertEquals(displayName, extendedMetadata.getDisplayName());
35 | Assert.assertEquals(name, extendedMetadata.getName());
36 | Assert.assertEquals(mbean, extendedMetadata.getMbean());
37 | Assert.assertEquals(openMetricsKeyOverride, extendedMetadata.getOpenMetricsKeyOverride().get());
38 | Assert.assertEquals(unit, extendedMetadata.unit().get());
39 | Assert.assertEquals(description, extendedMetadata.description().get());
40 | Assert.assertFalse(extendedMetadata.isSkipsScopeInOpenMetricsExportCompletely());
41 | Assert.assertFalse(extendedMetadata.isMulti());
42 | Assert.assertFalse(extendedMetadata.prependsScopeToOpenMetricsName().get());
43 | Assert.assertEquals(MetricType.CONCURRENT_GAUGE, extendedMetadata.getTypeRaw());
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/MetadataList.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics;
18 |
19 | import java.util.ArrayList;
20 | import java.util.Collections;
21 | import java.util.List;
22 |
23 | /**
24 | * Class holding the metadata for base, vendor and applications
25 | *
26 | * @author hrupp
27 | */
28 | public class MetadataList {
29 |
30 | private List base;
31 | private List vendor;
32 |
33 | public List getBase() {
34 | if (base == null) {
35 | base = new ArrayList<>(1);
36 | }
37 | return base;
38 | }
39 |
40 | public void setBase(List base) {
41 | this.base = base;
42 | }
43 |
44 | public List getVendor() {
45 | if (vendor == null) {
46 | vendor = new ArrayList<>(1);
47 | }
48 | return vendor;
49 | }
50 |
51 | public void setVendor(List vendor) {
52 | this.vendor = vendor;
53 | }
54 |
55 | public List get(String domain) {
56 | switch (domain) {
57 | case "base":
58 | return getBase();
59 | case "vendor":
60 | return getVendor();
61 |
62 | default:
63 | return Collections.emptyList();
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Counter_Method_Test.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.test.initialization;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import jakarta.annotation.security.PermitAll;
6 | import jakarta.enterprise.context.ApplicationScoped;
7 | import jakarta.inject.Inject;
8 |
9 | import org.eclipse.microprofile.metrics.MetricID;
10 | import org.eclipse.microprofile.metrics.MetricRegistry;
11 | import org.eclipse.microprofile.metrics.annotation.Counted;
12 | import org.jboss.arquillian.container.test.api.Deployment;
13 | import org.jboss.arquillian.junit.Arquillian;
14 | import org.jboss.shrinkwrap.api.ShrinkWrap;
15 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
16 | import org.jboss.shrinkwrap.api.spec.WebArchive;
17 | import org.junit.Assert;
18 | import org.junit.Test;
19 | import org.junit.runner.RunWith;
20 |
21 | @RunWith(Arquillian.class)
22 | public class Initialization_Counter_Method_Test {
23 |
24 | @Deployment
25 | public static WebArchive deployment() {
26 | return ShrinkWrap.create(WebArchive.class)
27 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
28 | .addClasses(BeanWithCounter_Method.class);
29 | }
30 |
31 | @Inject
32 | MetricRegistry registry;
33 |
34 | @Inject
35 | BeanWithCounter_Method bean;
36 |
37 | @Test
38 | public void test() {
39 | assertTrue(registry.getCounters().containsKey(new MetricID("counter_method")));
40 | assertTrue(registry.getCounters((metricID, metric) -> metricID.getName().contains("irrelevant")).isEmpty());
41 | bean.counterMethod();
42 | Assert.assertEquals(1, registry.getCounters().get(new MetricID("counter_method")).getCount());
43 | }
44 |
45 | @ApplicationScoped
46 | public static class BeanWithCounter_Method {
47 |
48 | @Counted(name = "counter_method", absolute = true)
49 | public void counterMethod() {
50 |
51 | }
52 |
53 | @PermitAll
54 | public void irrelevantAnnotatedMethod() {
55 |
56 | }
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/coverage/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | io.smallrye
8 | smallrye-metrics-parent
9 | 4.0.1-SNAPSHOT
10 |
11 |
12 | smallrye-metrics-coverage
13 | pom
14 |
15 | SmallRye: Metrics Coverage
16 |
17 |
18 |
19 | io.smallrye
20 | smallrye-metrics
21 | ${project.version}
22 |
23 |
24 |
25 |
26 |
27 |
28 | org.jacoco
29 | jacoco-maven-plugin
30 |
31 |
32 | merge
33 |
34 | merge
35 |
36 |
37 |
38 |
39 | .
40 |
41 | **/*.exec
42 |
43 |
44 |
45 |
46 |
47 |
48 | prepare-agent
49 | none
50 |
51 | prepare-agent
52 |
53 |
54 |
55 | aggregate-report
56 | verify
57 |
58 | report-aggregate
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/doc/modules/ROOT/pages/base-and-vendor-metrics.adoc:
--------------------------------------------------------------------------------
1 | [[base-vendor-metrics]]
2 | = Activating base and vendor metrics
3 |
4 | Base and vendor metrics are registered at deployment time by the `io.smallrye.metrics.setup.JmxRegistrar`
5 | class. It is necessary to instantiate it and invoke `jmxRegistrar.init()`. The definitions of base and vendor
6 | metrics are read from the file `base-metrics.properties` and `vendor-metrics.properties`, which should be available
7 | as a resource under the path `/io/smallrye/metrics/*-metrics.properties` for either the classloader that
8 | loaded the `JmxRegistrar` class (higher precedence) or the thread context class loader (lower precedence).
9 |
10 | These files reference management MBeans as the sources of metric values, so they can only be used for metrics
11 | that are obtained from MBeans, and only in cases when JMX is available at runtime. Furthermore, only
12 | Counters and Gauges are currently supported through this file. In other cases, a different
13 | approach must be devised to register base and vendor metrics (but the specification does not require
14 | any base metrics of different types).
15 |
16 | Note that JAX-RS metrics are a bit special and use a different mechanism. For info, see
17 | xref:jaxrs-metrics.adoc[JAX-RS Metrics].
18 |
19 |
20 | == base-metrics.properties and vendor-metrics.properties file schema
21 | These files list all base and vendor metrics through usage of a regular Java properties file.
22 | The schema is as following:
23 |
24 | For simple metrics (where one MBean property corresponds to one metric), you will need these properties:
25 | |===
26 | | Property key | Property meaning
27 | | METRIC_NAME.displayName
28 | | The display name of the metric
29 |
30 | | METRIC_NAME.type
31 | | The type of the metric (can be `counter` or `gauge`)
32 |
33 | | METRIC_NAME.unit
34 | | The unit of the metric as a string (you can use `none`)
35 |
36 | | METRIC_NAME.description
37 | | The description of the metric
38 |
39 | | METRIC_NAME.mbean
40 | | Reference to a JMX property including the `ObjectName` of the owning MBean.
41 | For example, `java.lang:type=ClassLoading/TotalLoadedClassCount`
42 | to obtain the total of all loaded classes in the JVM.
43 |
44 | |===
45 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/app/CounterImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | * *******************************************************************************
18 | * Copyright 2010-2013 Coda Hale and Yammer, Inc.
19 | *
20 | * Licensed under the Apache License, Version 2.0 (the "License");
21 | * you may not use this file except in compliance with the License.
22 | * You may obtain a copy of the License at
23 | *
24 | * http://www.apache.org/licenses/LICENSE-2.0
25 | *
26 | * Unless required by applicable law or agreed to in writing, software
27 | * distributed under the License is distributed on an "AS IS" BASIS,
28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 | * See the License for the specific language governing permissions and
30 | * limitations under the License.
31 | */
32 | package io.smallrye.metrics.app;
33 |
34 | import java.util.concurrent.atomic.LongAdder;
35 |
36 | import org.eclipse.microprofile.metrics.Counter;
37 |
38 | /**
39 | * @author hrupp
40 | */
41 | public class CounterImpl implements Counter {
42 |
43 | private final LongAdder count;
44 |
45 | public CounterImpl() {
46 | count = new LongAdder();
47 | }
48 |
49 | @Override
50 | public void inc() {
51 | count.increment();
52 | }
53 |
54 | @Override
55 | public void inc(long n) {
56 | count.add(n);
57 | }
58 |
59 | @Override
60 | public long getCount() {
61 | return count.sum();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/exporters/SomeTimer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.exporters;
19 |
20 | import java.time.Duration;
21 | import java.util.concurrent.Callable;
22 |
23 | import org.eclipse.microprofile.metrics.Snapshot;
24 | import org.eclipse.microprofile.metrics.Timer;
25 |
26 | public class SomeTimer implements Timer {
27 |
28 | private Snapshot snapshot = new SomeSnapshot();
29 |
30 | @Override
31 | public void update(Duration duration) {
32 | }
33 |
34 | @Override
35 | public T time(Callable event) throws Exception {
36 | return null;
37 | }
38 |
39 | @Override
40 | public void time(Runnable event) {
41 | }
42 |
43 | @Override
44 | public Context time() {
45 | return null;
46 | }
47 |
48 | @Override
49 | public Duration getElapsedTime() {
50 | return Duration.ZERO;
51 | }
52 |
53 | @Override
54 | public long getCount() {
55 | return 0;
56 | }
57 |
58 | @Override
59 | public double getFifteenMinuteRate() {
60 | return 0;
61 | }
62 |
63 | @Override
64 | public double getFiveMinuteRate() {
65 | return 0;
66 | }
67 |
68 | @Override
69 | public double getMeanRate() {
70 | return 0;
71 | }
72 |
73 | @Override
74 | public double getOneMinuteRate() {
75 | return 0;
76 | }
77 |
78 | @Override
79 | public Snapshot getSnapshot() {
80 | return snapshot;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/app/Reservoir.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | * *******************************************************************************
18 | * Copyright 2010-2013 Coda Hale and Yammer, Inc.
19 | *
20 | * Licensed under the Apache License, Version 2.0 (the "License");
21 | * you may not use this file except in compliance with the License.
22 | * You may obtain a copy of the License at
23 | *
24 | * http://www.apache.org/licenses/LICENSE-2.0
25 | *
26 | * Unless required by applicable law or agreed to in writing, software
27 | * distributed under the License is distributed on an "AS IS" BASIS,
28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 | * See the License for the specific language governing permissions and
30 | * limitations under the License.
31 | */
32 | package io.smallrye.metrics.app;
33 |
34 | import org.eclipse.microprofile.metrics.Snapshot;
35 |
36 | /**
37 | * A statistically representative reservoir of a data stream.
38 | */
39 | public interface Reservoir {
40 | /**
41 | * Returns the number of values recorded.
42 | *
43 | * @return the number of values recorded
44 | */
45 | int size();
46 |
47 | /**
48 | * Adds a new recorded value to the reservoir.
49 | *
50 | * @param value a new recorded value
51 | */
52 | void update(long value);
53 |
54 | /**
55 | * Returns a snapshot of the reservoir's values.
56 | *
57 | * @return a snapshot of the reservoir's values
58 | */
59 | Snapshot getSnapshot();
60 | }
61 |
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/java/io/smallrye/metrics/tck/optional/MetricsHttpServlet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.tck.optional;
18 |
19 | import java.io.IOException;
20 | import java.util.Collections;
21 | import java.util.stream.Stream;
22 |
23 | import jakarta.inject.Inject;
24 | import jakarta.servlet.annotation.WebServlet;
25 | import jakarta.servlet.http.HttpServlet;
26 | import jakarta.servlet.http.HttpServletRequest;
27 | import jakarta.servlet.http.HttpServletResponse;
28 |
29 | import io.smallrye.metrics.MetricsRequestHandler;
30 |
31 | @WebServlet(name = "metrics-servlet", urlPatterns = "/metrics/*")
32 | public class MetricsHttpServlet extends HttpServlet {
33 |
34 | @Override
35 | protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
36 | doGet(req, resp);
37 | }
38 |
39 | @Override
40 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
41 | String requestPath = request.getRequestURI();
42 | String method = request.getMethod();
43 | Stream acceptHeaders = Collections.list(request.getHeaders("Accept")).stream();
44 |
45 | metricsHandler.handleRequest(requestPath, method, acceptHeaders, (status, message, headers) -> {
46 | headers.forEach(response::addHeader);
47 | response.setStatus(status);
48 | response.getWriter().write(message);
49 | });
50 | }
51 |
52 | @Inject
53 | private MetricsRequestHandler metricsHandler;
54 | }
55 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_ConcurrentGauge_Method_Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.initialization;
19 |
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import jakarta.inject.Inject;
23 |
24 | import org.eclipse.microprofile.metrics.MetricID;
25 | import org.eclipse.microprofile.metrics.MetricRegistry;
26 | import org.eclipse.microprofile.metrics.annotation.ConcurrentGauge;
27 | import org.jboss.arquillian.container.test.api.Deployment;
28 | import org.jboss.arquillian.junit.Arquillian;
29 | import org.jboss.shrinkwrap.api.ShrinkWrap;
30 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
31 | import org.jboss.shrinkwrap.api.spec.WebArchive;
32 | import org.junit.Test;
33 | import org.junit.runner.RunWith;
34 |
35 | @RunWith(Arquillian.class)
36 | public class Initialization_ConcurrentGauge_Method_Test {
37 |
38 | @Deployment
39 | public static WebArchive deployment() {
40 | return ShrinkWrap.create(WebArchive.class)
41 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
42 | .addClasses(BeanWithConcurrentGauge_Method.class);
43 | }
44 |
45 | @Inject
46 | MetricRegistry registry;
47 |
48 | @Test
49 | public void test() {
50 | assertTrue(registry.getConcurrentGauges().containsKey(new MetricID("cgauged_method")));
51 | }
52 |
53 | public static class BeanWithConcurrentGauge_Method {
54 |
55 | @ConcurrentGauge(name = "cgauged_method", absolute = true)
56 | public void cGaugedMethod() {
57 |
58 | }
59 |
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/java/io/smallrye/metrics/tck/rest/MetricsHttpServlet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.tck.rest;
18 |
19 | import java.io.IOException;
20 | import java.util.Collections;
21 | import java.util.stream.Stream;
22 |
23 | import jakarta.inject.Inject;
24 | import jakarta.servlet.annotation.WebServlet;
25 | import jakarta.servlet.http.HttpServlet;
26 | import jakarta.servlet.http.HttpServletRequest;
27 | import jakarta.servlet.http.HttpServletResponse;
28 |
29 | import io.smallrye.metrics.MetricsRequestHandler;
30 |
31 | /**
32 | * @author hrupp
33 | * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
34 | */
35 | @WebServlet(name = "metrics-servlet", urlPatterns = "/metrics/*")
36 | public class MetricsHttpServlet extends HttpServlet {
37 |
38 | @Override
39 | protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
40 | doGet(req, resp);
41 | }
42 |
43 | @Override
44 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
45 | String requestPath = request.getRequestURI();
46 | String method = request.getMethod();
47 | Stream acceptHeaders = Collections.list(request.getHeaders("Accept")).stream();
48 |
49 | metricsHandler.handleRequest(requestPath, method, acceptHeaders, (status, message, headers) -> {
50 | headers.forEach(response::addHeader);
51 | response.setStatus(status);
52 | response.getWriter().write(message);
53 | });
54 | }
55 |
56 | @Inject
57 | private MetricsRequestHandler metricsHandler;
58 | }
59 |
--------------------------------------------------------------------------------
/doc/modules/ROOT/pages/extended-metadata.adoc:
--------------------------------------------------------------------------------
1 | [[extended-metadata]]
2 | = Extended metadata
3 |
4 | SmallRye Metrics provides its own class for metadata, `io.smallrye.metrics.ExtendedMetadata`,
5 | which contains a few additional fields. Usage of this is not mandatory, unless you need to make
6 | use of these extra fields.
7 |
8 | The extra fields are:
9 | |===
10 | | Field | Meaning
11 | | mbean
12 | | The expression designating the JMX MBean property from which the value of this metric will be retrieved.
13 | This is meant to be used only for base and vendor metrics, see
14 | xref:base-and-vendor-metrics.adoc[Base and vendor metrics] for more information
15 |
16 | | multi
17 | | Is set to `true` if `mbean` expression contains placeholders and therefore multiple metrics can potentially
18 | be created out of this definition.
19 |
20 | | prependsScopeToOpenMetricsName
21 | | Optional configuration to prepend the microprofile scope to the metric name when it is exported
22 | to the OpenMetrics format. By default, the option is empty() and will not be taken into account.
23 | If true, the scope is prepended to the metric name when the OpenMetrics
24 | name is generated (e.g. `vendor_foo`}.
25 | If false, the scope is added to the metric tags instead (e.g. `foo{microprofile_scope="vendor"`}.
26 | This option has precedence over the global configuration (config property `smallrye.metrics.usePrefixForScope`)
27 |
28 | | skipsScopeInOpenMetricsExportCompletely
29 | | If `true`, then the metrics scope will be omitted completely when exporting the metric. For example, instead of
30 | `application_metric1`, the OpenMetrics key will be just `metric1`. This can be useful
31 | for various special compatibility use cases. However, dropping the scope means that if there are metrics with
32 | the same name under multiple scopes, they might not be distinguishable in the OpenMetrics output.
33 | This is currently not handled in any way in SmallRye, so the user should make sure this will not happen.
34 |
35 | | openMetricsKeyOverride
36 | | If set, this property overrides the OpenMetrics key under which the metric will be presented in an OpenMetrics export.
37 | Normal export rules defined by the MicroProfile Metrics specification are therefore ignored. Only applies to non-compound
38 | metrics, that is counters and gauges.
39 | |===
40 |
41 | The `ExtendedMetadata` class also comes with a fluent builder - `io.smallrye.metrics.ExtendedMetadataBuilder`.
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Counter_Method_Reused_Test.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics.test.initialization;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertTrue;
5 |
6 | import jakarta.annotation.security.PermitAll;
7 | import jakarta.inject.Inject;
8 |
9 | import org.eclipse.microprofile.metrics.MetricID;
10 | import org.eclipse.microprofile.metrics.MetricRegistry;
11 | import org.eclipse.microprofile.metrics.annotation.Counted;
12 | import org.jboss.arquillian.container.test.api.Deployment;
13 | import org.jboss.arquillian.junit.Arquillian;
14 | import org.jboss.shrinkwrap.api.ShrinkWrap;
15 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
16 | import org.jboss.shrinkwrap.api.spec.WebArchive;
17 | import org.junit.Test;
18 | import org.junit.runner.RunWith;
19 |
20 | @RunWith(Arquillian.class)
21 | public class Initialization_Counter_Method_Reused_Test {
22 |
23 | @Deployment
24 | public static WebArchive deployment() {
25 | return ShrinkWrap.create(WebArchive.class)
26 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
27 | .addClasses(BeanWithCounter_Method_Reused.class);
28 | }
29 |
30 | @Inject
31 | private MetricRegistry registry;
32 |
33 | @Inject
34 | private BeanWithCounter_Method_Reused bean;
35 |
36 | @Test
37 | public void test() {
38 | assertTrue(registry.getCounters().containsKey(new MetricID("counter_method")));
39 | assertTrue(registry.getCounters((metricID, metric) -> metricID.getName().contains("irrelevant")).isEmpty());
40 | bean.counterMethod();
41 | assertEquals(1, registry.getCounters().get(new MetricID("counter_method")).getCount());
42 | bean.counterMethod2();
43 | assertEquals(2, registry.getCounters().get(new MetricID("counter_method")).getCount());
44 | assertEquals(1, registry.getCounters().size());
45 | }
46 |
47 | public static class BeanWithCounter_Method_Reused {
48 |
49 | @Counted(name = "counter_method", absolute = true)
50 | public void counterMethod() {
51 |
52 | }
53 |
54 | @Counted(name = "counter_method", absolute = true)
55 | public void counterMethod2() {
56 |
57 | }
58 |
59 | @PermitAll
60 | public void irrelevantAnnotatedMethod() {
61 |
62 | }
63 |
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Timer_Method_Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.initialization;
19 |
20 | import static org.junit.Assert.assertEquals;
21 | import static org.junit.Assert.assertTrue;
22 |
23 | import jakarta.inject.Inject;
24 |
25 | import org.eclipse.microprofile.metrics.MetricID;
26 | import org.eclipse.microprofile.metrics.MetricRegistry;
27 | import org.eclipse.microprofile.metrics.annotation.Timed;
28 | import org.jboss.arquillian.container.test.api.Deployment;
29 | import org.jboss.arquillian.junit.Arquillian;
30 | import org.jboss.shrinkwrap.api.ShrinkWrap;
31 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
32 | import org.jboss.shrinkwrap.api.spec.WebArchive;
33 | import org.junit.Test;
34 | import org.junit.runner.RunWith;
35 |
36 | @RunWith(Arquillian.class)
37 | public class Initialization_Timer_Method_Test {
38 |
39 | @Deployment
40 | public static WebArchive deployment() {
41 | return ShrinkWrap.create(WebArchive.class)
42 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
43 | .addClasses(BeanWithTimer_Method.class);
44 | }
45 |
46 | @Inject
47 | MetricRegistry registry;
48 |
49 | @Inject
50 | BeanWithTimer_Method bean;
51 |
52 | @Test
53 | public void test() {
54 | assertTrue(registry.getTimers().containsKey(new MetricID("timed_method")));
55 | bean.timedMethod();
56 | assertEquals(1, registry.getTimers().get(new MetricID("timed_method")).getCount());
57 | }
58 |
59 | public static class BeanWithTimer_Method {
60 |
61 | @Timed(name = "timed_method", absolute = true)
62 | public void timedMethod() {
63 |
64 | }
65 |
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/registry/AllMetricsOfGivenTypeTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.test.registry;
17 |
18 | import static org.junit.Assert.assertEquals;
19 | import static org.junit.Assert.assertFalse;
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import java.util.SortedMap;
23 |
24 | import jakarta.inject.Inject;
25 |
26 | import org.eclipse.microprofile.metrics.MetricID;
27 | import org.eclipse.microprofile.metrics.Timer;
28 | import org.jboss.arquillian.container.test.api.Deployment;
29 | import org.jboss.arquillian.junit.Arquillian;
30 | import org.jboss.shrinkwrap.api.ShrinkWrap;
31 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
32 | import org.jboss.shrinkwrap.api.spec.WebArchive;
33 | import org.junit.Test;
34 | import org.junit.runner.RunWith;
35 |
36 | import io.smallrye.metrics.test.HelloService;
37 | import io.smallrye.metrics.test.MetricsSummary;
38 |
39 | @RunWith(Arquillian.class)
40 | public class AllMetricsOfGivenTypeTest {
41 | @Inject
42 | HelloService hello;
43 |
44 | @Inject
45 | MetricsSummary summary;
46 |
47 | @Deployment
48 | public static WebArchive deployment() {
49 | return ShrinkWrap.create(WebArchive.class)
50 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
51 | .addPackage(HelloService.class.getPackage())
52 | .addPackage(AllMetricsOfGivenTypeTest.class.getPackage());
53 | }
54 |
55 | @Test
56 | public void testGetMetricsOfGivenType() {
57 | hello.hello();
58 | hello.howdy();
59 | SortedMap timers = summary.getAppMetrics().getTimers();
60 | assertEquals(1, timers.size());
61 | assertTrue(timers.containsKey(new MetricID("howdy-time")));
62 | assertFalse(timers.containsKey(new MetricID(("hello-count"))));
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/stereotype/StereotypeCountedClassTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.stereotype;
19 |
20 | import static org.junit.Assert.assertEquals;
21 | import static org.junit.Assert.assertTrue;
22 |
23 | import jakarta.inject.Inject;
24 |
25 | import org.eclipse.microprofile.metrics.MetricID;
26 | import org.eclipse.microprofile.metrics.MetricRegistry;
27 | import org.jboss.arquillian.container.test.api.Deployment;
28 | import org.jboss.arquillian.junit.Arquillian;
29 | import org.jboss.shrinkwrap.api.ShrinkWrap;
30 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
31 | import org.jboss.shrinkwrap.api.spec.WebArchive;
32 | import org.junit.Test;
33 | import org.junit.runner.RunWith;
34 |
35 | import io.smallrye.metrics.test.stereotype.stereotypes.CountMe;
36 |
37 | @RunWith(Arquillian.class)
38 | public class StereotypeCountedClassTest {
39 |
40 | @Deployment
41 | public static WebArchive createTestArchive() {
42 | return ShrinkWrap.create(WebArchive.class)
43 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
44 | .addClasses(CountedClass.class, CountMe.class);
45 | }
46 |
47 | @Inject
48 | MetricRegistry metricRegistry;
49 |
50 | @Inject
51 | CountedClass bean;
52 |
53 | @Test
54 | public void test() {
55 | MetricID id_constructor = new MetricID(CountedClass.class.getName() + ".CountedClass");
56 | assertTrue(metricRegistry.getCounters().containsKey(id_constructor));
57 | MetricID id_method = new MetricID(CountedClass.class.getName() + ".foo");
58 | assertTrue(metricRegistry.getCounters().containsKey(id_method));
59 | bean.foo();
60 | assertEquals(1, metricRegistry.getCounters().get(id_method).getCount());
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/inject/NonReusableMetricInjectionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.inject;
19 |
20 | import jakarta.enterprise.inject.Instance;
21 | import jakarta.inject.Inject;
22 |
23 | import org.eclipse.microprofile.metrics.MetricID;
24 | import org.eclipse.microprofile.metrics.MetricRegistry;
25 | import org.eclipse.microprofile.metrics.Tag;
26 | import org.jboss.arquillian.container.test.api.Deployment;
27 | import org.jboss.arquillian.junit.Arquillian;
28 | import org.jboss.shrinkwrap.api.ShrinkWrap;
29 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
30 | import org.jboss.shrinkwrap.api.spec.WebArchive;
31 | import org.junit.Assert;
32 | import org.junit.Test;
33 | import org.junit.runner.RunWith;
34 |
35 | /**
36 | * Test that it is possible to inject a metric using an annotated method parameter.
37 | */
38 | @RunWith(Arquillian.class)
39 | public class NonReusableMetricInjectionTest {
40 |
41 | @Inject
42 | private Instance bean;
43 |
44 | @Inject
45 | private MetricRegistry metricRegistry;
46 |
47 | @Deployment
48 | public static WebArchive deployment() {
49 | return ShrinkWrap.create(WebArchive.class)
50 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
51 | .addClass(NonReusableMetricInjectionBean.class);
52 | }
53 |
54 | @Test
55 | public void test() {
56 | // force creating two instances of the bean
57 | bean.get();
58 | bean.get();
59 | Assert.assertEquals(4, metricRegistry.getCounters().get(new MetricID("mycounter", new Tag("k", "v1"))).getCount());
60 | Assert.assertEquals(6, metricRegistry.getCounters().get(new MetricID("mycounter", new Tag("k", "v2"))).getCount());
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_SimpleTimer_Method_Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.initialization;
19 |
20 | import static org.junit.Assert.assertEquals;
21 | import static org.junit.Assert.assertTrue;
22 |
23 | import jakarta.inject.Inject;
24 |
25 | import org.eclipse.microprofile.metrics.MetricID;
26 | import org.eclipse.microprofile.metrics.MetricRegistry;
27 | import org.eclipse.microprofile.metrics.annotation.SimplyTimed;
28 | import org.jboss.arquillian.container.test.api.Deployment;
29 | import org.jboss.arquillian.junit.Arquillian;
30 | import org.jboss.shrinkwrap.api.ShrinkWrap;
31 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
32 | import org.jboss.shrinkwrap.api.spec.WebArchive;
33 | import org.junit.Test;
34 | import org.junit.runner.RunWith;
35 |
36 | @RunWith(Arquillian.class)
37 | public class Initialization_SimpleTimer_Method_Test {
38 |
39 | @Deployment
40 | public static WebArchive deployment() {
41 | return ShrinkWrap.create(WebArchive.class)
42 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
43 | .addClasses(BeanWithSimpleTimer_Method.class);
44 | }
45 |
46 | @Inject
47 | MetricRegistry registry;
48 |
49 | @Inject
50 | BeanWithSimpleTimer_Method bean;
51 |
52 | @Test
53 | public void test() {
54 | assertTrue(registry.getSimpleTimers().containsKey(new MetricID("simplytimed_method")));
55 | bean.timedMethod();
56 | assertEquals(1, registry.getSimpleTimers().get(new MetricID("simplytimed_method")).getCount());
57 | }
58 |
59 | public static class BeanWithSimpleTimer_Method {
60 |
61 | @SimplyTimed(name = "simplytimed_method", absolute = true)
62 | public void timedMethod() {
63 |
64 | }
65 |
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/OriginAndMetadata.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics;
19 |
20 | import java.util.Optional;
21 |
22 | import org.eclipse.microprofile.metrics.Metadata;
23 | import org.eclipse.microprofile.metrics.MetricType;
24 |
25 | /**
26 | * Created by bob on 2/5/18.
27 | */
28 | public class OriginAndMetadata implements Metadata {
29 |
30 | private final Object origin;
31 | private final Metadata metadata;
32 |
33 | public OriginAndMetadata(Object origin, Metadata metadata) {
34 | this.metadata = metadata;
35 | this.origin = origin;
36 | }
37 |
38 | public Object getOrigin() {
39 | return this.origin;
40 | }
41 |
42 | public Metadata getMetadata() {
43 | return metadata;
44 | }
45 |
46 | @Override
47 | public String getName() {
48 | return metadata.getName();
49 | }
50 |
51 | @Override
52 | public String getDisplayName() {
53 | return metadata.getDisplayName();
54 | }
55 |
56 | @Override
57 | public Optional displayName() {
58 | return metadata.displayName();
59 | }
60 |
61 | @Override
62 | public String getDescription() {
63 | return metadata.getDescription();
64 | }
65 |
66 | @Override
67 | public Optional description() {
68 | return metadata.description();
69 | }
70 |
71 | @Override
72 | public String getType() {
73 | return metadata.getType();
74 | }
75 |
76 | @Override
77 | public MetricType getTypeRaw() {
78 | return metadata.getTypeRaw();
79 | }
80 |
81 | @Override
82 | public String getUnit() {
83 | return metadata.getUnit();
84 | }
85 |
86 | @Override
87 | public Optional unit() {
88 | return metadata.unit();
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/exporters/ExporterUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.exporters;
18 |
19 | import org.eclipse.microprofile.metrics.MetricUnits;
20 |
21 | /**
22 | * @author hrupp, Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
23 | */
24 | public class ExporterUtil {
25 |
26 | public static final long NANOS_PER_MICROSECOND = 1_000;
27 | public static final long NANOS_PER_MILLI = 1_000_000;
28 | public static final long NANOS_PER_SECOND = 1_000_000_000;
29 | public static final long NANOS_PER_MINUTE = 60 * 1_000_000_000L;
30 | public static final long NANOS_PER_HOUR = 3600 * 1_000_000_000L;
31 | public static final long NANOS_PER_DAY = 24 * 3600 * 1_000_000_000L;
32 |
33 | private ExporterUtil() {
34 | }
35 |
36 | public static Double convertNanosTo(Double value, String unit) {
37 |
38 | Double out;
39 |
40 | switch (unit) {
41 | case MetricUnits.NANOSECONDS:
42 | out = value;
43 | break;
44 | case MetricUnits.MICROSECONDS:
45 | out = value / NANOS_PER_MICROSECOND;
46 | break;
47 | case MetricUnits.MILLISECONDS:
48 | out = value / NANOS_PER_MILLI;
49 | break;
50 | case MetricUnits.SECONDS:
51 | out = value / NANOS_PER_SECOND;
52 | break;
53 | case MetricUnits.MINUTES:
54 | out = value / NANOS_PER_MINUTE;
55 | break;
56 | case MetricUnits.HOURS:
57 | out = value / NANOS_PER_HOUR;
58 | break;
59 | case MetricUnits.DAYS:
60 | out = value / NANOS_PER_DAY;
61 | break;
62 | default:
63 | out = value;
64 | }
65 | return out;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/reusability/ReuseMetricWithDifferingTagsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.reusability;
19 |
20 | import jakarta.inject.Inject;
21 |
22 | import org.eclipse.microprofile.metrics.MetricID;
23 | import org.eclipse.microprofile.metrics.MetricRegistry;
24 | import org.eclipse.microprofile.metrics.Tag;
25 | import org.jboss.arquillian.container.test.api.Deployment;
26 | import org.jboss.arquillian.junit.Arquillian;
27 | import org.jboss.shrinkwrap.api.ShrinkWrap;
28 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
29 | import org.jboss.shrinkwrap.api.spec.WebArchive;
30 | import org.junit.Assert;
31 | import org.junit.Test;
32 | import org.junit.runner.RunWith;
33 |
34 | /**
35 | * Test that two metrics of the same name and differing tags can be created by annotations.
36 | */
37 | @RunWith(Arquillian.class)
38 | public class ReuseMetricWithDifferingTagsTest {
39 |
40 | @Inject
41 | MetricRegistry metricRegistry;
42 |
43 | @Inject
44 | private ReuseMetricWithDifferingTagsBean bean;
45 |
46 | @Deployment
47 | public static WebArchive deployment() {
48 | return ShrinkWrap.create(WebArchive.class)
49 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
50 | .addClass(ReuseMetricWithDifferingTagsBean.class);
51 | }
52 |
53 | @Test
54 | public void test() {
55 | bean.colorBlue1();
56 | bean.colorBlue1();
57 | bean.colorBlue2();
58 | bean.colorRed1();
59 | bean.colorRed2();
60 | Assert.assertEquals(3,
61 | metricRegistry.getCounters().get(new MetricID("colorCounter", new Tag("color", "blue"))).getCount());
62 | Assert.assertEquals(2,
63 | metricRegistry.getCounters().get(new MetricID("colorCounter", new Tag("color", "red"))).getCount());
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/java/io/smallrye/metrics/tck/rest/ArchiveProcessor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.tck.rest;
17 |
18 | import java.io.File;
19 |
20 | import org.jboss.arquillian.container.test.spi.TestDeployment;
21 | import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor;
22 | import org.jboss.shrinkwrap.api.Archive;
23 | import org.jboss.shrinkwrap.api.spec.WebArchive;
24 | import org.jboss.shrinkwrap.resolver.api.maven.Maven;
25 |
26 | /**
27 | * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
28 | *
29 | * Date: 6/19/18
30 | */
31 | public class ArchiveProcessor implements ProtocolArchiveProcessor {
32 | @Override
33 | public void process(TestDeployment testDeployment, Archive> protocolArchive) {
34 | WebArchive war = (WebArchive) protocolArchive;
35 | war.addAsWebInfResource("WEB-INF/jboss-web.xml", "jboss-web.xml");
36 | String[] deps = {
37 | "io.smallrye:smallrye-config",
38 | "io.smallrye:smallrye-metrics",
39 | "io.smallrye:smallrye-metrics-testsuite-common",
40 | "org.eclipse.microprofile.metrics:microprofile-metrics-api",
41 | // "org.jboss.weld.servlet:weld-servlet-core"
42 | };
43 |
44 | File[] dependencies = Maven.resolver().loadPomFromFile(new File("pom.xml")).resolve(deps).withTransitivity().asFile();
45 |
46 | war.addAsLibraries(dependencies);
47 |
48 | // war.addClass(SmallRyeBeanArchiveHandler.class);
49 | war.addClass(MetricsHttpServlet.class);
50 | // war.addClass(MetricsInitializer.class);
51 | war.addAsResource("io/smallrye/metrics/base-metrics.properties", "/io/smallrye/metrics/base-metrics.properties");
52 | // war.addAsServiceProvider(BeanArchiveHandler.class, SmallRyeBeanArchiveHandler.class);
53 | // war.addAsServiceProvider(Extension.class, ConfigExtension.class);
54 | // war.addAsServiceProvider(ConfigProviderResolver.class, SmallRyeConfigProviderResolver.class);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/registry/MetricRegistryInjectionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.test.registry;
17 |
18 | import static org.junit.Assert.assertEquals;
19 | import static org.junit.Assert.assertNotNull;
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import jakarta.inject.Inject;
23 |
24 | import org.eclipse.microprofile.metrics.Counting;
25 | import org.eclipse.microprofile.metrics.Metric;
26 | import org.eclipse.microprofile.metrics.MetricID;
27 | import org.jboss.arquillian.container.test.api.Deployment;
28 | import org.jboss.arquillian.junit.Arquillian;
29 | import org.jboss.shrinkwrap.api.ShrinkWrap;
30 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
31 | import org.jboss.shrinkwrap.api.spec.WebArchive;
32 | import org.junit.Test;
33 | import org.junit.runner.RunWith;
34 |
35 | import io.smallrye.metrics.test.HelloService;
36 | import io.smallrye.metrics.test.MetricsSummary;
37 |
38 | /**
39 | *
40 | * @author Martin Kouba
41 | */
42 | @RunWith(Arquillian.class)
43 | public class MetricRegistryInjectionTest {
44 |
45 | @Inject
46 | HelloService hello;
47 |
48 | @Inject
49 | MetricsSummary summary;
50 |
51 | @Deployment
52 | public static WebArchive createTestArchive() {
53 | return ShrinkWrap.create(WebArchive.class).addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
54 | .addPackage(MetricsSummary.class.getPackage())
55 | .addPackage(MetricRegistryInjectionTest.class.getPackage());
56 | }
57 |
58 | @Test
59 | public void testInjection() {
60 | hello.hello();
61 | assertNotNull(summary.getBaseMetrics().getMetrics().containsKey("memory.usedHeap"));
62 | assertNotNull(summary.getVendorMetrics().getMetrics().containsKey("loadedModules"));
63 | Metric helloCountMetric = summary.getAppMetrics().getMetrics().get(new MetricID("hello-count"));
64 | assertNotNull(helloCountMetric);
65 | assertTrue(helloCountMetric instanceof Counting);
66 | Counting helloCount = (Counting) helloCountMetric;
67 | assertEquals(1, helloCount.getCount());
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Injection_Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.initialization;
19 |
20 | import static org.junit.Assert.assertEquals;
21 | import static org.junit.Assert.assertTrue;
22 |
23 | import jakarta.inject.Inject;
24 |
25 | import org.eclipse.microprofile.metrics.Histogram;
26 | import org.eclipse.microprofile.metrics.MetricID;
27 | import org.eclipse.microprofile.metrics.MetricRegistry;
28 | import org.eclipse.microprofile.metrics.annotation.Metric;
29 | import org.jboss.arquillian.container.test.api.Deployment;
30 | import org.jboss.arquillian.junit.Arquillian;
31 | import org.jboss.shrinkwrap.api.ShrinkWrap;
32 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
33 | import org.jboss.shrinkwrap.api.spec.WebArchive;
34 | import org.junit.Test;
35 | import org.junit.runner.RunWith;
36 |
37 | @RunWith(Arquillian.class)
38 | public class Initialization_Injection_Test {
39 |
40 | @Deployment
41 | public static WebArchive deployment() {
42 | return ShrinkWrap.create(WebArchive.class)
43 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
44 | .addClasses(BeanWithMetricInjection.class);
45 | }
46 |
47 | @Inject
48 | MetricRegistry registry;
49 |
50 | @Inject
51 | BeanWithMetricInjection bean;
52 |
53 | @Test
54 | public void test() {
55 | MetricID metricID = new MetricID(
56 | "io.smallrye.metrics.test.initialization.Initialization_Injection_Test.BeanWithMetricInjection.histogram");
57 | // check that the injected histogram is registered eagerly
58 | assertTrue(registry.getHistograms().containsKey(metricID));
59 | bean.addDataToHistogram();
60 | assertEquals(10, registry.getHistograms().get(metricID).getSnapshot().getMax());
61 | }
62 |
63 | public static class BeanWithMetricInjection {
64 |
65 | @Inject
66 | @Metric
67 | Histogram histogram;
68 |
69 | public void addDataToHistogram() {
70 | histogram.update(10);
71 | }
72 |
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/app/Clock.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | * *******************************************************************************
18 | * Copyright 2010-2013 Coda Hale and Yammer, Inc.
19 | *
20 | * Licensed under the Apache License, Version 2.0 (the "License");
21 | * you may not use this file except in compliance with the License.
22 | * You may obtain a copy of the License at
23 | *
24 | * http://www.apache.org/licenses/LICENSE-2.0
25 | *
26 | * Unless required by applicable law or agreed to in writing, software
27 | * distributed under the License is distributed on an "AS IS" BASIS,
28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 | * See the License for the specific language governing permissions and
30 | * limitations under the License.
31 | */
32 | package io.smallrye.metrics.app;
33 |
34 | /**
35 | * An abstraction for how time passes. It is passed to {@link org.eclipse.microprofile.metrics.Timer} to track timing.
36 | */
37 | public abstract class Clock {
38 | /**
39 | * Returns the current time tick.
40 | *
41 | * @return time tick in nanoseconds
42 | */
43 | public abstract long getTick();
44 |
45 | /**
46 | * Returns the current time in milliseconds.
47 | *
48 | * @return time in milliseconds
49 | */
50 | public long getTime() {
51 | return System.currentTimeMillis();
52 | }
53 |
54 | /**
55 | * The default clock to use.
56 | *
57 | * @return the default {@link Clock} instance
58 | * @see Clock.UserTimeClock
59 | */
60 | public static Clock defaultClock() {
61 | return UserTimeClockHolder.DEFAULT;
62 | }
63 |
64 | /**
65 | * A clock implementation which returns the current time in epoch nanoseconds.
66 | */
67 | public static class UserTimeClock extends Clock {
68 | @Override
69 | public long getTick() {
70 | return System.nanoTime();
71 | }
72 | }
73 |
74 | private static class UserTimeClockHolder {
75 | private static final Clock DEFAULT = new UserTimeClock();
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/dependent/GaugeInDependentScopedBeanTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.smallrye.metrics.test.dependent;
18 |
19 | import jakarta.enterprise.inject.Instance;
20 | import jakarta.inject.Inject;
21 |
22 | import org.eclipse.microprofile.metrics.MetricFilter;
23 | import org.eclipse.microprofile.metrics.MetricRegistry;
24 | import org.jboss.arquillian.container.test.api.Deployment;
25 | import org.jboss.arquillian.junit.Arquillian;
26 | import org.jboss.shrinkwrap.api.ShrinkWrap;
27 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
28 | import org.jboss.shrinkwrap.api.spec.WebArchive;
29 | import org.junit.After;
30 | import org.junit.Assert;
31 | import org.junit.Test;
32 | import org.junit.runner.RunWith;
33 |
34 | import io.smallrye.metrics.MetricRegistries;
35 |
36 | /**
37 | * Gauges can only be used with AnnotationScoped beans. If we place a gauge on a bean that creates multiple
38 | * instances during the application lifetime, this should be treated as an error, because a gauge
39 | * must always be bound to just one object, therefore creating multiple instances of the bean would
40 | * create ambiguity.
41 | */
42 | @RunWith(Arquillian.class)
43 | public class GaugeInDependentScopedBeanTest {
44 |
45 | @Deployment
46 | public static WebArchive deployment() {
47 | return ShrinkWrap.create(WebArchive.class)
48 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
49 | .addClass(DependentScopedBeanWithGauge.class);
50 | }
51 |
52 | @After
53 | public void cleanupApplicationMetrics() {
54 | MetricRegistries.get(MetricRegistry.Type.APPLICATION).removeMatching(MetricFilter.ALL);
55 | }
56 |
57 | @Inject
58 | private Instance beanInstance;
59 |
60 | @Test
61 | public void gauge() {
62 | try {
63 | DependentScopedBeanWithGauge instance1 = beanInstance.get();
64 | DependentScopedBeanWithGauge instance2 = beanInstance.get();
65 | Assert.fail("Shouldn't be able to create multiple instances of a bean that contains a gauge");
66 | } catch (Exception e) {
67 |
68 | }
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/setup/AnnotatedTypeDecorator.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.setup;
17 |
18 | import java.lang.annotation.Annotation;
19 | import java.util.Collections;
20 | import java.util.HashSet;
21 | import java.util.Set;
22 |
23 | import jakarta.enterprise.inject.spi.AnnotatedConstructor;
24 | import jakarta.enterprise.inject.spi.AnnotatedField;
25 | import jakarta.enterprise.inject.spi.AnnotatedMethod;
26 | import jakarta.enterprise.inject.spi.AnnotatedType;
27 |
28 | /* package-private */ final class AnnotatedTypeDecorator extends AnnotatedDecorator implements AnnotatedType {
29 |
30 | private final AnnotatedType decoratedType;
31 |
32 | private final Set> decoratedMethods;
33 |
34 | AnnotatedTypeDecorator(AnnotatedType decoratedType, Annotation decoratingAnnotation) {
35 | this(decoratedType, decoratingAnnotation, Collections.> emptySet());
36 | }
37 |
38 | AnnotatedTypeDecorator(AnnotatedType decoratedType, Annotation decoratingAnnotation,
39 | Set> decoratedMethods) {
40 | super(decoratedType, Collections.singleton(decoratingAnnotation));
41 | this.decoratedType = decoratedType;
42 | this.decoratedMethods = decoratedMethods;
43 | }
44 |
45 | @Override
46 | public Class getJavaClass() {
47 | return decoratedType.getJavaClass();
48 | }
49 |
50 | @Override
51 | public Set> getConstructors() {
52 | return decoratedType.getConstructors();
53 | }
54 |
55 | @Override
56 | public Set> getMethods() {
57 | Set> methods = new HashSet<>(decoratedType.getMethods());
58 | for (AnnotatedMethod super X> method : decoratedMethods) {
59 | methods.remove(method);
60 | methods.add(method);
61 | }
62 |
63 | return Collections.unmodifiableSet(methods);
64 | }
65 |
66 | @Override
67 | public Set> getFields() {
68 | return decoratedType.getFields();
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Gauge_Method_Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.initialization;
19 |
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import jakarta.enterprise.context.ApplicationScoped;
23 | import jakarta.inject.Inject;
24 |
25 | import org.eclipse.microprofile.metrics.MetricID;
26 | import org.eclipse.microprofile.metrics.MetricRegistry;
27 | import org.eclipse.microprofile.metrics.MetricUnits;
28 | import org.eclipse.microprofile.metrics.annotation.Gauge;
29 | import org.jboss.arquillian.container.test.api.Deployment;
30 | import org.jboss.arquillian.junit.Arquillian;
31 | import org.jboss.shrinkwrap.api.ShrinkWrap;
32 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
33 | import org.jboss.shrinkwrap.api.spec.WebArchive;
34 | import org.junit.Assert;
35 | import org.junit.Test;
36 | import org.junit.runner.RunWith;
37 |
38 | @RunWith(Arquillian.class)
39 | public class Initialization_Gauge_Method_Test {
40 |
41 | @Deployment
42 | public static WebArchive deployment() {
43 | return ShrinkWrap.create(WebArchive.class)
44 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
45 | .addClasses(BeanWithGauge_ApplicationScoped.class);
46 | }
47 |
48 | @Inject
49 | MetricRegistry registry;
50 |
51 | @Inject
52 | BeanWithGauge_ApplicationScoped applicationScopedBean;
53 |
54 | /**
55 | * With a gauge in an application-scoped bean, the metric will be registered once the bean is instantiated.
56 | */
57 | @Test
58 | public void testApplicationScoped() {
59 | applicationScopedBean.gauge(); // access the application-scoped bean so that an instance gets created
60 | assertTrue(registry.getGauges().containsKey(new MetricID("gaugeApp")));
61 | Assert.assertEquals(2L, registry.getGauges().get(new MetricID("gaugeApp")).getValue());
62 | Assert.assertEquals(3L, registry.getGauges().get(new MetricID("gaugeApp")).getValue());
63 | }
64 |
65 | @ApplicationScoped
66 | public static class BeanWithGauge_ApplicationScoped {
67 |
68 | Long i = 0L;
69 |
70 | @Gauge(name = "gaugeApp", absolute = true, unit = MetricUnits.NONE)
71 | public Long gauge() {
72 | return ++i;
73 | }
74 |
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/setup/AnnotatedDecorator.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.setup;
17 |
18 | import java.lang.annotation.Annotation;
19 | import java.lang.reflect.Type;
20 | import java.util.Collections;
21 | import java.util.HashSet;
22 | import java.util.Set;
23 |
24 | import jakarta.enterprise.inject.spi.Annotated;
25 |
26 | /* package-private */ class AnnotatedDecorator implements Annotated {
27 |
28 | private final Annotated decorated;
29 |
30 | private final Set annotations;
31 |
32 | AnnotatedDecorator(Annotated decorated, Set annotations) {
33 | this.decorated = decorated;
34 | this.annotations = annotations;
35 | }
36 |
37 | @Override
38 | public Type getBaseType() {
39 | return decorated.getBaseType();
40 | }
41 |
42 | @Override
43 | public Set getTypeClosure() {
44 | return decorated.getTypeClosure();
45 | }
46 |
47 | @Override
48 | public T getAnnotation(Class annotationType) {
49 | T annotation = getDecoratingAnnotation(annotationType);
50 | if (annotation != null) {
51 | return annotation;
52 | } else {
53 | return decorated.getAnnotation(annotationType);
54 | }
55 | }
56 |
57 | @Override
58 | public Set getAnnotations(Class annotationType) {
59 | return decorated.getAnnotations(annotationType);
60 | }
61 |
62 | @Override
63 | public Set getAnnotations() {
64 | Set annotations = new HashSet<>(this.annotations);
65 | annotations.addAll(decorated.getAnnotations());
66 | return Collections.unmodifiableSet(annotations);
67 | }
68 |
69 | @Override
70 | public boolean isAnnotationPresent(Class extends Annotation> annotationType) {
71 | return getDecoratingAnnotation(annotationType) != null || decorated.isAnnotationPresent(annotationType);
72 | }
73 |
74 | @SuppressWarnings("unchecked")
75 | private T getDecoratingAnnotation(Class annotationType) {
76 | for (Annotation annotation : annotations) {
77 | if (annotationType.isAssignableFrom(annotation.annotationType())) {
78 | return (T) annotation;
79 | }
80 | }
81 |
82 | return null;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/testsuite/rest-tck/src/test/java/io/smallrye/metrics/tck/rest/SmallRyeBeanArchiveHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Red Hat, Inc, and individual contributors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.tck.rest;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.net.URL;
21 | import java.util.zip.ZipEntry;
22 | import java.util.zip.ZipInputStream;
23 |
24 | import jakarta.annotation.Priority;
25 |
26 | import org.jboss.weld.environment.deployment.discovery.BeanArchiveBuilder;
27 | import org.jboss.weld.environment.deployment.discovery.BeanArchiveHandler;
28 | import org.jboss.weld.environment.util.Files;
29 |
30 | /**
31 | * Copied from SmallRye Rest Client
32 | *
33 | * Special handler for WildFly VFS urls.
34 | *
35 | * @author Martin Kouba
36 | */
37 | @Priority(1)
38 | public class SmallRyeBeanArchiveHandler implements BeanArchiveHandler {
39 |
40 | @Override
41 | public BeanArchiveBuilder handle(String beanArchiveReference) {
42 |
43 | // An external form of a wildfly beans.xml URL will be something like:
44 | // vfs:/content/_DEFAULT___DEFAULT__1f4a3572-fc97-41f5-8fed-0e7e7f7895df.war/WEB-INF/lib/4e0a1b50-4a74-429d-b519-9eedcac11046.jar/META-INF/beans.xml
45 | beanArchiveReference = beanArchiveReference.substring(0, beanArchiveReference.lastIndexOf("/META-INF/beans.xml"));
46 |
47 | if (beanArchiveReference.endsWith(".war")) {
48 | // We only use this handler for libraries - WEB-INF classes are handled by ServletContextBeanArchiveHandler
49 | return null;
50 | }
51 |
52 | try {
53 | URL url = new URL(beanArchiveReference);
54 | try (ZipInputStream in = openStream(url)) {
55 | BeanArchiveBuilder builder = new BeanArchiveBuilder();
56 | handleLibrary(url, in, builder);
57 | return builder;
58 | }
59 | } catch (IOException e) {
60 | throw new IllegalStateException(e);
61 | }
62 | }
63 |
64 | ZipInputStream openStream(URL url) throws IOException {
65 | InputStream in = url.openStream();
66 | return (in instanceof ZipInputStream) ? (ZipInputStream) in : new ZipInputStream(in);
67 | }
68 |
69 | private void handleLibrary(URL url, ZipInputStream zip, BeanArchiveBuilder builder) throws IOException {
70 | ZipEntry entry = null;
71 | while ((entry = zip.getNextEntry()) != null) {
72 | if (Files.isClass(entry.getName())) {
73 | builder.addClass(Files.filenameToClassname(entry.getName()));
74 | }
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/testsuite/optional-tck/src/test/java/io/smallrye/metrics/tck/optional/JaxRsMetricsActivatingProcessor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.tck.optional;
19 |
20 | import java.io.File;
21 |
22 | import jakarta.ws.rs.ext.Providers;
23 |
24 | import org.jboss.arquillian.container.test.spi.TestDeployment;
25 | import org.jboss.arquillian.container.test.spi.client.deployment.ProtocolArchiveProcessor;
26 | import org.jboss.shrinkwrap.api.Archive;
27 | import org.jboss.shrinkwrap.api.spec.WebArchive;
28 | import org.jboss.shrinkwrap.resolver.api.maven.Maven;
29 |
30 | import io.smallrye.metrics.jaxrs.JaxRsMetricsFilter;
31 | import io.smallrye.metrics.jaxrs.JaxRsMetricsServletFilter;
32 |
33 | public class JaxRsMetricsActivatingProcessor implements ProtocolArchiveProcessor {
34 |
35 | @Override
36 | public void process(TestDeployment testDeployment, Archive> archive) {
37 | WebArchive war = (WebArchive) archive;
38 |
39 | String[] deps = {
40 | // "io.smallrye:smallrye-config",
41 | "io.smallrye:smallrye-metrics",
42 | "io.smallrye:smallrye-metrics-testsuite-common",
43 | "org.eclipse.microprofile.metrics:microprofile-metrics-api",
44 | // "org.eclipse.microprofile.config:microprofile-config-api"
45 | };
46 | File[] dependencies = Maven.resolver().loadPomFromFile(new File("pom.xml")).resolve(deps).withTransitivity().asFile();
47 | war.addAsLibraries(dependencies);
48 |
49 | war.addClass(MetricsHttpServlet.class);
50 | war.addClass(JaxRsMetricsFilter.class);
51 | war.addClass(JaxRsMetricsServletFilter.class);
52 |
53 | // change application context root to '/' because the TCK assumes that the metrics
54 | // will be available at '/metrics', and in our case the metrics servlet is located
55 | // within the application itself, we don't use WildFly's built-in support for metrics
56 | war.addAsWebInfResource("WEB-INF/jboss-web.xml", "jboss-web.xml");
57 |
58 | // activate the servlet filter
59 | war.setWebXML("WEB-INF/web.xml");
60 |
61 | // activate the JAX-RS request filter
62 | war.addAsServiceProvider(Providers.class.getName(), JaxRsMetricsFilter.class.getName());
63 |
64 | // exclude built-in Metrics and Config from WildFly
65 | war.addAsManifestResource("META-INF/jboss-deployment-structure.xml", "jboss-deployment-structure.xml");
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/UnspecifiedMetadata.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics;
19 |
20 | import java.util.Optional;
21 |
22 | import org.eclipse.microprofile.metrics.Metadata;
23 | import org.eclipse.microprofile.metrics.MetricType;
24 |
25 | /**
26 | * This is a special class to internally mark that no metadata was specified for a metric registration. We can't simply use null
27 | * instead of this because we still need to keep track of the metric name and type somewhere.
28 | * Instances of this class MUST NOT be actually stored in the MetricsRegistry, it needs to be converted to real metadata
29 | * first!!!
30 | */
31 | public class UnspecifiedMetadata implements Metadata {
32 |
33 | private final String name;
34 | private final MetricType type;
35 |
36 | public UnspecifiedMetadata(String name, MetricType type) {
37 | this.name = name;
38 | this.type = type;
39 | }
40 |
41 | @Override
42 | public String getName() {
43 | return this.name;
44 | }
45 |
46 | @Override
47 | public String getDisplayName() {
48 | throw new IllegalStateException("Unspecified metadata only contains name and type.");
49 | }
50 |
51 | @Override
52 | public Optional displayName() {
53 | throw new IllegalStateException("Unspecified metadata only contains name and type.");
54 | }
55 |
56 | @Override
57 | public String getDescription() {
58 | throw new IllegalStateException("Unspecified metadata only contains name and type.");
59 | }
60 |
61 | @Override
62 | public Optional description() {
63 | throw new IllegalStateException("Unspecified metadata only contains name and type.");
64 | }
65 |
66 | @Override
67 | public String getType() {
68 | return type.toString();
69 | }
70 |
71 | @Override
72 | public MetricType getTypeRaw() {
73 | return type;
74 | }
75 |
76 | @Override
77 | public String getUnit() {
78 | throw new IllegalStateException("Unspecified metadata only contains name and type.");
79 | }
80 |
81 | @Override
82 | public Optional unit() {
83 | throw new IllegalStateException("Unspecified metadata only contains name and type.");
84 | }
85 |
86 | public Metadata convertToRealMetadata() {
87 | return Metadata.builder()
88 | .withName(name)
89 | .withType(type)
90 | .build();
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/MetricRegistries.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics;
18 |
19 | import java.util.Map;
20 | import java.util.concurrent.ConcurrentHashMap;
21 |
22 | import jakarta.annotation.PreDestroy;
23 | import jakarta.enterprise.context.ApplicationScoped;
24 | import jakarta.enterprise.inject.Default;
25 | import jakarta.enterprise.inject.Produces;
26 |
27 | import org.eclipse.microprofile.metrics.MetricRegistry;
28 | import org.eclipse.microprofile.metrics.annotation.RegistryType;
29 |
30 | /**
31 | * @author hrupp
32 | */
33 | @ApplicationScoped
34 | public class MetricRegistries {
35 |
36 | @Produces
37 | @Default
38 | @RegistryType(type = MetricRegistry.Type.APPLICATION)
39 | @ApplicationScoped
40 | public MetricRegistry getApplicationRegistry() {
41 | return get(MetricRegistry.Type.APPLICATION);
42 | }
43 |
44 | @Produces
45 | @RegistryType(type = MetricRegistry.Type.BASE)
46 | @ApplicationScoped
47 | public MetricRegistry getBaseRegistry() {
48 | return get(MetricRegistry.Type.BASE);
49 | }
50 |
51 | @Produces
52 | @RegistryType(type = MetricRegistry.Type.VENDOR)
53 | @ApplicationScoped
54 | public MetricRegistry getVendorRegistry() {
55 | return get(MetricRegistry.Type.VENDOR);
56 | }
57 |
58 | public static MetricRegistry get(MetricRegistry.Type type) {
59 | return registries.computeIfAbsent(type, t -> new MetricsRegistryImpl(type));
60 | }
61 |
62 | @PreDestroy
63 | public void cleanUp() {
64 | registries.remove(MetricRegistry.Type.APPLICATION);
65 | }
66 |
67 | /**
68 | * Drops a particular registry. If a reference to the same registry type
69 | * is requested later, a new empty registry will be created for that purpose.
70 | *
71 | * @param type Type of registry that should be dropped.
72 | */
73 | public static void drop(MetricRegistry.Type type) {
74 | registries.remove(type);
75 | }
76 |
77 | /**
78 | * Drops all registries. If a reference to a registry
79 | * is requested later, a new empty registry will be created for that purpose.
80 | */
81 | public static void dropAll() {
82 | registries.remove(MetricRegistry.Type.APPLICATION);
83 | registries.remove(MetricRegistry.Type.BASE);
84 | registries.remove(MetricRegistry.Type.VENDOR);
85 | }
86 |
87 | private static final Map registries = new ConcurrentHashMap<>();
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/testsuite/extra/src/test/java/io/smallrye/metrics/test/initialization/Initialization_Counter_ClassLevel_Test.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.test.initialization;
19 |
20 | import static org.junit.Assert.assertFalse;
21 | import static org.junit.Assert.assertTrue;
22 |
23 | import jakarta.inject.Inject;
24 |
25 | import org.eclipse.microprofile.metrics.MetricID;
26 | import org.eclipse.microprofile.metrics.MetricRegistry;
27 | import org.eclipse.microprofile.metrics.Tag;
28 | import org.eclipse.microprofile.metrics.annotation.Counted;
29 | import org.jboss.arquillian.container.test.api.Deployment;
30 | import org.jboss.arquillian.junit.Arquillian;
31 | import org.jboss.shrinkwrap.api.ShrinkWrap;
32 | import org.jboss.shrinkwrap.api.asset.EmptyAsset;
33 | import org.jboss.shrinkwrap.api.spec.WebArchive;
34 | import org.junit.Test;
35 | import org.junit.runner.RunWith;
36 |
37 | @RunWith(Arquillian.class)
38 | public class Initialization_Counter_ClassLevel_Test {
39 |
40 | @Deployment
41 | public static WebArchive deployment() {
42 | return ShrinkWrap.create(WebArchive.class)
43 | .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
44 | .addClasses(BeanWithCounter_ClassLevel.class);
45 | }
46 |
47 | @Inject
48 | MetricRegistry registry;
49 |
50 | @Test
51 | public void test() {
52 | // metric should be created for the constructor
53 | assertTrue(
54 | registry.getCounters().containsKey(new MetricID("customName.BeanWithCounter_ClassLevel", new Tag("t1", "v1"))));
55 |
56 | // metrics should be created for public methods
57 | assertTrue(registry.getCounters().containsKey(new MetricID("customName.publicMethod", new Tag("t1", "v1"))));
58 | assertTrue(registry.getCounters().containsKey(new MetricID("customName.publicMethod2", new Tag("t1", "v1"))));
59 |
60 | // but not for private methods
61 | assertFalse(registry.getCounters().keySet().stream()
62 | .anyMatch(metricID -> metricID.getName().toLowerCase().contains("private")));
63 | }
64 |
65 | @Counted(name = "customName", tags = "t1=v1", absolute = true)
66 | private static class BeanWithCounter_ClassLevel {
67 |
68 | public BeanWithCounter_ClassLevel() {
69 |
70 | }
71 |
72 | public void publicMethod() {
73 |
74 | }
75 |
76 | public void publicMethod2() {
77 |
78 | }
79 |
80 | private void privateMethod() {
81 |
82 | }
83 |
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/registration/MetricTypeMismatchTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.registration;
18 |
19 | import static org.hamcrest.CoreMatchers.containsString;
20 | import static org.hamcrest.CoreMatchers.instanceOf;
21 | import static org.junit.Assert.assertEquals;
22 | import static org.junit.Assert.assertThat;
23 | import static org.junit.Assert.fail;
24 |
25 | import org.eclipse.microprofile.metrics.Metadata;
26 | import org.eclipse.microprofile.metrics.MetricFilter;
27 | import org.eclipse.microprofile.metrics.MetricRegistry;
28 | import org.eclipse.microprofile.metrics.MetricType;
29 | import org.junit.After;
30 | import org.junit.Test;
31 |
32 | import io.smallrye.metrics.MetricRegistries;
33 |
34 | public class MetricTypeMismatchTest {
35 |
36 | private MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
37 |
38 | @After
39 | public void cleanupApplicationMetrics() {
40 | registry.removeMatching(MetricFilter.ALL);
41 | }
42 |
43 | @Test
44 | public void metricsWithDifferentType() {
45 | Metadata metadata1 = Metadata.builder().withName("metric1")
46 | .withDescription("description1").build();
47 | Metadata metadata2 = Metadata.builder().withName("metric1")
48 | .withDescription("description2").build();
49 |
50 | registry.histogram(metadata1);
51 | try {
52 | registry.meter(metadata2);
53 | fail("Must not be able to register if a metric with different type is registered under the same name");
54 | } catch (Exception e) {
55 | assertThat(e, instanceOf(IllegalStateException.class));
56 | assertEquals(1, registry.getMetrics().size());
57 | }
58 | }
59 |
60 | @Test
61 | public void wrongTypeInMetadata() {
62 | Metadata metadata1 = Metadata.builder()
63 | .withName("metric1")
64 | .withType(MetricType.COUNTER)
65 | .build();
66 | try {
67 | registry.meter(metadata1);
68 | fail("Must not be able to register a metric if the type in its metadata is different than the what we specified by using a particular registration method.");
69 | } catch (Exception e) {
70 | assertThat(e, instanceOf(IllegalArgumentException.class));
71 | assertThat(e.getMessage(),
72 | containsString("Attempting to register a meter, but the passed metadata contains type=counter"));
73 | assertEquals(0, registry.getMetrics().size());
74 | }
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/implementation/src/test/resources/base-metrics.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | # and other contributors as indicated by the @author tags.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 | #
17 |
18 | classloader.currentLoadedClass.count.displayName: Current Loaded Class Count
19 | classloader.currentLoadedClass.count.type: counter
20 | classloader.currentLoadedClass.count.unit: none
21 | classloader.currentLoadedClass.count.description: Displays the number of classes that are currently loaded in the Java virtual machine.
22 | classloader.currentLoadedClass.count.mbean: java.lang:type=ClassLoading/LoadedClassCount
23 | classloader.totalLoadedClass.count.displayName: Total Loaded Class Count
24 | classloader.totalLoadedClass.count.type: counter
25 | classloader.totalLoadedClass.count.unit: none
26 | classloader.totalLoadedClass.count.description: Displays the total number of classes that have been loaded since the Java virtual machine has started execution.
27 | classloader.totalLoadedClass.count.mbean: java.lang:type=ClassLoading/TotalLoadedClassCount
28 | classloader.totalUnloadedClass.count.displayName: Total Unloaded Class Count
29 | classloader.totalUnloadedClass.count.type: counter
30 | classloader.totalUnloadedClass.count.unit: none
31 | classloader.totalUnloadedClass.count.description: Displays the total number of classes unloaded since the Java virtual machine has started execution.
32 | classloader.totalUnloadedClass.count.mbean: java.lang:type=ClassLoading/UnloadedClassCount
33 | gc.count.displayName: Garbage Collection Count
34 | gc.count.type: counter
35 | gc.count.unit: none
36 | gc.count.multi: true
37 | gc.count.description: Displays the total number of collections that have occurred. This attribute lists -1 if the collection count is undefined for this collector.
38 | gc.count.mbean: java.lang:type=GarbageCollector,name=%s/CollectionCount
39 | gc.count.tags: name=%s1
40 | gc.time.displayName: Garbage Collection Time
41 | gc.time.type: gauge
42 | gc.time.unit: milliseconds
43 | gc.time.multi: true
44 | gc.time.description: Displays the approximate accumulated collection elapsed time in milliseconds. This attribute displays -1 if the collection elapsed time is undefined for this collector. The Java virtual machine implementation may use a high resolution timer to measure the elapsed time. This attribute may display the same value even if the collection count has been incremented if the collection elapsed time is very short.
45 | gc.time.mbean: java.lang:type=GarbageCollector,name=%s/CollectionTime
46 | gc.time.tags: name=%s1
47 | test_key.mbean: java.nio:name=%s2,type=%s1/ObjectName
48 | test_key.displayName: Display Name %s1-%s2
49 | test_key.type: counter
50 | test_key.unit: none
51 | test_key.multi: true
52 | test_key.description: Description %s1-%s2
53 | test_key.tags: type=%s1;name=%s2
54 |
--------------------------------------------------------------------------------
/testsuite/extra/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
20 | 4.0.0
21 |
22 |
23 | io.smallrye
24 | smallrye-metrics-testsuite-parent
25 | 4.0.1-SNAPSHOT
26 |
27 |
28 | smallrye-metrics-testsuite-extra
29 |
30 | SmallRye: MicroProfile Metrics Test Suite Additional Tests
31 |
32 |
33 |
34 | io.smallrye
35 | smallrye-metrics
36 | ${project.version}
37 |
38 |
39 | io.smallrye
40 | smallrye-config
41 |
42 |
43 | io.smallrye.config
44 | smallrye-config
45 |
46 |
47 | org.eclipse.microprofile.metrics
48 | microprofile-metrics-api
49 |
50 |
51 |
52 | io.smallrye
53 | smallrye-metrics-testsuite-common
54 | ${project.version}
55 |
56 |
57 | jakarta.enterprise
58 | jakarta.enterprise.cdi-api
59 | provided
60 |
61 |
62 | org.jboss.weld
63 | weld-core-impl
64 |
65 |
66 | org.jboss.arquillian.container
67 | arquillian-weld-embedded
68 |
69 |
70 | junit
71 | junit
72 | 4.13.2
73 |
74 |
75 | org.jboss.arquillian.junit
76 | arquillian-junit-container
77 |
78 |
79 |
80 |
81 |
82 | coverage
83 |
84 | @{jacocoArgLine}
85 |
86 |
87 |
88 |
89 |
90 | org.jacoco
91 | jacoco-maven-plugin
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/app/HistogramImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | * *******************************************************************************
18 | * Copyright 2010-2013 Coda Hale and Yammer, Inc.
19 | *
20 | * Licensed under the Apache License, Version 2.0 (the "License");
21 | * you may not use this file except in compliance with the License.
22 | * You may obtain a copy of the License at
23 | *
24 | * http://www.apache.org/licenses/LICENSE-2.0
25 | *
26 | * Unless required by applicable law or agreed to in writing, software
27 | * distributed under the License is distributed on an "AS IS" BASIS,
28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 | * See the License for the specific language governing permissions and
30 | * limitations under the License.
31 | */
32 | package io.smallrye.metrics.app;
33 |
34 | import java.util.concurrent.atomic.LongAdder;
35 |
36 | import org.eclipse.microprofile.metrics.Histogram;
37 | import org.eclipse.microprofile.metrics.Snapshot;
38 |
39 | /**
40 | * A metric which calculates the distribution of a value.
41 | *
42 | * @see Accurately computing running
43 | * variance
44 | */
45 | public class HistogramImpl implements Histogram {
46 | private final Reservoir reservoir;
47 | private final LongAdder count;
48 | private final LongAdder sum;
49 |
50 | /**
51 | * Creates a new {@link HistogramImpl} with the given reservoir.
52 | *
53 | * @param reservoir the reservoir to create a histogram from
54 | */
55 | public HistogramImpl(Reservoir reservoir) {
56 | this.reservoir = reservoir;
57 | this.count = new LongAdder();
58 | this.sum = new LongAdder();
59 | }
60 |
61 | /**
62 | * Adds a recorded value.
63 | *
64 | * @param value the length of the value
65 | */
66 | public void update(int value) {
67 | update((long) value);
68 | }
69 |
70 | /**
71 | * Adds a recorded value.
72 | *
73 | * @param value the length of the value
74 | */
75 | public void update(long value) {
76 | count.increment();
77 | sum.add(value);
78 | reservoir.update(value);
79 | }
80 |
81 | /**
82 | * Returns the number of values recorded.
83 | *
84 | * @return the number of values recorded
85 | */
86 | @Override
87 | public long getCount() {
88 | return count.sum();
89 | }
90 |
91 | @Override
92 | public long getSum() {
93 | return sum.sum();
94 | }
95 |
96 | @Override
97 | public Snapshot getSnapshot() {
98 | return reservoir.getSnapshot();
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/CountedInterceptor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.smallrye.metrics.interceptors;
17 |
18 | import java.lang.reflect.AnnotatedElement;
19 | import java.lang.reflect.Member;
20 | import java.util.Set;
21 |
22 | import jakarta.annotation.Priority;
23 | import jakarta.inject.Inject;
24 | import jakarta.interceptor.AroundConstruct;
25 | import jakarta.interceptor.AroundInvoke;
26 | import jakarta.interceptor.AroundTimeout;
27 | import jakarta.interceptor.Interceptor;
28 | import jakarta.interceptor.InvocationContext;
29 |
30 | import org.eclipse.microprofile.metrics.Counter;
31 | import org.eclipse.microprofile.metrics.MetricID;
32 | import org.eclipse.microprofile.metrics.MetricRegistry;
33 | import org.eclipse.microprofile.metrics.MetricType;
34 | import org.eclipse.microprofile.metrics.annotation.Counted;
35 |
36 | import io.smallrye.metrics.MetricRegistries;
37 | import io.smallrye.metrics.MetricsRegistryImpl;
38 | import io.smallrye.metrics.SmallRyeMetricsMessages;
39 | import io.smallrye.metrics.elementdesc.adapter.cdi.CDIMemberInfoAdapter;
40 |
41 | @SuppressWarnings("unused")
42 | @Counted
43 | @Interceptor
44 | @Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)
45 | public class CountedInterceptor {
46 |
47 | private final MetricRegistry registry;
48 |
49 | @Inject
50 | CountedInterceptor() {
51 | this.registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
52 | }
53 |
54 | @AroundConstruct
55 | Object countedConstructor(InvocationContext context) throws Exception {
56 | return countedCallable(context, context.getConstructor());
57 | }
58 |
59 | @AroundInvoke
60 | Object countedMethod(InvocationContext context) throws Exception {
61 | return countedCallable(context, context.getMethod());
62 | }
63 |
64 | @AroundTimeout
65 | Object countedTimeout(InvocationContext context) throws Exception {
66 | return countedCallable(context, context.getMethod());
67 | }
68 |
69 | private Object countedCallable(InvocationContext context, E element)
70 | throws Exception {
71 | Set ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
72 | .getCounters(new CDIMemberInfoAdapter<>().convert(element));
73 | if (ids == null || ids.isEmpty()) {
74 | throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
75 | }
76 | ids.stream()
77 | .map(metricID -> {
78 | Counter metric = registry.getCounters().get(metricID);
79 | if (metric == null) {
80 | throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.COUNTER, metricID);
81 | }
82 | return metric;
83 | })
84 | .forEach(Counter::inc);
85 | return context.proceed();
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/registration/MetadataMismatchTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.registration;
18 |
19 | import static org.hamcrest.CoreMatchers.equalTo;
20 | import static org.hamcrest.CoreMatchers.instanceOf;
21 | import static org.junit.Assert.assertEquals;
22 | import static org.junit.Assert.assertNotEquals;
23 | import static org.junit.Assert.assertThat;
24 | import static org.junit.Assert.fail;
25 |
26 | import org.eclipse.microprofile.metrics.Histogram;
27 | import org.eclipse.microprofile.metrics.Metadata;
28 | import org.eclipse.microprofile.metrics.MetricFilter;
29 | import org.eclipse.microprofile.metrics.MetricRegistry;
30 | import org.eclipse.microprofile.metrics.Tag;
31 | import org.junit.After;
32 | import org.junit.Test;
33 |
34 | import io.smallrye.metrics.MetricRegistries;
35 |
36 | public class MetadataMismatchTest {
37 |
38 | private MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
39 |
40 | @After
41 | public void cleanupApplicationMetrics() {
42 | registry.removeMatching(MetricFilter.ALL);
43 | }
44 |
45 | @Test
46 | public void metricsWithDifferentMetadata() {
47 | Metadata metadata1 = Metadata.builder().withName("myhistogram").withDescription("description1").build();
48 | Metadata metadata2 = Metadata.builder().withName("myhistogram").withDescription("description2").build();
49 |
50 | registry.histogram(metadata1);
51 | try {
52 | registry.histogram(metadata2);
53 | fail("Shouldn't be able to re-register a metric with different metadata");
54 | } catch (Exception e) {
55 | assertThat(e, instanceOf(IllegalStateException.class));
56 | assertEquals(1, registry.getMetrics().size());
57 | }
58 | }
59 |
60 | @Test
61 | public void reusingMetadata() {
62 | Metadata metadata1 = Metadata.builder().withName("myhistogram").withDescription("description1").build();
63 |
64 | Histogram histogram1 = registry.histogram(metadata1);
65 | Histogram histogram2 = registry.histogram("myhistogram", new Tag("color", "blue"));
66 |
67 | assertNotEquals(histogram1, histogram2);
68 | assertEquals(2, registry.getMetrics().size());
69 | assertThat(registry.getMetadata().get("myhistogram").description().get(), equalTo("description1"));
70 | }
71 |
72 | @Test
73 | public void metricsWithSameTypeAndMetadata() {
74 | Metadata metadata1 = Metadata.builder().withName("myhistogram").withDescription("description1").build();
75 | Metadata metadata2 = Metadata.builder().withName("myhistogram").withDescription("description1").build();
76 |
77 | Histogram histogram1 = registry.histogram(metadata1);
78 | Histogram histogram2 = registry.histogram(metadata2);
79 |
80 | assertEquals(histogram1, histogram2);
81 | assertEquals(1, registry.getMetrics().size());
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/MeteredInterceptor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | */
18 | package io.smallrye.metrics.interceptors;
19 |
20 | import java.lang.reflect.AnnotatedElement;
21 | import java.lang.reflect.Member;
22 | import java.util.Set;
23 |
24 | import jakarta.annotation.Priority;
25 | import jakarta.inject.Inject;
26 | import jakarta.interceptor.AroundConstruct;
27 | import jakarta.interceptor.AroundInvoke;
28 | import jakarta.interceptor.AroundTimeout;
29 | import jakarta.interceptor.Interceptor;
30 | import jakarta.interceptor.InvocationContext;
31 |
32 | import org.eclipse.microprofile.metrics.Meter;
33 | import org.eclipse.microprofile.metrics.MetricID;
34 | import org.eclipse.microprofile.metrics.MetricRegistry;
35 | import org.eclipse.microprofile.metrics.MetricType;
36 | import org.eclipse.microprofile.metrics.annotation.Metered;
37 |
38 | import io.smallrye.metrics.MetricRegistries;
39 | import io.smallrye.metrics.MetricsRegistryImpl;
40 | import io.smallrye.metrics.SmallRyeMetricsMessages;
41 | import io.smallrye.metrics.elementdesc.adapter.cdi.CDIMemberInfoAdapter;
42 |
43 | @SuppressWarnings("unused")
44 | @Metered
45 | @Interceptor
46 | @Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)
47 | public class MeteredInterceptor {
48 |
49 | private final MetricRegistry registry;
50 |
51 | @Inject
52 | MeteredInterceptor() {
53 | this.registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
54 | }
55 |
56 | @AroundConstruct
57 | Object meteredConstructor(InvocationContext context) throws Exception {
58 | return meteredCallable(context, context.getConstructor());
59 | }
60 |
61 | @AroundInvoke
62 | Object meteredMethod(InvocationContext context) throws Exception {
63 | return meteredCallable(context, context.getMethod());
64 | }
65 |
66 | @AroundTimeout
67 | Object meteredTimeout(InvocationContext context) throws Exception {
68 | return meteredCallable(context, context.getMethod());
69 | }
70 |
71 | private Object meteredCallable(InvocationContext context, E element)
72 | throws Exception {
73 | Set ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
74 | .getMeters(new CDIMemberInfoAdapter<>().convert(element));
75 | if (ids == null || ids.isEmpty()) {
76 | throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
77 | }
78 | ids.stream()
79 | .map(metricID -> {
80 | Meter metric = registry.getMeters().get(metricID);
81 | if (metric == null) {
82 | throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.METERED, metricID);
83 | }
84 | return metric;
85 | })
86 | .forEach(Meter::mark);
87 | return context.proceed();
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/adapter/cdi/CDIBeanInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc.adapter.cdi;
19 |
20 | import java.lang.annotation.Annotation;
21 | import java.lang.reflect.AnnotatedElement;
22 |
23 | import jakarta.enterprise.inject.Stereotype;
24 |
25 | import io.smallrye.metrics.elementdesc.AnnotationInfo;
26 | import io.smallrye.metrics.elementdesc.BeanInfo;
27 |
28 | public class CDIBeanInfo implements BeanInfo {
29 |
30 | private final Class> input;
31 | private final Package pkg;
32 |
33 | CDIBeanInfo(Class> input) {
34 | this.input = input;
35 | this.pkg = input.getPackage();
36 | }
37 |
38 | @Override
39 | public String getSimpleName() {
40 | return input.getSimpleName();
41 | }
42 |
43 | @Override
44 | public String getPackageName() {
45 | return pkg == null ? null : pkg.getName();
46 | }
47 |
48 | @Override
49 | public AnnotationInfo getAnnotation(Class metric) {
50 | T annotation = input.getAnnotation(metric);
51 | if (annotation != null) {
52 | return new CDIAnnotationInfoAdapter().convert(annotation);
53 | } else {
54 | // the metric annotation can also be applied via a stereotype, so look for stereotype annotations
55 | for (Annotation stereotypeCandidate : ((AnnotatedElement) input).getAnnotations()) {
56 | if (stereotypeCandidate.annotationType().isAnnotationPresent(Stereotype.class) &&
57 | stereotypeCandidate.annotationType().isAnnotationPresent(metric)) {
58 | return new CDIAnnotationInfoAdapter().convert(stereotypeCandidate.annotationType().getAnnotation(metric));
59 | }
60 | }
61 | return null;
62 | }
63 | }
64 |
65 | @Override
66 | public boolean isAnnotationPresent(Class metric) {
67 | if (input.isAnnotationPresent(metric)) {
68 | return true;
69 | } else {
70 | // the metric annotation can also be applied via a stereotype, so look for stereotype annotations
71 | for (Annotation stereotypeCandidate : ((AnnotatedElement) input).getAnnotations()) {
72 | if (stereotypeCandidate.annotationType().isAnnotationPresent(Stereotype.class) &&
73 | stereotypeCandidate.annotationType().isAnnotationPresent(metric)) {
74 | return true;
75 | }
76 | }
77 | return false;
78 | }
79 | }
80 |
81 | @Override
82 | public BeanInfo getSuperclass() {
83 | Class> superclass = input.getSuperclass();
84 | if (superclass != null) {
85 | return new CDIBeanInfo(superclass);
86 | } else {
87 | return null;
88 | }
89 | }
90 |
91 | @Override
92 | public String toString() {
93 | return input.toString();
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/implementation/src/test/java/io/smallrye/metrics/exporters/OpenMetricsUnitScalingTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package io.smallrye.metrics.exporters;
18 |
19 | import static org.junit.Assert.*;
20 |
21 | import java.util.Optional;
22 |
23 | import org.eclipse.microprofile.metrics.MetricUnits;
24 | import org.junit.Test;
25 |
26 | /**
27 | * @author hrupp
28 | */
29 | public class OpenMetricsUnitScalingTest {
30 |
31 | @Test
32 | public void testScaleToSecondsForNanos() {
33 | String foo = MetricUnits.NANOSECONDS;
34 | double out = OpenMetricsUnit.scaleToBase(foo, 3.0);
35 | assertEquals("Out was " + out, 0.000_000_003, out, 0.001);
36 | }
37 |
38 | @Test
39 | public void testScaleToSeconds() {
40 | String foo = MetricUnits.SECONDS;
41 | double out = OpenMetricsUnit.scaleToBase(foo, 3.0);
42 | assertEquals("Out was " + out, 3, out, 0.001);
43 | }
44 |
45 | @Test
46 | public void testScaleToSecondsForDays() {
47 | String foo = MetricUnits.DAYS;
48 | double out = OpenMetricsUnit.scaleToBase(foo, 3.0);
49 | assertEquals("Out was " + out, 3 * 24 * 60 * 60, out, 0.001);
50 | }
51 |
52 | @Test
53 | public void testScaleMegabyteToByte() {
54 | String foo = MetricUnits.MEGABYTES;
55 | double out = OpenMetricsUnit.scaleToBase(foo, 1.0);
56 | assertEquals("Out was " + out, 1_000_000, out, 0.001);
57 | }
58 |
59 | @Test
60 | public void testScaleBitsToByte() {
61 | String foo = MetricUnits.BITS;
62 | double out = OpenMetricsUnit.scaleToBase(foo, 13.0);
63 | assertEquals("Out was " + out, 13.0 / 8.0, out, 0.001);
64 | }
65 |
66 | @Test
67 | public void testFindBaseUnit1() {
68 | String foo = MetricUnits.HOURS;
69 | String out = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(foo));
70 | assertEquals(MetricUnits.SECONDS, out);
71 | String promUnit = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(out));
72 | assertEquals("seconds", promUnit);
73 | }
74 |
75 | @Test
76 | public void testFindBaseUnit2() {
77 | String foo = MetricUnits.MILLISECONDS;
78 | String out = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(foo));
79 | assertEquals(MetricUnits.SECONDS, out);
80 | String promUnit = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(out));
81 | assertEquals("seconds", promUnit);
82 | }
83 |
84 | @Test
85 | public void testFindBaseUnit3() {
86 | String foo = MetricUnits.PERCENT;
87 | String out = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(foo));
88 | assertEquals(MetricUnits.PERCENT, out);
89 | }
90 |
91 | @Test
92 | public void testFindBaseUnit4() {
93 | String foo = MetricUnits.NONE;
94 | String out = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(Optional.ofNullable(foo));
95 | assertEquals(MetricUnits.NONE, out);
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/SmallRyeMetricsLogging.java:
--------------------------------------------------------------------------------
1 | package io.smallrye.metrics;
2 |
3 | import jakarta.enterprise.inject.spi.AnnotatedField;
4 | import jakarta.enterprise.inject.spi.AnnotatedMethod;
5 |
6 | import org.eclipse.microprofile.metrics.MetricID;
7 | import org.eclipse.microprofile.metrics.MetricType;
8 | import org.jboss.logging.Logger;
9 | import org.jboss.logging.annotations.Cause;
10 | import org.jboss.logging.annotations.LogMessage;
11 | import org.jboss.logging.annotations.Message;
12 | import org.jboss.logging.annotations.MessageLogger;
13 |
14 | import io.smallrye.metrics.elementdesc.MemberInfo;
15 |
16 | @MessageLogger(projectCode = "SRMET", length = 5)
17 | public interface SmallRyeMetricsLogging {
18 |
19 | SmallRyeMetricsLogging log = Logger.getMessageLogger(SmallRyeMetricsLogging.class,
20 | SmallRyeMetricsLogging.class.getPackage().getName());
21 |
22 | /* 1000-1099: welcome and boot logs */
23 |
24 | @LogMessage(level = Logger.Level.WARN)
25 | @Message(id = 1000, value = "Unable to detect version of SmallRye Metrics")
26 | void unableToDetectVersion();
27 |
28 | @LogMessage(level = Logger.Level.INFO)
29 | @Message(id = 1001, value = "MicroProfile: Metrics activated (SmallRye Metrics version: %s)")
30 | void logSmallRyeMetricsVersion(String version);
31 |
32 | /* 1100-1199: logs related to application scanning and initialization */
33 |
34 | @LogMessage(level = Logger.Level.DEBUG)
35 | @Message(id = 1100, value = "Metric producer field discovered: %s")
36 | void producerFieldDiscovered(AnnotatedField> field);
37 |
38 | @LogMessage(level = Logger.Level.DEBUG)
39 | @Message(id = 1101, value = "Metric producer method discovered: %s")
40 | void producerMethodDiscovered(AnnotatedMethod> method);
41 |
42 | @LogMessage(level = Logger.Level.TRACE)
43 | @Message(id = 1102, value = "Matching member %s to metric ID=%s and type=%s")
44 | void matchingMemberToMetric(MemberInfo member, MetricID metricID, MetricType metricType);
45 |
46 | @LogMessage(level = Logger.Level.WARN)
47 | @Message(id = 1103, value = "Name [%s] did not contain any placeholders or tags, no replacement will be done, check"
48 | + " the configuration")
49 | void nameDoesNotContainPlaceHoldersOrTags(String name);
50 |
51 | /* 1200-1299: metric registry logs */
52 |
53 | @LogMessage(level = Logger.Level.DEBUG)
54 | @Message(id = 1200, value = "Register metric [metricId: %s, type: %s]")
55 | void registerMetric(MetricID metricID, MetricType metricType);
56 |
57 | @LogMessage(level = Logger.Level.DEBUG)
58 | @Message(id = 1201, value = "Register metric [metricId: %s, type: %s, origin: %s]")
59 | void registerMetric(MetricID metricID, MetricType metricType, Object origin);
60 |
61 | @LogMessage(level = Logger.Level.DEBUG)
62 | @Message(id = 1202, value = "Removing metrics with [name: %s]")
63 | void removeMetricsByName(String name);
64 |
65 | @LogMessage(level = Logger.Level.DEBUG)
66 | @Message(id = 1203, value = "Removing metric with [id: %s]")
67 | void removeMetricsById(MetricID id);
68 |
69 | @LogMessage(level = Logger.Level.DEBUG)
70 | @Message(id = 1204, value = "Remove metadata for [name: %s]")
71 | void removeMetadata(String name);
72 |
73 | /* 1300-1399: exporter logs */
74 |
75 | @LogMessage(level = Logger.Level.DEBUG)
76 | @Message(id = 1300, value = "Unable to export metric %s")
77 | void unableToExport(String name, @Cause Exception e);
78 |
79 | @LogMessage(level = Logger.Level.ERROR)
80 | @Message(id = 1301, value = "The expected context root of metrics is \"%s\", but a request with a different " +
81 | "path was routed to MetricsRequestHandler")
82 | void contextPathMismatch(String name);
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/RawAnnotationInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc;
19 |
20 | public class RawAnnotationInfo implements AnnotationInfo {
21 |
22 | private String name;
23 |
24 | private boolean absolute;
25 |
26 | private String[] tags;
27 |
28 | private String unit;
29 |
30 | private String description;
31 |
32 | private String displayName;
33 |
34 | private String annotationName;
35 |
36 | public RawAnnotationInfo() {
37 |
38 | }
39 |
40 | public RawAnnotationInfo(String name, boolean absolute, String[] tags, String unit,
41 | String description, String displayName, String annotationName) {
42 | this.name = name;
43 | this.absolute = absolute;
44 | this.tags = tags;
45 | this.unit = unit;
46 | this.description = description;
47 | this.displayName = displayName;
48 | this.annotationName = annotationName;
49 | }
50 |
51 | public String getName() {
52 | return name;
53 | }
54 |
55 | public void setName(String name) {
56 | this.name = name;
57 | }
58 |
59 | public boolean isAbsolute() {
60 | return absolute;
61 | }
62 |
63 | public void setAbsolute(boolean absolute) {
64 | this.absolute = absolute;
65 | }
66 |
67 | public String[] getTags() {
68 | return tags;
69 | }
70 |
71 | public void setTags(String[] tags) {
72 | this.tags = tags;
73 | }
74 |
75 | public String getUnit() {
76 | return unit;
77 | }
78 |
79 | public void setUnit(String unit) {
80 | this.unit = unit;
81 | }
82 |
83 | public String getDescription() {
84 | return description;
85 | }
86 |
87 | public void setDescription(String description) {
88 | this.description = description;
89 | }
90 |
91 | public String getDisplayName() {
92 | return displayName;
93 | }
94 |
95 | public void setDisplayName(String displayName) {
96 | this.displayName = displayName;
97 | }
98 |
99 | public String getAnnotationName() {
100 | return annotationName;
101 | }
102 |
103 | public void setAnnotationName(String annotationName) {
104 | this.annotationName = annotationName;
105 | }
106 |
107 | @Override
108 | public String name() {
109 | return name;
110 | }
111 |
112 | @Override
113 | public boolean absolute() {
114 | return absolute;
115 | }
116 |
117 | @Override
118 | public String[] tags() {
119 | return tags;
120 | }
121 |
122 | @Override
123 | public String unit() {
124 | return unit;
125 | }
126 |
127 | @Override
128 | public String description() {
129 | return description;
130 | }
131 |
132 | @Override
133 | public String displayName() {
134 | return displayName;
135 | }
136 |
137 | @Override
138 | public String annotationName() {
139 | return annotationName;
140 | }
141 |
142 | }
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/elementdesc/RawBeanInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package io.smallrye.metrics.elementdesc;
19 |
20 | import java.lang.annotation.Annotation;
21 | import java.util.ArrayList;
22 | import java.util.Collection;
23 | import java.util.List;
24 |
25 | public class RawBeanInfo implements BeanInfo {
26 |
27 | private String simpleName;
28 |
29 | private String packageName;
30 |
31 | private List annotationInfos = new ArrayList<>();
32 | private AnnotationInfo[] infosArray;
33 |
34 | private BeanInfo superClassInfo;
35 |
36 | public RawBeanInfo() {
37 |
38 | }
39 |
40 | public RawBeanInfo(String simpleName, String packageName, Collection annotationInfos,
41 | BeanInfo superClassInfo) {
42 | this.simpleName = simpleName;
43 | this.packageName = packageName;
44 | this.annotationInfos.addAll(annotationInfos);
45 | this.superClassInfo = superClassInfo;
46 | this.infosArray = annotationInfos.toArray(new AnnotationInfo[] {});
47 | }
48 |
49 | public void setSimpleName(String simpleName) {
50 | this.simpleName = simpleName;
51 | }
52 |
53 | public void setPackageName(String packageName) {
54 | this.packageName = packageName;
55 | }
56 |
57 | public List getAnnotationInfos() {
58 | return annotationInfos;
59 | }
60 |
61 | public void setAnnotationInfos(List annotationInfos) {
62 | this.annotationInfos = annotationInfos;
63 | }
64 |
65 | public AnnotationInfo[] getInfosArray() {
66 | return infosArray;
67 | }
68 |
69 | public void setInfosArray(AnnotationInfo[] infosArray) {
70 | this.infosArray = infosArray;
71 | }
72 |
73 | public BeanInfo getSuperClassInfo() {
74 | return superClassInfo;
75 | }
76 |
77 | public void setSuperClassInfo(BeanInfo superClassInfo) {
78 | this.superClassInfo = superClassInfo;
79 | }
80 |
81 | @Override
82 | public String getSimpleName() {
83 | return simpleName;
84 | }
85 |
86 | @Override
87 | public String getPackageName() {
88 | return packageName;
89 | }
90 |
91 | @Override
92 | public AnnotationInfo getAnnotation(Class metric) {
93 | return annotationInfos.stream().filter(annotation -> annotation.annotationName().equals(metric.getName())).findFirst()
94 | .orElse(null);
95 | }
96 |
97 | @Override
98 | public boolean isAnnotationPresent(Class metric) {
99 | return annotationInfos.stream().anyMatch(annotation -> annotation.annotationName().equals(metric.getName()));
100 | }
101 |
102 | @Override
103 | public BeanInfo getSuperclass() {
104 | return superClassInfo;
105 | }
106 |
107 | @Override
108 | public boolean equals(Object obj) {
109 | if (!(obj instanceof BeanInfo)) {
110 | return false;
111 | } else {
112 | return this.getSimpleName().equals(((BeanInfo) obj).getSimpleName());
113 | }
114 | }
115 |
116 | @Override
117 | public int hashCode() {
118 | return this.getSimpleName().hashCode();
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/implementation/src/main/java/io/smallrye/metrics/interceptors/SimplyTimedInterceptor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Red Hat, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | */
18 | package io.smallrye.metrics.interceptors;
19 |
20 | import java.lang.reflect.AnnotatedElement;
21 | import java.lang.reflect.Member;
22 | import java.util.List;
23 | import java.util.Set;
24 | import java.util.stream.Collectors;
25 |
26 | import jakarta.annotation.Priority;
27 | import jakarta.inject.Inject;
28 | import jakarta.interceptor.AroundConstruct;
29 | import jakarta.interceptor.AroundInvoke;
30 | import jakarta.interceptor.AroundTimeout;
31 | import jakarta.interceptor.Interceptor;
32 | import jakarta.interceptor.InvocationContext;
33 |
34 | import org.eclipse.microprofile.metrics.MetricID;
35 | import org.eclipse.microprofile.metrics.MetricRegistry;
36 | import org.eclipse.microprofile.metrics.MetricType;
37 | import org.eclipse.microprofile.metrics.SimpleTimer;
38 | import org.eclipse.microprofile.metrics.annotation.SimplyTimed;
39 |
40 | import io.smallrye.metrics.MetricRegistries;
41 | import io.smallrye.metrics.MetricsRegistryImpl;
42 | import io.smallrye.metrics.SmallRyeMetricsMessages;
43 | import io.smallrye.metrics.elementdesc.adapter.cdi.CDIMemberInfoAdapter;
44 |
45 | @SuppressWarnings("unused")
46 | @SimplyTimed
47 | @Interceptor
48 | @Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)
49 | public class SimplyTimedInterceptor {
50 |
51 | private final MetricRegistry registry;
52 |
53 | @Inject
54 | SimplyTimedInterceptor() {
55 | this.registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
56 | }
57 |
58 | @AroundConstruct
59 | Object simplyTimedConstructor(InvocationContext context) throws Exception {
60 | return timedCallable(context, context.getConstructor());
61 | }
62 |
63 | @AroundInvoke
64 | Object simplyTimedMethod(InvocationContext context) throws Exception {
65 | return timedCallable(context, context.getMethod());
66 | }
67 |
68 | @AroundTimeout
69 | Object simplyTimedTimeout(InvocationContext context) throws Exception {
70 | return timedCallable(context, context.getMethod());
71 | }
72 |
73 | private Object timedCallable(InvocationContext invocationContext, E element)
74 | throws Exception {
75 | Set ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
76 | .getSimpleTimers(new CDIMemberInfoAdapter<>().convert(element));
77 | if (ids == null || ids.isEmpty()) {
78 | throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
79 | }
80 | List contexts = ids.stream()
81 | .map(metricID -> {
82 | SimpleTimer metric = registry.getSimpleTimers().get(metricID);
83 | if (metric == null) {
84 | throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.SIMPLE_TIMER, metricID);
85 | }
86 | return metric;
87 | })
88 | .map(SimpleTimer::time)
89 | .collect(Collectors.toList());
90 | try {
91 | return invocationContext.proceed();
92 | } finally {
93 | for (SimpleTimer.Context timeContext : contexts) {
94 | timeContext.stop();
95 | }
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------