├── .gitignore
├── LICENSE.txt
├── README.md
├── RELEASE-NOTES.md
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
└── java
│ └── com
│ └── palominolabs
│ └── metrics
│ └── guice
│ ├── CountedInterceptor.java
│ ├── CountedListener.java
│ ├── DeclaredMethodsTypeListener.java
│ ├── DeclaringClassMetricNamer.java
│ ├── ExceptionMeteredInterceptor.java
│ ├── ExceptionMeteredListener.java
│ ├── GaugeInjectionListener.java
│ ├── GaugeInstanceClassMetricNamer.java
│ ├── GaugeListener.java
│ ├── MeteredInterceptor.java
│ ├── MeteredListener.java
│ ├── MetricNamer.java
│ ├── MetricsInstrumentationModule.java
│ ├── TimedInterceptor.java
│ ├── TimedListener.java
│ └── annotation
│ ├── AnnotationResolver.java
│ ├── ClassAnnotationResolver.java
│ ├── ListAnnotationResolver.java
│ └── MethodAnnotationResolver.java
└── test
└── java
└── com
└── palominolabs
└── metrics
└── guice
├── CountInvocationGenericSubtypeTest.java
├── CountedTest.java
├── DeclaringClassNamerGaugeTest.java
├── ExceptionMeteredTest.java
├── GaugeInheritanceTest.java
├── GaugeInstanceClassNamerTest.java
├── GaugeTestBase.java
├── GenericThing.java
├── InstrumentedWithCounter.java
├── InstrumentedWithCounterParent.java
├── InstrumentedWithExceptionMetered.java
├── InstrumentedWithGauge.java
├── InstrumentedWithGaugeParent.java
├── InstrumentedWithMetered.java
├── InstrumentedWithTimed.java
├── MatcherTest.java
├── MeteredTest.java
├── MyException.java
├── StringThing.java
├── TimedTest.java
└── annotation
├── ClassAnnotationResolverTest.java
├── ListAnnotationResolverTest.java
└── MethodAnnotationResolverTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .idea
3 | *.ipr
4 | *.iws
5 | .directory
6 | /out
7 | .~lock.*.od*#
8 | build
9 | .gradle
10 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | # Copyfree Open Innovation License
2 |
3 | This is version 0.6 of the Copyfree Open Innovation License.
4 |
5 | ## Terms and Conditions
6 |
7 | Redistributions, modified or unmodified, in whole or in part, must retain
8 | applicable notices of copyright or other legal privilege, these conditions, and
9 | the following license terms and disclaimer. Subject to these conditions, each
10 | holder of copyright or other legal privileges, author or assembler, and
11 | contributor of this work, henceforth "licensor", hereby grants to any person
12 | who obtains a copy of this work in any form:
13 |
14 | 1. Permission to reproduce, modify, distribute, publish, sell, sublicense, use,
15 | and/or otherwise deal in the licensed material without restriction.
16 |
17 | 2. A perpetual, worldwide, non-exclusive, royalty-free, gratis, irrevocable
18 | patent license to make, have made, provide, transfer, import, use, and/or
19 | otherwise deal in the licensed material without restriction, for any and all
20 | patents held by such licensor and necessarily infringed by the form of the work
21 | upon distribution of that licensor's contribution to the work under the terms
22 | of this license.
23 |
24 | NO WARRANTY OF ANY KIND IS IMPLIED BY, OR SHOULD BE INFERRED FROM, THIS LICENSE
25 | OR THE ACT OF DISTRIBUTION UNDER THE TERMS OF THIS LICENSE, INCLUDING BUT NOT
26 | LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
27 | AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, ASSEMBLERS, OR HOLDERS OF
28 | COPYRIGHT OR OTHER LEGAL PRIVILEGE BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
29 | LIABILITY, WHETHER IN ACTION OF CONTRACT, TORT, OR OTHERWISE ARISING FROM, OUT
30 | OF, OR IN CONNECTION WITH THE WORK OR THE USE OF OR OTHER DEALINGS IN THE WORK.
31 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Quick Start
2 |
3 | ### Get the artifacts
4 |
5 | Artifacts are released in Maven Central.
6 |
7 | Maven:
8 |
9 | ```xml
10 |
11 | com.palominolabs.metrics
12 | metrics-guice
13 | [the latest version]
14 |
15 | ```
16 |
17 | Gradle:
18 |
19 | ```
20 | compile 'com.palominolabs.metrics:metrics-guice:[the latest version]'
21 | ```
22 |
23 | ### Install the Guice module
24 |
25 | ```java
26 | // somewhere in your Guice module setup
27 | install(MetricsInstrumentationModule.builder().withMetricRegistry(yourFavoriteMetricRegistry).build());
28 | ```
29 |
30 | ### Use it
31 |
32 | The `MetricsInstrumentationModule` you installed above will create and appropriately invoke a [Timer](https://dropwizard.github.io/metrics/3.1.0/manual/core/#timers) for `@Timed` methods, a [Meter](https://dropwizard.github.io/metrics/3.1.0/manual/core/#meters) for `@Metered` methods, a [Counter](https://dropwizard.github.io/metrics/3.1.0/manual/core/#counters) for `@Counted` methods, and a [Gauge](https://dropwizard.github.io/metrics/3.1.0/manual/core/#gauges) for `@Gauge` methods. `@ExceptionMetered` is also supported; this creates a `Meter` that measures how often a method throws exceptions.
33 |
34 | The annotations have some configuration options available for metric name, etc. You can also provide a custom `MetricNamer` implementation if the default name scheme does not work for you.
35 |
36 | ### Customizing annotation lookup
37 |
38 | By default `MetricsInstrumentationModule` will provide metrics only for annotated methods. You can also look for annotations on the enclosing classes, or both, or provide your own custom logic. To change annotation resolution, provide an `AnnotationResolver` when building the `MetricsInstrumentationModule`. `MethodAnnotationResolver` is the default implementation. `ClassAnnotationResolver` will look for annotations on the class instead of the method. You can invoke multiple resolvers in order with `ListAnnotationResolver `, so if you wanted to look in methods first and then the class, you could do that:
39 |
40 | ```java
41 | // somewhere in your Guice module setup
42 | install(
43 | MetricsInstrumentationModule.builder()
44 | .withMetricRegistry(yourFavoriteMetricRegistry)
45 | .withAnnotationResolver(new ListAnnotationResolver(Lists.newArrayList(new ClassAnnotationResolver(), new MethodAnnotationResolver()))
46 | .build()
47 | );
48 | ```
49 |
50 | ### Metric namer
51 |
52 | The default `MetricNamer` implementation probably does what you want out of the box, but you can also write and use your own.
53 |
54 | #### Example
55 |
56 | If you have a method like this:
57 |
58 | ```java
59 | class SuperCriticalFunctionality {
60 | public void doSomethingImportant() {
61 | // critical business logic
62 | }
63 | }
64 | ```
65 |
66 | and you want to use a [Timer](https://dropwizard.github.io/metrics/3.1.0/manual/core/#timers) to measure duration, etc, you could always do it by hand:
67 |
68 | ```java
69 | public void doSomethingImportant() {
70 | // timer is some Timer instance
71 | Timer.Context context = timer.time();
72 | try {
73 | // critical business logic
74 | } finally {
75 | context.stop();
76 | }
77 | }
78 | ```
79 |
80 | However, if you're instantiating that class with Guice, you could just do this:
81 |
82 | ```java
83 | @Timed
84 | public void doSomethingImportant() {
85 | // critical business logic
86 | }
87 | ```
88 |
89 | ### Limitations
90 |
91 | Since this uses Guice AOP, instances must be created by Guice; see [the Guice wiki](https://github.com/google/guice/wiki/AOP). This means that using a Provider where you create the instance won't work, or binding a singleton to an instance, etc.
92 |
93 | Guice AOP doesn't allow us to intercept method calls to annotated methods in supertypes, so `@Counted`, etc, will not have metrics generated for them if they are in supertypes of the injectable class. One small consolation is that `@Gauge` methods can be anywhere in the type hierarchy since they work differently from the other metrics (the generated Gauge object invokes the `java.lang.reflect.Method` directly, so we can call the supertype method unambiguously).
94 |
95 | One common way users might hit this issue is if when trying to use `@Counted`, etc on a JAX-RS resource annotated with `@Path`, `@GET`, etc. This may pose problems for the JAX-RS implementation because the thing it has at runtime is now an auto-generated proxy class, not the "normal" class. A perfectly reasonable approach is instead to handle metrics generation for those classes via the hooks available in the JAX-RS implementation. For Jersey 2, might I suggest [jersey2-metrics](https://bitbucket.org/marshallpierce/jersey2-metrics)?
96 |
97 | # History
98 |
99 | This module started from the state of metrics-guice immediately before it was removed from the [main metrics repo](https://github.com/dropwizard/metrics) in [dropwizard/metrics@e058f76dabf3f805d1c220950a4f42c2ec605ecd](https://github.com/dropwizard/metrics/commit/e058f76dabf3f805d1c220950a4f42c2ec605ecd).
100 |
101 |
--------------------------------------------------------------------------------
/RELEASE-NOTES.md:
--------------------------------------------------------------------------------
1 | - 5.0.1
2 | - Publish to maven central
3 | - Build system updates
4 | - 5.0.0
5 | - Build system updates; update Gradle to 6.8
6 | - Update to Guice 4.2.3
7 | - Update to Metrics 5.0.0
8 | - 4.0.0
9 | - Build system updates; update Gradle to 4.6
10 | - Update to Metrics 4.0.2
11 | - Update to Java 8
12 | - 3.3.0
13 | - Change default `MetricNamer` implementation to one that is friendlier to re-using superclass gauges in multiple child classes. The previous behavior is still available as `DeclaringClassMetricNamer`.
14 | - Change `MetricNamer.getNameForGauge` to take an additional parameter to support the superclass logic above.
15 | - Add Animal Sniffer to build to ensure that only JDK6 types are used.
16 | - Update to Gradle 4.0.1
17 | - 3.2.2
18 | - Update to Metrics 3.2.3
19 | - Update to Gradle 4.0
20 | - 3.2.1
21 | - Update to Metrics 3.2 and SLF4J 1.7.25
22 | - Update to Gradle 3.4
23 | - 3.2.0
24 | - Update to Gradle 3.1
25 | - Updated dependencies: SLF4J 1.7.21, Guice 4.1.0
26 | - Allow customization in how annotations are resolved for a method. The default is the previous behavior (only looks on the method itself), but implementations for looking on the class and combining multiple resolvers are provided.
27 | - `MetricsInstrumentationModule` is now constructed builder-style.
28 | - 3.1.4
29 | - Switch to releasing in bintray
30 | - Remove superclass traversal when looking for annotated methods to intercept because AOP on superclass methods doesn't appear to work anyway
31 | - Switch build to Gradle
32 | - License under COIL
33 | - Add ability to have non-public @Gauge methods anywhere in the type hierarchy of an injected type
34 | - Updated dependencies: Metrics 3.1.2, SLF4J 1.7.12, Guice 4.0
35 | - 3.1.3
36 | - Add support for `@Counted`
37 | - Move metric name creation into `MetricNamer` for easy customization
38 | - Move AdminServletModule into [metrics-guice-servlet](https://github.com/palominolabs/metrics-guice-servlet)
39 | - 3.1.2
40 | - Make injection listeners public
41 | - Depend on Metrics 3.1.0
42 | - Tweak metric naming to avoid duplicate names for different metrics
43 | - 3.1.1
44 | - Allow specifying a custom matcher
45 | - 3.1.0
46 | - Don't create MetricRegistry, HealthCheckRegistry, or JmxReporter for the user. This makes it easier to integrate with existing systems that already have instances that should be used.
47 | - Rename InstrumentationModule to MetricsInstrumentationModule
48 | - Update to SLF4J
49 | - 3.0.2
50 | - Update to Metrics 3.0.2
51 | - 3.0.1
52 | - Update to Jackson 2.0.2
53 | - Update to Metrics 3.0.1
54 | - Update to SLF4J 1.7.6
55 | - Use javax.servlet:javax.servlet-api for servlet implementation
56 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import java.time.Duration
2 | import java.net.URI
3 |
4 | plugins {
5 | `java-library`
6 | `maven-publish`
7 | signing
8 | id("biz.aQute.bnd.builder") version "5.3.0"
9 | id("net.researchgate.release") version "2.8.1"
10 | id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
11 | id("com.github.ben-manes.versions") version "0.38.0"
12 | id("ru.vyarus.animalsniffer") version "1.5.3"
13 | }
14 |
15 | repositories {
16 | mavenCentral()
17 | }
18 |
19 | group = "com.palominolabs.metrics"
20 |
21 | val deps by extra {
22 | mapOf(
23 | "metrics" to "5.0.0",
24 | "slf4j" to "1.7.30",
25 | "guice" to "4.2.3"
26 | )
27 | }
28 |
29 | dependencies {
30 | implementation("io.dropwizard.metrics5:metrics-core:${deps["metrics"]}")
31 | implementation("io.dropwizard.metrics5:metrics-annotation:${deps["metrics"]}")
32 | implementation("com.google.inject:guice:${deps["guice"]}")
33 | implementation("com.google.code.findbugs:jsr305:3.0.2")
34 |
35 | testRuntimeOnly("org.slf4j:slf4j-simple:${deps["slf4j"]}")
36 | testRuntimeOnly("org.slf4j:jul-to-slf4j:${deps["slf4j"]}")
37 | testRuntimeOnly("org.slf4j:log4j-over-slf4j:${deps["slf4j"]}")
38 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.0")
39 | testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.0")
40 | testImplementation("org.hamcrest:hamcrest-all:1.3")
41 |
42 | signature("org.codehaus.mojo.signature:java18:1.0@signature")
43 | }
44 |
45 | java {
46 | sourceCompatibility = JavaVersion.VERSION_1_8
47 | targetCompatibility = JavaVersion.VERSION_1_8
48 | withSourcesJar()
49 | withJavadocJar()
50 | }
51 |
52 | tasks.withType {
53 | options.compilerArgs.add("-Xlint:unchecked")
54 | options.isDeprecation = true
55 | options.encoding = "UTF-8"
56 | }
57 |
58 | tasks {
59 | test {
60 | useJUnitPlatform()
61 | }
62 |
63 | afterReleaseBuild {
64 | dependsOn(provider { project.tasks.named("publishToSonatype") })
65 | }
66 | }
67 |
68 | publishing {
69 | publications {
70 | register("sonatype") {
71 | from(components["java"])
72 | // sonatype required pom elements
73 | pom {
74 | name.set("${project.group}:${project.name}")
75 | description.set(name)
76 | url.set("https://github.com/palominolabs/metrics-guice")
77 | licenses {
78 | license {
79 | name.set("Copyfree Open Innovation License 0.4")
80 | url.set("https://copyfree.org/content/standard/licenses/coil/license.txt")
81 | }
82 | }
83 | developers {
84 | developer {
85 | id.set("marshallpierce")
86 | name.set("Marshall Pierce")
87 | email.set("575695+marshallpierce@users.noreply.github.com")
88 | }
89 | }
90 | scm {
91 | connection.set("scm:git:https://github.com/palominolabs/metrics-guice")
92 | developerConnection.set("scm:git:ssh://git@github.com:palominolabs/metrics-guice.git")
93 | url.set("https://github.com/palominolabs/metrics-guice")
94 | }
95 | }
96 | }
97 | }
98 |
99 | // A safe throw-away place to publish to:
100 | // ./gradlew publishSonatypePublicationToLocalDebugRepository -Pversion=foo
101 | repositories {
102 | maven {
103 | name = "localDebug"
104 | url = URI.create("file:///${project.buildDir}/repos/localDebug")
105 | }
106 | }
107 | }
108 |
109 | // don't barf for devs without signing set up
110 | if (project.hasProperty("signing.keyId")) {
111 | signing {
112 | sign(project.extensions.getByType().publications["sonatype"])
113 | }
114 | }
115 |
116 | nexusPublishing {
117 | repositories {
118 | sonatype {
119 | // sonatypeUsername and sonatypePassword properties are used automatically
120 | stagingProfileId.set("26c8b7fff47581") // com.palominolabs
121 | }
122 | }
123 | // these are not strictly required. The default timeouts are set to 1 minute. But Sonatype can be really slow.
124 | // If you get the error "java.net.SocketTimeoutException: timeout", these lines will help.
125 | connectTimeout.set(Duration.ofMinutes(3))
126 | clientTimeout.set(Duration.ofMinutes(3))
127 | }
128 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | version = 5.0.2-SNAPSHOT
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/palominolabs/metrics-guice/a7fc18f359f9d55963b321aff782f8008e11f692/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'metrics-guice'
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/CountedInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import io.dropwizard.metrics5.Counter;
4 | import io.dropwizard.metrics5.annotation.Counted;
5 | import org.aopalliance.intercept.MethodInterceptor;
6 | import org.aopalliance.intercept.MethodInvocation;
7 |
8 | class CountedInterceptor implements MethodInterceptor {
9 |
10 | private final Counter counter;
11 | private final boolean decrementAfterMethod;
12 |
13 | CountedInterceptor(Counter counter, Counted annotation) {
14 | this.counter = counter;
15 | decrementAfterMethod = !annotation.monotonic();
16 | }
17 |
18 | @Override
19 | public Object invoke(MethodInvocation invocation) throws Throwable {
20 | counter.inc();
21 | try {
22 | return invocation.proceed();
23 | } finally {
24 | if (decrementAfterMethod) {
25 | counter.dec();
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/CountedListener.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import io.dropwizard.metrics5.Counter;
4 | import io.dropwizard.metrics5.MetricRegistry;
5 | import io.dropwizard.metrics5.annotation.Counted;
6 | import com.palominolabs.metrics.guice.annotation.AnnotationResolver;
7 | import java.lang.reflect.Method;
8 | import javax.annotation.Nullable;
9 | import org.aopalliance.intercept.MethodInterceptor;
10 |
11 | /**
12 | * A listener which adds method interceptors to counted methods.
13 | */
14 | public class CountedListener extends DeclaredMethodsTypeListener {
15 | private final MetricRegistry metricRegistry;
16 | private final MetricNamer metricNamer;
17 | private final AnnotationResolver annotationResolver;
18 |
19 | public CountedListener(MetricRegistry metricRegistry, MetricNamer metricNamer,
20 | AnnotationResolver annotationResolver) {
21 | this.metricRegistry = metricRegistry;
22 | this.metricNamer = metricNamer;
23 | this.annotationResolver = annotationResolver;
24 | }
25 |
26 | @Nullable
27 | @Override
28 | protected MethodInterceptor getInterceptor(Method method) {
29 | final Counted annotation = annotationResolver.findAnnotation(Counted.class, method);
30 | if (annotation != null) {
31 | final Counter counter = metricRegistry.counter(metricNamer.getNameForCounted(method, annotation));
32 | return new CountedInterceptor(counter, annotation);
33 | }
34 | return null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/DeclaredMethodsTypeListener.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import com.google.inject.TypeLiteral;
4 | import com.google.inject.matcher.Matchers;
5 | import com.google.inject.spi.TypeEncounter;
6 | import com.google.inject.spi.TypeListener;
7 | import java.lang.reflect.Method;
8 | import javax.annotation.Nullable;
9 | import org.aopalliance.intercept.MethodInterceptor;
10 |
11 | /**
12 | * A TypeListener which delegates to {@link DeclaredMethodsTypeListener#getInterceptor(Method)} for each method in the
13 | * class's declared methods.
14 | */
15 | abstract class DeclaredMethodsTypeListener implements TypeListener {
16 |
17 | @Override
18 | public void hear(TypeLiteral literal, TypeEncounter encounter) {
19 | Class super T> klass = literal.getRawType();
20 |
21 | for (Method method : klass.getDeclaredMethods()) {
22 | if (method.isSynthetic()) {
23 | continue;
24 | }
25 |
26 | final MethodInterceptor interceptor = getInterceptor(method);
27 | if (interceptor != null) {
28 | encounter.bindInterceptor(Matchers.only(method), interceptor);
29 | }
30 | }
31 | }
32 |
33 | /**
34 | * Called for every method on every class in the type hierarchy of the visited type
35 | *
36 | * @param method method to get interceptor for
37 | * @return null if no interceptor should be applied, else an interceptor
38 | */
39 | @Nullable
40 | protected abstract MethodInterceptor getInterceptor(Method method);
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/DeclaringClassMetricNamer.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import io.dropwizard.metrics5.MetricName;
4 | import io.dropwizard.metrics5.annotation.Counted;
5 | import io.dropwizard.metrics5.annotation.ExceptionMetered;
6 | import io.dropwizard.metrics5.annotation.Gauge;
7 | import io.dropwizard.metrics5.annotation.Metered;
8 | import io.dropwizard.metrics5.annotation.Timed;
9 | import java.lang.reflect.Method;
10 | import javax.annotation.Nonnull;
11 |
12 | import static io.dropwizard.metrics5.MetricRegistry.name;
13 |
14 | /**
15 | * Uses the name fields in the metric annotations, if present, or the method declaring class and method name.
16 | */
17 | public class DeclaringClassMetricNamer implements MetricNamer {
18 | static final String COUNTER_SUFFIX = "counter";
19 | static final String COUNTER_SUFFIX_MONOTONIC = "current";
20 | static final String GAUGE_SUFFIX = "gauge";
21 | static final String METERED_SUFFIX = "meter";
22 | static final String TIMED_SUFFIX = "timer";
23 |
24 | @Nonnull
25 | @Override
26 | public MetricName getNameForCounted(@Nonnull Method method, @Nonnull Counted counted) {
27 | if (counted.absolute()) {
28 | return name(counted.name());
29 | }
30 |
31 | if (counted.name().isEmpty()) {
32 | if (counted.monotonic()) {
33 | return name(method.getDeclaringClass(), method.getName(), COUNTER_SUFFIX_MONOTONIC);
34 | } else {
35 | return name(method.getDeclaringClass(), method.getName(), COUNTER_SUFFIX);
36 | }
37 | }
38 |
39 | return name(method.getDeclaringClass(), counted.name());
40 | }
41 |
42 | @Nonnull
43 | @Override
44 | public MetricName getNameForExceptionMetered(@Nonnull Method method, @Nonnull ExceptionMetered exceptionMetered) {
45 | if (exceptionMetered.absolute()) {
46 | return name(exceptionMetered.name());
47 | }
48 |
49 | if (exceptionMetered.name().isEmpty()) {
50 | return
51 | name(method.getDeclaringClass(), method.getName(), ExceptionMetered.DEFAULT_NAME_SUFFIX);
52 | }
53 |
54 | return name(method.getDeclaringClass(), exceptionMetered.name());
55 | }
56 |
57 | @Nonnull
58 | @Override
59 | public MetricName getNameForGauge(@Nonnull Class> instanceClass, @Nonnull Method method, @Nonnull Gauge gauge) {
60 | if (gauge.absolute()) {
61 | return name(gauge.name());
62 | }
63 |
64 | if (gauge.name().isEmpty()) {
65 | return name(method.getDeclaringClass(), method.getName(), GAUGE_SUFFIX);
66 | }
67 |
68 | return name(method.getDeclaringClass(), gauge.name());
69 | }
70 |
71 | @Nonnull
72 | @Override
73 | public MetricName getNameForMetered(@Nonnull Method method, @Nonnull Metered metered) {
74 | if (metered.absolute()) {
75 | return name(metered.name());
76 | }
77 |
78 | if (metered.name().isEmpty()) {
79 | return name(method.getDeclaringClass(), method.getName(), METERED_SUFFIX);
80 | }
81 |
82 | return name(method.getDeclaringClass(), metered.name());
83 | }
84 |
85 | @Nonnull
86 | @Override
87 | public MetricName getNameForTimed(@Nonnull Method method, @Nonnull Timed timed) {
88 | if (timed.absolute()) {
89 | return name(timed.name());
90 | }
91 |
92 | if (timed.name().isEmpty()) {
93 | return name(method.getDeclaringClass(), method.getName(), TIMED_SUFFIX);
94 | }
95 |
96 | return name(method.getDeclaringClass(), timed.name());
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/ExceptionMeteredInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import io.dropwizard.metrics5.Meter;
4 | import org.aopalliance.intercept.MethodInterceptor;
5 | import org.aopalliance.intercept.MethodInvocation;
6 |
7 | /**
8 | * A method interceptor which measures the rate at which the annotated method throws exceptions of a given type.
9 | */
10 | class ExceptionMeteredInterceptor implements MethodInterceptor {
11 |
12 | private final Meter meter;
13 | private final Class extends Throwable> klass;
14 |
15 | ExceptionMeteredInterceptor(Meter meter, Class extends Throwable> klass) {
16 | this.meter = meter;
17 | this.klass = klass;
18 | }
19 |
20 | @Override
21 | public Object invoke(MethodInvocation invocation) throws Throwable {
22 | try {
23 | return invocation.proceed();
24 | } catch (Throwable t) {
25 | if (klass.isAssignableFrom(t.getClass())) {
26 | meter.mark();
27 | }
28 | throw t;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/ExceptionMeteredListener.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import io.dropwizard.metrics5.Meter;
4 | import io.dropwizard.metrics5.MetricRegistry;
5 | import io.dropwizard.metrics5.annotation.ExceptionMetered;
6 | import com.palominolabs.metrics.guice.annotation.AnnotationResolver;
7 | import java.lang.reflect.Method;
8 | import javax.annotation.Nullable;
9 | import org.aopalliance.intercept.MethodInterceptor;
10 |
11 | /**
12 | * A listener which adds method interceptors to methods that should be instrumented for exceptions
13 | */
14 | public class ExceptionMeteredListener extends DeclaredMethodsTypeListener {
15 | private final MetricRegistry metricRegistry;
16 | private final MetricNamer metricNamer;
17 | private final AnnotationResolver annotationResolver;
18 |
19 | public ExceptionMeteredListener(MetricRegistry metricRegistry, MetricNamer metricNamer,
20 | final AnnotationResolver annotationResolver) {
21 | this.metricRegistry = metricRegistry;
22 | this.metricNamer = metricNamer;
23 | this.annotationResolver = annotationResolver;
24 | }
25 |
26 | @Nullable
27 | @Override
28 | protected MethodInterceptor getInterceptor(Method method) {
29 | final ExceptionMetered annotation = annotationResolver.findAnnotation(ExceptionMetered.class, method);
30 | if (annotation != null) {
31 | final Meter meter = metricRegistry.meter(metricNamer.getNameForExceptionMetered(method, annotation));
32 | return new ExceptionMeteredInterceptor(meter, annotation.cause());
33 | }
34 | return null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/palominolabs/metrics/guice/GaugeInjectionListener.java:
--------------------------------------------------------------------------------
1 | package com.palominolabs.metrics.guice;
2 |
3 | import io.dropwizard.metrics5.Gauge;
4 | import io.dropwizard.metrics5.MetricName;
5 | import io.dropwizard.metrics5.MetricRegistry;
6 | import com.google.inject.spi.InjectionListener;
7 |
8 | import java.lang.reflect.Method;
9 |
10 | /**
11 | * An injection listener which creates a gauge for the declaring class with the given name (or the method's name, if
12 | * none was provided) which returns the value returned by the annotated method.
13 | */
14 | public class GaugeInjectionListener implements InjectionListener {
15 | private final MetricRegistry metricRegistry;
16 | private final MetricName metricName;
17 | private final Method method;
18 |
19 | public GaugeInjectionListener(MetricRegistry metricRegistry, MetricName metricName, Method method) {
20 | this.metricRegistry = metricRegistry;
21 | this.metricName = metricName;
22 | this.method = method;
23 | }
24 |
25 | @Override
26 | public void afterInjection(final I i) {
27 | metricRegistry.register(metricName, (Gauge