repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Snapshot.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Snapshot.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
import java.io.OutputStream;
/**
* A statistical snapshot of a {@link Snapshot}.
*/
public interface Snapshot {
/**
* Returns the value at the given quantile.
*
* @param quantile a given quantile, in {@code [0..1]}
* @return the value in the distribution at {@code quantile}
*/
double getValue(double quantile);
/**
* Returns the entire set of values in the snapshot.
*
* @return the entire set of values
*/
long[] getValues();
/**
* Returns the number of values in the snapshot.
*
* @return the number of values
*/
int size();
/**
* Returns the median value in the distribution.
*
* @return the median value
*/
default double getMedian() {
return getValue(0.5);
}
/**
* Returns the value at the 75th percentile in the distribution.
*
* @return the value at the 75th percentile
*/
default double get75thPercentile() {
return getValue(0.75);
}
/**
* Returns the value at the 95th percentile in the distribution.
*
* @return the value at the 95th percentile
*/
default double get95thPercentile() {
return getValue(0.95);
}
/**
* Returns the value at the 98th percentile in the distribution.
*
* @return the value at the 98th percentile
*/
default double get98thPercentile() {
return getValue(0.98);
}
/**
* Returns the value at the 99th percentile in the distribution.
*
* @return the value at the 99th percentile
*/
default double get99thPercentile() {
return getValue(0.99);
}
/**
* Returns the value at the 99.9th percentile in the distribution.
*
* @return the value at the 99.9th percentile
*/
default double get999thPercentile() {
return getValue(0.999);
}
/**
* Returns the highest value in the snapshot.
*
* @return the highest value
*/
long getMax();
/**
* Returns the arithmetic mean of the values in the snapshot.
*
* @return the arithmetic mean
*/
double getMean();
/**
* Returns the lowest value in the snapshot.
*
* @return the lowest value
*/
long getMin();
/**
* Returns the standard deviation of the values in the snapshot.
*
* @return the standard value
*/
double getStdDev();
/**
* Writes the values of the snapshot to the given stream.
*
* @param output an output stream
*/
void dump(OutputStream output);
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Metered.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Metered.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
/**
* An object which maintains mean and moving average rates.
*/
public interface Metered extends Metric, Counting {
/**
* Returns the fifteen-minute moving average rate at which events have
* occurred since the meter was created.
*
* @return the fifteen-minute moving average rate at which events have
* occurred since the meter was created
*/
double getFifteenMinuteRate();
/**
* Returns the five-minute moving average rate at which events have
* occurred since the meter was created.
*
* @return the five-minute moving average rate at which events have
* occurred since the meter was created
*/
double getFiveMinuteRate();
/**
* Returns the mean rate at which events have occurred since the meter was created.
*
* @return the mean rate at which events have occurred since the meter was created
*/
double getMeanRate();
/**
* Returns the one-minute moving average rate at which events have
* occurred since the meter was created.
*
* @return the one-minute moving average rate at which events have
* occurred since the meter was created
*/
double getOneMinuteRate();
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Meter.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Meter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
/**
* A meter metric which measures mean throughput and one-, five-, and fifteen-minute
* moving average throughputs.
*/
public interface Meter extends Metered {
/**
* Mark the occurrence of a given number of events.
*
* @param n the number of events
*/
void mark(long n);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Counter.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Counter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
/**
* An incrementing and decrementing counter metric.
*/
public interface Counter extends Metric, Counting {
/**
* Increment the counter by {@code n}.
*
* @param n the amount by which the counter will be increased
*/
void inc(long n);
/**
* Decrement the counter by {@code n}.
*
* @param n the amount by which the counter will be decreased
*/
default void dec(final long n) {
inc(-n);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Sampling.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Sampling.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
/**
* An object which samples values.
*/
public interface Sampling {
/**
* Returns a snapshot of the values.
*
* @return a snapshot of the values
*/
Snapshot getSnapshot();
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Gauge.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Gauge.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
public interface Gauge<T> extends Metric {
/**
* Returns the metric's current value.
*
* @return the metric's current value
*/
T getValue();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/Histogram.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/Histogram.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api;
/**
* A metric which calculates the distribution of a value.
*/
public interface Histogram extends Metric, Sampling, Counting {
/**
* Adds a recorded value.
*
* @param value the length of the value
*/
void update(long value);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Timed.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Timed.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for marking a method of an annotated object as timed.
* <p>
* Given a method like this:
* <pre><code>
* {@literal @}Timed(name = "fancyName")
* public String fancyName(String name) {
* return "Sir Captain " + name;
* }
* </code></pre>
* <p>
* A timer for the defining class with the name {@code fancyName} will be created and each time the
* {@code #fancyName(String)} method is invoked, the method's execution will be timed.
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Timed {
/**
* @return The name of the timer.
*/
String name() default "";
/**
* @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name
* relative to the annotated class. When annotating a class, this must be {@code false}.
*/
boolean absolute() default false;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/ExceptionMetered.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/ExceptionMetered.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for marking a method of an annotated object as metered.
* <p>
* Given a method like this:
* <pre><code>
* {@literal @}ExceptionMetered(name = "fancyName", cause=IllegalArgumentException.class)
* public String fancyName(String name) {
* return "Sir Captain " + name;
* }
* </code></pre>
* <p>
* A meter for the defining class with the name {@code fancyName} will be created and each time the
* {@code #fancyName(String)} throws an exception of type {@code cause} (or a subclass), the meter
* will be marked.
* <p>
* A name for the metric can be specified as an annotation parameter, otherwise, the metric will be
* named based on the method name.
* <p>
* For instance, given a declaration of
* <pre><code>
* {@literal @}ExceptionMetered
* public String fancyName(String name) {
* return "Sir Captain " + name;
* }
* </code></pre>
* <p>
* A meter named {@code fancyName.exceptions} will be created and marked every time an exception is
* thrown.
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface ExceptionMetered {
/**
* The default suffix for meter names.
*/
String DEFAULT_NAME_SUFFIX = "exceptions";
/**
* @return The name of the meter. If not specified, the meter will be given a name based on the method
* it decorates and the suffix "Exceptions".
*/
String name() default "";
/**
* @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name
* relative to the annotated class. When annotating a class, this must be {@code false}.
*/
boolean absolute() default false;
/**
* @return The type of exceptions that the meter will catch and count.
*/
Class<? extends Throwable> cause() default Exception.class;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Metered.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Metered.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for marking a method of an annotated object as metered.
* <p>
* Given a method like this:
* <pre><code>
* {@literal @}Metered(name = "fancyName")
* public String fancyName(String name) {
* return "Sir Captain " + name;
* }
* </code></pre>
* <p>
* A meter for the defining class with the name {@code fancyName} will be created and each time the
* {@code #fancyName(String)} method is invoked, the meter will be marked.
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Metered {
/**
* @return The name of the meter.
*/
String name() default "";
/**
* @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name
* relative to the annotated class. When annotating a class, this must be {@code false}.
*/
boolean absolute() default false;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/MetricTag.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/MetricTag.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.PARAMETER;
/**
* This annotation can be used to add tags to your resource metrics based on the value of parameters
* passed into the resource action.
* <code>
*
* @TimedResource public Response create(@MetricTag(tag = "type") String type)
* @TimedResource public Response create(@MetricTag(tag = "type", property="paymentType") Payment type)
* </code>
* @see TimedResource
*/
@Target(PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface MetricTag {
/**
* Name of the tag.
*/
String tag();
/**
* Optional property name from which the value of tag will be extracted
*/
String property() default "";
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/TimedResource.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/TimedResource.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.killbill.commons.metrics.api.annotation.MetricTag;
/**
* An annotation for marking a JAX-RS resource method of a Guice-provided object as timed.
* <p/>
* Given a method like this:
* <code><pre>
* @TimedResource(name = "fancyName")
* public Response create() {
* return "Sir Captain " + name;
* }
* </pre></code>
* <p/>
* A timer metric will be created for each response code returned by the method during runtime. Metrics will also be
* grouped be the response code (2xx, 3xx, etc). Both rate and latency metrics will be provided.
* <p/>
* The generated metric name uses the provided name in the annotation or the method name, if the latter is omitted:
* <pre>
* kb_resource./payments.fancyName.2xx.200
* kb_resource./payments.fancyName.2xx.201
* </pre>
* Note that the metric naming is affected by other factors, like the resource Path annotation and the presence of
* MetricTag annotations in the method's parameters
*
* @see MetricTag
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimedResource {
/**
* The name of the timer. If not provided, the name of the method will be used.
*/
String name() default "";
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Gauge.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Gauge.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for marking a method of an annotated object as a gauge.
* <p>
* Given a method like this:
* <pre><code>
* {@literal @}Gauge(name = "queueSize")
* public int getQueueSize() {
* return queue.size;
* }
* </code></pre>
* <p>
* A gauge for the defining class with the name {@code queueSize} will be created which uses the
* annotated method's return value as its value.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface Gauge {
/**
* @return The gauge's name.
*/
String name() default "";
/**
* @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name
* relative to the annotated class.
*/
boolean absolute() default false;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Counted.java | metrics-api/src/main/java/org/killbill/commons/metrics/api/annotation/Counted.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.api.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for marking a method of an annotated object as counted.
*
* <p>
* Given a method like this:
* <pre><code>
* {@literal @}Counted(name = "fancyName")
* public String fancyName(String name) {
* return "Sir Captain " + name;
* }
* </code></pre>
* <p>
* A counter for the defining class with the name {@code fancyName} will be created and each time the
* {@code #fancyName(String)} method is invoked, the counter will be marked.
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Counted {
/**
* @return The name of the counter.
*/
String name() default "";
/**
* @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name
* relative to the annotated class. When annotating a class, this must be {@code false}.
*/
boolean absolute() default false;
/**
* @return If {@code false} (default), the counter is decremented when the annotated
* method returns, counting current invocations of the annotated method.
* If {@code true}, the counter increases monotonically, counting total
* invocations of the annotated method.
*/
boolean monotonic() default false;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/postgresql/src/test/java/org/killbill/commons/embeddeddb/postgresql/KillBillTestingPostgreSqlServer.java | embeddeddb/postgresql/src/test/java/org/killbill/commons/embeddeddb/postgresql/KillBillTestingPostgreSqlServer.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.postgresql;
import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Nullable;
import org.killbill.commons.utils.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.zonky.test.db.postgres.embedded.EmbeddedPostgres;
import static java.lang.String.format;
// Forked from https://github.com/airlift/testing-postgresql-server (as of 9.6.3-3)
// Added Java 6 support and ability to configure the port
class KillBillTestingPostgreSqlServer implements Closeable {
private static final Logger log = LoggerFactory.getLogger(KillBillTestingPostgreSqlServer.class);
private final String user;
private final String database;
private final int port;
private final EmbeddedPostgres server;
public KillBillTestingPostgreSqlServer(final String user, final String database) throws Exception {
this(user, null, database);
}
public KillBillTestingPostgreSqlServer(final String user, @Nullable final Integer portOrNull, final String database) throws Exception {
// Make sure the driver is registered
Class.forName("org.postgresql.Driver");
this.user = Preconditions.checkNotNull(user, "user is null");
this.database = Preconditions.checkNotNull(database, "database is null");
if (portOrNull == null) {
server = EmbeddedPostgres.builder().start();
} else {
server = EmbeddedPostgres.builder().setPort(portOrNull).start();
}
port = server.getPort();
Connection connection = null;
try {
connection = server.getPostgresDatabase().getConnection();
Statement statement = null;
try {
statement = connection.createStatement();
execute(statement, format("CREATE ROLE %s WITH LOGIN SUPERUSER", user));
execute(statement, format("CREATE DATABASE %s OWNER %s ENCODING = 'utf8'", database, user));
} finally {
if (statement != null) {
statement.close();
}
}
} catch (final Exception e) {
if (connection != null) {
connection.close();
}
server.close();
throw e;
}
log.info("PostgreSQL server ready: {}", getJdbcUrl());
}
private static void execute(final Statement statement, final String sql) throws SQLException {
log.debug("Executing: {}", sql);
statement.execute(sql);
}
@Override
public void close() throws IOException {
server.close();
}
public String getUser() {
return user;
}
public String getDatabase() {
return database;
}
public int getPort() {
return port;
}
public String getJdbcUrl() {
return server.getJdbcUrl(user, database);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/postgresql/src/test/java/org/killbill/commons/embeddeddb/postgresql/PostgreSQLEmbeddedDB.java | embeddeddb/postgresql/src/test/java/org/killbill/commons/embeddeddb/postgresql/PostgreSQLEmbeddedDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.postgresql;
import org.killbill.commons.embeddeddb.EmbeddedDB;
import org.postgresql.ds.PGSimpleDataSource;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
public class PostgreSQLEmbeddedDB extends EmbeddedDB {
protected final AtomicBoolean started = new AtomicBoolean(false);
protected final int port;
private KillBillTestingPostgreSqlServer testingPostgreSqlServer;
public PostgreSQLEmbeddedDB() {
// Avoid dashes - PostgreSQL doesn't like them
this("database" + UUID.randomUUID().toString().substring(0, 8),
"user" + UUID.randomUUID().toString().substring(0, 8));
}
public PostgreSQLEmbeddedDB(final String databaseName, final String username) {
super(databaseName, username, null, null);
this.port = getPort();
this.jdbcConnectionString = String.format("jdbc:postgresql://localhost:%s/%s?user=%s", port, databaseName, username);
}
@Override
public DBEngine getDBEngine() {
return DBEngine.POSTGRESQL;
}
@Override
public void initialize() throws IOException {
}
@Override
public void start() throws IOException {
if (started.get()) {
throw new IOException("PostgreSQL is already running: " + jdbcConnectionString);
}
startPostgreSql();
createDataSource();
refreshTableNames();
}
@Override
public void refreshTableNames() throws IOException {
final String query = "select table_name from information_schema.tables where table_schema = current_schema() and table_type = 'BASE TABLE';";
try {
executeQuery(query, new ResultSetJob() {
@Override
public void work(final ResultSet resultSet) throws SQLException {
allTables.clear();
while (resultSet.next()) {
allTables.add(resultSet.getString(1));
}
}
});
} catch (final SQLException e) {
throw new IOException(e);
}
}
@Override
public DataSource getDataSource() throws IOException {
if (!started.get()) {
throw new IOException("PostgreSQL is not running");
}
return super.getDataSource();
}
@Override
public void stop() throws IOException {
if (!started.get()) {
throw new IOException("PostgreSQL is not running");
}
super.stop();
stopPostgreSql();
}
@Override
public String getCmdLineConnectionString() {
return String.format("psql -U%s -p%s %s", username, port, databaseName);
}
protected void createDataSource() throws IOException {
if (useConnectionPooling()) {
dataSource = createHikariDataSource();
} else {
final PGSimpleDataSource pgSimpleDataSource = new PGSimpleDataSource();
pgSimpleDataSource.setDatabaseName(databaseName);
pgSimpleDataSource.setUser(username);
pgSimpleDataSource.setUrl(jdbcConnectionString);
dataSource = pgSimpleDataSource;
}
}
private void startPostgreSql() throws IOException {
try {
this.testingPostgreSqlServer = new KillBillTestingPostgreSqlServer(username, port, databaseName);
} catch (final Exception e) {
throw new IOException(e);
}
started.set(true);
logger.info("PostgreSQL started: " + getCmdLineConnectionString());
}
private void stopPostgreSql() throws IOException {
if (testingPostgreSqlServer != null) {
testingPostgreSqlServer.close();
started.set(false);
logger.info("PostgreSQL stopped: " + getCmdLineConnectionString());
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/postgresql/src/main/java/org/killbill/commons/embeddeddb/postgresql/PostgreSQLStandaloneDB.java | embeddeddb/postgresql/src/main/java/org/killbill/commons/embeddeddb/postgresql/PostgreSQLStandaloneDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.postgresql;
import java.io.IOException;
import java.net.URI;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.killbill.commons.embeddeddb.GenericStandaloneDB;
import org.postgresql.ds.PGSimpleDataSource;
/**
* Delegates to a real PostgreSQL database. This can be used for debugging.
*/
public class PostgreSQLStandaloneDB extends GenericStandaloneDB {
private final int port;
public PostgreSQLStandaloneDB(final String databaseName, final String username, final String password) {
this(databaseName, username, password, "jdbc:postgresql://localhost:5432/" + databaseName);
}
public PostgreSQLStandaloneDB(final String databaseName, final String username, final String password, final String jdbcConnectionString) {
super(databaseName, username, password, jdbcConnectionString);
this.port = URI.create(jdbcConnectionString.substring(5)).getPort();
}
@Override
public DBEngine getDBEngine() {
return DBEngine.POSTGRESQL;
}
@Override
public void initialize() throws IOException, SQLException {
super.initialize();
dataSource = new PGSimpleDataSource();
((PGSimpleDataSource) dataSource).setDatabaseName(databaseName);
((PGSimpleDataSource) dataSource).setUser(username);
((PGSimpleDataSource) dataSource).setPassword(password);
((PGSimpleDataSource) dataSource).setUrl(jdbcConnectionString);
}
@Override
public void refreshTableNames() throws IOException {
final String query = "select table_name from information_schema.tables where table_schema = current_schema() and table_type = 'BASE TABLE';";
try {
executeQuery(query, new ResultSetJob() {
@Override
public void work(final ResultSet resultSet) throws SQLException {
allTables.clear();
while (resultSet.next()) {
allTables.add(resultSet.getString(1));
}
}
});
} catch (final SQLException e) {
throw new IOException(e);
}
}
@Override
public String getCmdLineConnectionString() {
return String.format("PGPASSWORD=%s psql -U%s -p%s %s", password, username, port, databaseName);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/h2/src/main/java/org/killbill/commons/embeddeddb/h2/H2EmbeddedDB.java | embeddeddb/h2/src/main/java/org/killbill/commons/embeddeddb/h2/H2EmbeddedDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.h2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import org.h2.api.ErrorCode;
import org.h2.jdbcx.JdbcConnectionPool;
import org.h2.tools.Server;
import org.killbill.commons.embeddeddb.EmbeddedDB;
public class H2EmbeddedDB extends EmbeddedDB {
private final AtomicBoolean started = new AtomicBoolean(false);
private Server server;
static {
try {
Class.forName("org.h2.Driver");
} catch (final ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public H2EmbeddedDB() {
this(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
}
public H2EmbeddedDB(final String databaseName, final String username, final String password) {
// Use LEGACY compatibility mode to support the SERIAL data type and to allow comparison between numeric and boolean values
this(databaseName, username, password, "jdbc:h2:mem:" + databaseName + ";MODE=LEGACY;DB_CLOSE_DELAY=-1");
}
public H2EmbeddedDB(final String databaseName, final String username, final String password, final String jdbcConnectionString) {
super(databaseName, username, password, jdbcConnectionString);
}
@Override
public DBEngine getDBEngine() {
return DBEngine.H2;
}
@Override
public void initialize() throws IOException {
}
@Override
public void start() throws IOException {
if (started.get()) {
throw new IOException("H2 is already running: " + jdbcConnectionString);
}
createDataSource();
try {
// Start a web server for debugging (http://127.0.0.1:8082/)
server = Server.createWebServer().start();
logger.info(String.format("H2 started on http://127.0.0.1:8082. JDBC=%s, Username=%s, Password=%s",
getJdbcConnectionString(), getUsername(), getPassword()));
} catch (final SQLException e) {
// H2 most likely already started (e.g. by a different pool) -- ignore
// Note: we still want the EmbeddedDB object to be started, for a clean shutdown of the dataSource
if (!String.valueOf(ErrorCode.EXCEPTION_OPENING_PORT_2).equals(e.getSQLState())) {
throw new IOException(e);
}
}
started.set(true);
refreshTableNames();
}
@Override
public void refreshTableNames() throws IOException {
final String query = "select table_name from information_schema.tables where table_schema = current_schema() and table_type = 'BASE TABLE';";
try {
executeQuery(query, new ResultSetJob() {
@Override
public void work(final ResultSet resultSet) throws SQLException {
allTables.clear();
while (resultSet.next()) {
allTables.add(resultSet.getString(1));
}
}
});
} catch (final SQLException e) {
throw new IOException(e);
}
}
protected void createDataSource() throws IOException {
if (useConnectionPooling()) {
dataSource = createHikariDataSource();
} else {
final JdbcConnectionPool jdbcConnectionPool = JdbcConnectionPool.create(jdbcConnectionString, username, password);
// Default is 10, set it to 30 to match the default for org.killbill.dao.maxActive.
// set to 100 temporarily to temporarily solve CI problem: https://github.com/killbill/killbill/issues/1799
jdbcConnectionPool.setMaxConnections(100);
dataSource = jdbcConnectionPool;
}
}
@Override
public DataSource getDataSource() throws IOException {
if (!started.get()) {
throw new IOException("H2 is not running");
}
return super.getDataSource();
}
@Override
public void stop() throws IOException {
if (!started.get()) {
throw new IOException("H2 is not running");
}
// Close the database pool ASAP to make sure the database is never re-opened by background threads
super.stop();
try (final Connection connection = DriverManager.getConnection(jdbcConnectionString, username, password);
final Statement statement = connection.createStatement()) {
statement.execute("SHUTDOWN");
} catch (final Exception e) {
logger.warn("Exception while trying to shutdown H2", e);
}
if (dataSource instanceof JdbcConnectionPool) {
((JdbcConnectionPool) dataSource).dispose();
}
if (server != null) {
server.stop();
server = null;
}
started.set(false);
logger.info(String.format("H2 stopped on http://127.0.0.1:8082. JDBC=%s, Username=%s, Password=%s",
getJdbcConnectionString(), getUsername(), getPassword()));
}
@Override
public String getCmdLineConnectionString() {
return "open " + server.getURL();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/mysql/src/test/java/org/killbill/commons/embeddeddb/mysql/MySQLEmbeddedDB.java | embeddeddb/mysql/src/test/java/org/killbill/commons/embeddeddb/mysql/MySQLEmbeddedDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.mysql;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import org.killbill.commons.embeddeddb.EmbeddedDB;
import org.killbill.commons.utils.Preconditions;
import org.killbill.testing.mysql.MySqlServerOptions;
import org.killbill.testing.mysql.TestingMySqlServer;
import org.mariadb.jdbc.MariaDbDataSource;
public class MySQLEmbeddedDB extends EmbeddedDB {
private final MySqlServerOptions options;
private TestingMySqlServer mysqldResource;
protected final AtomicBoolean started = new AtomicBoolean(false);
public MySQLEmbeddedDB() {
// Avoid dashes - MySQL doesn't like them
this("mydb_" + UUID.randomUUID().toString().substring(0, 8),
"myuser_" + UUID.randomUUID().toString().substring(0, 8),
"mypass_" + UUID.randomUUID().toString().substring(0, 8));
}
public MySQLEmbeddedDB(final String databaseName, final String username, final String password) {
super(databaseName, username, password, null);
options = MySqlServerOptions.builder(databaseName)
.setUsername(username)
.setPassword(password)
.build();
// jdbcConnectionString required to set here in constructor, before #start() method. This is because some
// clients (like TestKillbillConfigSource along with PlatformDBTestingHelper in killbill-platform) need to get
// jdbcConnectionString value. For MySQL PlatformDBTestingHelper#getInstance() will return this instance, and if
// jdbcConnectionString not set here, it will `null` and causing DaoConfig's default value take place.
jdbcConnectionString = options.getJdbcUrl(databaseName);
}
@Override
public DBEngine getDBEngine() {
return DBEngine.MYSQL;
}
@Override
public void initialize() throws IOException {
}
@Override
public void start() throws IOException, SQLException {
if (started.get()) {
throw new IOException("MySQL is already running: " + jdbcConnectionString);
}
try {
mysqldResource = new TestingMySqlServer(options);
started.set(true);
logger.info("MySQL started: {}", getCmdLineConnectionString());
} catch (final Exception e) {
throw new IOException(e);
}
createDataSource();
refreshTableNames();
}
@Override
public void refreshTableNames() throws IOException {
final String query = String.format("select table_name from information_schema.tables where table_schema = '%s' and table_type = 'BASE TABLE';", databaseName);
try {
executeQuery(query, new ResultSetJob() {
@Override
public void work(final ResultSet resultSet) throws SQLException {
allTables.clear();
while (resultSet.next()) {
allTables.add(resultSet.getString(1));
}
}
});
} catch (final SQLException e) {
throw new IOException(e);
}
}
@Override
public DataSource getDataSource() throws IOException {
if (!started.get()) {
throw new IOException("MySQL is not running");
}
return super.getDataSource();
}
@Override
public void stop() throws IOException {
if (!started.get()) {
throw new IOException("MySQL is not running");
}
super.stop();
stopMysql();
}
@Override
public String getCmdLineConnectionString() {
Preconditions.checkState(started.get(), "MySQL isn't running");
Preconditions.checkNotNull(mysqldResource);
return String.format("mysql -u%s -p%s -P%s -S%s/mysql.sock %s", username, password, options.getPort(), mysqldResource.getServerDirectory(), databaseName);
}
protected void createDataSource() throws IOException, SQLException {
Preconditions.checkState(started.get(), "MySQL isn't running");
if (useConnectionPooling()) {
dataSource = createHikariDataSource();
} else {
final MariaDbDataSource mariaDBDataSource = new MariaDbDataSource();
try {
mariaDBDataSource.setUrl(jdbcConnectionString);
} catch (final SQLException e) {
throw new IOException(e);
}
mariaDBDataSource.setUser(username);
mariaDBDataSource.setPassword(password);
dataSource = mariaDBDataSource;
}
}
private void stopMysql() {
if (mysqldResource != null) {
try {
mysqldResource.close();
} catch (final NullPointerException npe) {
logger.warn("Failed to shutdown mysql properly ", npe);
}
started.set(false);
logger.info("MySQL stopped");
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/mysql/src/test/java/org/killbill/commons/embeddeddb/mysql/TestKillBillMariaDbDataSource.java | embeddeddb/mysql/src/test/java/org/killbill/commons/embeddeddb/mysql/TestKillBillMariaDbDataSource.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.mysql;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestKillBillMariaDbDataSource {
@Test(groups = "fast")
public void testUpdateUrl() throws Exception {
final KillBillMariaDbDataSource killBillMariaDbDataSource = new KillBillMariaDbDataSource();
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill?createDatabaseIfNotExist=true&allowMultiQueries=true&cachePrepStmts=false"),
"jdbc:mysql://127.0.0.1:3306/killbill?allowMultiQueries=true&cachePrepStmts=false&createDatabaseIfNotExist=true&permitMysqlScheme=true");
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill"),
"jdbc:mysql://127.0.0.1:3306/killbill?permitMysqlScheme=true");
killBillMariaDbDataSource.setCachePrepStmts(false);
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill?createDatabaseIfNotExist=true&allowMultiQueries=true&cachePrepStmts=false"),
"jdbc:mysql://127.0.0.1:3306/killbill?allowMultiQueries=true&cachePrepStmts=false&createDatabaseIfNotExist=true&permitMysqlScheme=true");
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill"),
"jdbc:mysql://127.0.0.1:3306/killbill?cachePrepStmts=false&permitMysqlScheme=true");
killBillMariaDbDataSource.setCachePrepStmts(true);
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill?createDatabaseIfNotExist=true&allowMultiQueries=true&cachePrepStmts=false"),
"jdbc:mysql://127.0.0.1:3306/killbill?allowMultiQueries=true&cachePrepStmts=false&createDatabaseIfNotExist=true&permitMysqlScheme=true");
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill"),
"jdbc:mysql://127.0.0.1:3306/killbill?cachePrepStmts=true&permitMysqlScheme=true");
killBillMariaDbDataSource.setPrepStmtCacheSize(123);
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill?createDatabaseIfNotExist=true&allowMultiQueries=true&cachePrepStmts=false"),
"jdbc:mysql://127.0.0.1:3306/killbill?allowMultiQueries=true&cachePrepStmts=false&createDatabaseIfNotExist=true&permitMysqlScheme=true&prepStmtCacheSize=123");
Assert.assertEquals(killBillMariaDbDataSource.buildUpdatedUrl("jdbc:mysql://127.0.0.1:3306/killbill"),
"jdbc:mysql://127.0.0.1:3306/killbill?cachePrepStmts=true&permitMysqlScheme=true&prepStmtCacheSize=123");
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/mysql/src/test/java/org/killbill/commons/embeddeddb/mysql/TestMySqlEmbeddedDB.java | embeddeddb/mysql/src/test/java/org/killbill/commons/embeddeddb/mysql/TestMySqlEmbeddedDB.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.mysql;
import java.io.IOException;
import java.sql.SQLException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Make sure that {@link MySQLEmbeddedDB} actually works, before running in other modules and lead to confusion.
*/
public class TestMySqlEmbeddedDB {
private MySQLEmbeddedDB embeddedDB;
@BeforeMethod(groups = "slow", alwaysRun = true)
public void beforeMethod() {
embeddedDB = new MySQLEmbeddedDB("killbill", "root", "");
}
@AfterMethod(groups = "slow", alwaysRun = true)
public void afterMethod() throws IOException {
if (embeddedDB != null) {
embeddedDB.stop();
}
}
@Test(groups = "slow")
public void testStart() throws SQLException, IOException {
embeddedDB.start();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/mysql/src/main/java/org/killbill/commons/embeddeddb/mysql/MySQLStandaloneDB.java | embeddeddb/mysql/src/main/java/org/killbill/commons/embeddeddb/mysql/MySQLStandaloneDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.mysql;
import java.io.IOException;
import java.net.URI;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.killbill.commons.embeddeddb.GenericStandaloneDB;
import com.mysql.cj.jdbc.MysqlDataSource;
/**
* Delegates to a real MySQL database. This can be used for debugging.
*/
public class MySQLStandaloneDB extends GenericStandaloneDB {
private final int port;
private final boolean useMariaDB;
public MySQLStandaloneDB(final String databaseName) {
this(databaseName, "root", null);
}
public MySQLStandaloneDB(final String databaseName, final String username, final String password) {
this(databaseName, username, password, "jdbc:mysql://localhost:3306/" + databaseName + "?createDatabaseIfNotExist=true&allowMultiQueries=true");
}
public MySQLStandaloneDB(final String databaseName, final String username, final String password, final String jdbcConnectionString) {
this(databaseName, username, password, jdbcConnectionString, true);
}
public MySQLStandaloneDB(final String databaseName, final String username, final String password, final String jdbcConnectionString, final boolean useMariaDB) {
super(databaseName, username, password, jdbcConnectionString);
this.port = URI.create(jdbcConnectionString.substring(5)).getPort();
this.useMariaDB = useMariaDB;
}
@Override
public DBEngine getDBEngine() {
return DBEngine.MYSQL;
}
@Override
public void initialize() throws IOException, SQLException {
super.initialize();
if (useMariaDB) {
final KillBillMariaDbDataSource mariaDBDataSource = new KillBillMariaDbDataSource();
try {
mariaDBDataSource.setUrl(jdbcConnectionString);
} catch (final SQLException e) {
throw new IOException(e);
}
mariaDBDataSource.setUser(username);
mariaDBDataSource.setPassword(password);
dataSource = mariaDBDataSource;
} else {
final MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setDatabaseName(databaseName);
mysqlDataSource.setUser(username);
mysqlDataSource.setPassword(password);
mysqlDataSource.setPort(port);
// See http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
mysqlDataSource.setURL(jdbcConnectionString);
dataSource = mysqlDataSource;
}
}
@Override
public void refreshTableNames() throws IOException {
final String query = String.format("select table_name from information_schema.tables where table_schema = '%s' and table_type = 'BASE TABLE';", databaseName);
try {
executeQuery(query, new ResultSetJob() {
@Override
public void work(final ResultSet resultSet) throws SQLException {
allTables.clear();
while (resultSet.next()) {
allTables.add(resultSet.getString(1));
}
}
});
} catch (final SQLException e) {
throw new IOException(e);
}
}
@Override
public String getCmdLineConnectionString() {
return String.format("mysql -u%s -p%s -P%s %s", username, password, port, databaseName);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/mysql/src/main/java/org/killbill/commons/embeddeddb/mysql/KillBillMariaDbDataSource.java | embeddeddb/mysql/src/main/java/org/killbill/commons/embeddeddb/mysql/KillBillMariaDbDataSource.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb.mysql;
import java.sql.SQLException;
import java.util.Properties;
import java.util.TreeMap;
import org.killbill.commons.utils.MapJoiner;
import org.killbill.commons.utils.annotation.VisibleForTesting;
import org.mariadb.jdbc.Configuration;
import org.mariadb.jdbc.MariaDbDataSource;
public class KillBillMariaDbDataSource extends MariaDbDataSource {
private static final MapJoiner mapJoiner = new MapJoiner("=", "&");
private String url;
private Boolean cachePrepStmts;
private Integer prepStmtCacheSize;
private Integer prepStmtCacheSqlLimit;
private Boolean useServerPrepStmts;
@Override
public void setUrl(final String url) throws SQLException {
this.url = url;
// If called by PropertyElf.setTargetFromProperties (HikariCP), we need to take into account our extra properties
updateUrlIfNeeded(); // will call super()
}
// See HikariDataSourceBuilder and https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
public void setCachePrepStmts(final boolean cachePrepStmts) throws SQLException {
this.cachePrepStmts = cachePrepStmts;
updateUrlIfNeeded();
}
public void setPrepStmtCacheSize(final int prepStmtCacheSize) throws SQLException {
this.prepStmtCacheSize = prepStmtCacheSize;
updateUrlIfNeeded();
}
public void setPrepStmtCacheSqlLimit(final int prepStmtCacheSqlLimit) throws SQLException {
this.prepStmtCacheSqlLimit = prepStmtCacheSqlLimit;
updateUrlIfNeeded();
}
// Note! New default is now false (was true before 1.6.0)
public void setUseServerPrepStmts(final boolean useServerPrepStmts) throws SQLException {
this.useServerPrepStmts = useServerPrepStmts;
updateUrlIfNeeded();
}
private void updateUrlIfNeeded() throws SQLException {
if (url != null) {
this.url = buildUpdatedUrl(this.url);
super.setUrl(url);
}
}
// No easy way to set MariaDB options at runtime besides updating the JDBC url
@VisibleForTesting
String buildUpdatedUrl(final String url) throws SQLException {
// See https://mariadb.com/kb/en/mariadb-connector-j-303-release-notes/
final Properties propertyWithPermitMysqlScheme = new Properties();
propertyWithPermitMysqlScheme.put("permitMysqlScheme", "true");
final String baseUrlWithPermitMysqlScheme = buildUpdatedUrl(url, propertyWithPermitMysqlScheme, true);
final Properties props = new Properties();
Configuration.parse(baseUrlWithPermitMysqlScheme, props);
if (cachePrepStmts != null && !props.containsKey("cachePrepStmts")) {
props.put("cachePrepStmts", cachePrepStmts);
}
if (prepStmtCacheSize != null && !props.containsKey("prepStmtCacheSize")) {
props.put("prepStmtCacheSize", prepStmtCacheSize);
}
if (prepStmtCacheSqlLimit != null && !props.containsKey("prepStmtCacheSqlLimit")) {
props.put("prepStmtCacheSqlLimit", prepStmtCacheSqlLimit);
}
if (useServerPrepStmts != null && !props.containsKey("useServerPrepStmts")) {
props.put("useServerPrepStmts", useServerPrepStmts);
}
return buildUpdatedUrl(url, props, false);
}
private String buildUpdatedUrl(final String url, final Properties props, final boolean append) {
if (props.isEmpty()) {
return url;
}
final int separator = url.indexOf("//");
final String urlSecondPart = url.substring(separator + 2);
final int paramIndex = urlSecondPart.indexOf("?");
// Note: the ordering (TreeMap) is mostly for tests, to ensure a predictable order regardless of the JDK
if (append) {
return url + (paramIndex > 0 ? "&" : "?") + mapJoiner.join(new TreeMap<>(props));
} else {
final String baseUrl = paramIndex > 0 ? url.substring(0, separator + 2 + paramIndex) : url;
return baseUrl + "?" + mapJoiner.join(new TreeMap<>(props));
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/common/src/main/java/org/killbill/commons/embeddeddb/GenericStandaloneDB.java | embeddeddb/common/src/main/java/org/killbill/commons/embeddeddb/GenericStandaloneDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb;
import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicBoolean;
public class GenericStandaloneDB extends EmbeddedDB {
protected final AtomicBoolean started = new AtomicBoolean(false);
public GenericStandaloneDB(final String databaseName, final String username, final String password, final String jdbcConnectionString) {
super(databaseName, username, password, jdbcConnectionString);
}
@Override
public DBEngine getDBEngine() {
return DBEngine.GENERIC;
}
@Override
public void initialize() throws IOException, SQLException {
}
@Override
public void start() throws IOException {
started.set(true);
refreshTableNames();
}
@Override
public void refreshTableNames() throws IOException {
}
@Override
public void stop() throws IOException {
started.set(false);
super.stop();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/embeddeddb/common/src/main/java/org/killbill/commons/embeddeddb/EmbeddedDB.java | embeddeddb/common/src/main/java/org/killbill/commons/embeddeddb/EmbeddedDB.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.embeddeddb;
import java.io.IOException;
import java.net.ServerSocket;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class EmbeddedDB {
protected static final Logger logger = LoggerFactory.getLogger(EmbeddedDB.class);
public enum DBEngine {
GENERIC,
MYSQL,
H2,
POSTGRESQL
}
// Not final to allow more flexible implementers
protected String databaseName;
protected String username;
protected String password;
protected String jdbcConnectionString;
protected DataSource dataSource;
protected List<String> allTables = new LinkedList<>();
protected EmbeddedDB(final String databaseName, final String username, final String password, final String jdbcConnectionString) {
this.databaseName = databaseName;
this.username = username;
this.password = password;
this.jdbcConnectionString = jdbcConnectionString;
}
public boolean useConnectionPooling() {
return Boolean .getBoolean("killbill.test.use.connection.pool");
}
public abstract DBEngine getDBEngine();
public abstract void initialize() throws IOException, SQLException;
public abstract void start() throws IOException, SQLException;
public abstract void refreshTableNames() throws IOException;
public DataSource getDataSource() throws IOException {
return dataSource;
}
// Delayed initialization for GenericStandaloneDB
public void setDataSource(final DataSource dataSource) {
this.dataSource = dataSource;
}
public void stop() throws IOException {
final DataSource dataSource = getDataSource();
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).close();
}
}
// Optional - for debugging, how to connect to it?
public String getCmdLineConnectionString() {
return null;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getDatabaseName() {
return databaseName;
}
public String getJdbcConnectionString() {
return jdbcConnectionString;
}
public List<String> getAllTables() {
return List.copyOf(allTables);
}
private static final Pattern WHITESPACE_ONLY = Pattern.compile("^\\s*$");
// Only used in tests (embedded versions)
protected DataSource createHikariDataSource() throws IOException {
final String dataSourceClassName;
switch(getDBEngine()) {
case MYSQL:
dataSourceClassName = "org.mariadb.jdbc.MariaDbDataSource";
break;
case POSTGRESQL:
dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource";
break;
case H2:
dataSourceClassName = "org.h2.jdbcx.JdbcDataSource";
break;
default:
dataSourceClassName = null;
break;
}
final HikariConfig hikariConfig = new HikariConfig();
if (username != null) {
hikariConfig.setUsername(username);
hikariConfig.addDataSourceProperty("user", username);
}
if (password != null) {
hikariConfig.setPassword(password);
hikariConfig.addDataSourceProperty("password", password);
}
if (jdbcConnectionString != null) {
hikariConfig.addDataSourceProperty("url", jdbcConnectionString);
}
hikariConfig.setMaximumPoolSize(100);
hikariConfig.setMinimumIdle(1);
hikariConfig.setConnectionTimeout(10 * 000);
hikariConfig.setIdleTimeout(60 * 1000 * 1000);
hikariConfig.setMaxLifetime(0);
hikariConfig.setDataSourceClassName(dataSourceClassName);
return new HikariDataSource(hikariConfig);
}
public void executeScript(final String script) throws IOException {
try {
execute(script);
} catch (final SQLException e) {
throw new IOException(e);
}
}
public void cleanupAllTables() throws IOException {
for (final String tableName : allTables) {
cleanupTable(tableName);
}
}
public void cleanupTable(final String table) throws IOException {
logger.debug("Deleting table: " + table);
try {
executeUpdate("truncate table " + table);
} catch (final SQLException e) {
throw new IOException(e);
}
}
protected void execute(final String query) throws SQLException, IOException {
execute(query, new ResultSetJob());
}
protected void execute(final String query, final ResultSetJob job) throws SQLException, IOException {
final Connection connection = getConnection();
Statement statement = null;
try {
statement = connection.createStatement();
if (statement.execute(query)) {
job.work(statement.getResultSet());
}
} finally {
if (statement != null) {
statement.close();
}
connection.close();
}
}
protected int executeUpdate(final String query) throws SQLException, IOException {
final Connection connection = getConnection();
Statement statement = null;
try {
statement = connection.createStatement();
return statement.executeUpdate(query);
} finally {
if (statement != null) {
statement.close();
}
connection.close();
}
}
protected void executeQuery(final String query, final ResultSetJob job) throws SQLException, IOException {
try (final Connection connection = getConnection();
final Statement statement = connection.createStatement();
final ResultSet rs = statement.executeQuery(query)) {
job.work(rs);
}
}
protected Connection getConnection() throws SQLException, IOException {
return getDataSource().getConnection();
}
protected static class ResultSetJob {
public void work(final ResultSet resultSet) throws SQLException {}
}
protected int getPort() {
// New socket on any free port
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
return socket.getLocalPort();
} catch (final IOException e) {
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (final IOException ignored) {
}
}
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithCounterParent.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithCounterParent.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Counted;
@SuppressWarnings("UnusedReturnValue")
class InstrumentedWithCounterParent {
@Counted(name = "counterParent", absolute = true)
String counterParent() {
return "counterParent";
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithGauge.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithGauge.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Gauge;
@SuppressWarnings("UnusedReturnValue")
class InstrumentedWithGauge extends InstrumentedWithGaugeParent {
@Gauge(name = "things")
String doAThing() {
return "poop";
}
@Gauge
String doAnotherThing() {
return "anotherThing";
}
@Gauge(name = "absoluteName", absolute = true)
String doAThingWithAbsoluteName() {
return "anotherThingWithAbsoluteName";
}
@Gauge(name = "gaugePrivate")
private String gaugePrivate() {
return "gaugePrivate";
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithExceptionMetered.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithExceptionMetered.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.ExceptionMetered;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
@SuppressWarnings("UnusedReturnValue")
class InstrumentedWithExceptionMetered {
@ExceptionMetered(name = "exceptionCounter")
String explodeWithPublicScope(final boolean explode) {
if (explode) {
throw new RuntimeException("Boom!");
} else {
return "calm";
}
}
@ExceptionMetered
String explodeForUnnamedMetric() {
throw new RuntimeException("Boom!");
}
@ExceptionMetered(name = "n")
String explodeForMetricWithName() {
throw new RuntimeException("Boom!");
}
@ExceptionMetered(name = "absoluteName", absolute = true)
String explodeForMetricWithAbsoluteName() {
throw new RuntimeException("Boom!");
}
@ExceptionMetered
String explodeWithDefaultScope() {
throw new RuntimeException("Boom!");
}
@ExceptionMetered
String explodeWithProtectedScope() {
throw new RuntimeException("Boom!");
}
@ExceptionMetered(name = "failures", cause = MyException.class)
void errorProneMethod(final RuntimeException e) {
throw e;
}
@ExceptionMetered(name = "things",
cause = ArrayIndexOutOfBoundsException.class)
Object causeAnOutOfBoundsException() {
@SuppressWarnings("MismatchedReadAndWriteOfArray") final Object[] arr = {};
//noinspection ConstantConditions
return arr[1];
}
@Timed
@ExceptionMetered
void timedAndException(final RuntimeException e) {
if (e != null) {
throw e;
}
}
@Metered
@ExceptionMetered
void meteredAndException(final RuntimeException e) {
if (e != null) {
throw e;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithTimed.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithTimed.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Timed;
@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"})
class InstrumentedWithTimed {
@Timed(name = "things")
public String doAThing() throws InterruptedException {
Thread.sleep(10);
return "poop";
}
@Timed
String doAThingWithDefaultScope() {
return "defaultResult";
}
@Timed
protected String doAThingWithProtectedScope() {
return "defaultProtected";
}
@Timed(name = "absoluteName", absolute = true)
protected String doAThingWithAbsoluteName() {
return "defaultProtected";
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/GenericThing.java | metrics/src/test/java/org/killbill/commons/metrics/guice/GenericThing.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
@SuppressWarnings("EmptyMethod")
class GenericThing<T> {
void doThing(final T t) {
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/CountInvocationGenericSubtypeTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/CountInvocationGenericSubtypeTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class CountInvocationGenericSubtypeTest {
private GenericThing<String> instance;
private MetricRegistry registry;
@BeforeMethod(groups = "fast")
void setup() {
this.registry = new NoOpMetricRegistry();
final Injector injector = Guice.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).build());
this.instance = injector.getInstance(StringThing.class);
}
@Test(groups = "fast")
void testCountsInvocationOfGenericOverride() {
instance.doThing("foo");
final Counter metric = registry.getCounters().get("stringThing");
assertNotNull(metric);
assertEquals(metric.getCount(), 1);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/MatcherTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/MatcherTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
public class MatcherTest {
private InstrumentedWithTimed timedInstance;
private InstrumentedWithMetered meteredInstance;
private MetricRegistry registry;
@BeforeMethod(groups = "fast")
void setup() {
this.registry = new NoOpMetricRegistry();
final Matcher<? super TypeLiteral<?>> matcher = new AbstractMatcher<TypeLiteral<?>>() {
@Override
public boolean matches(final TypeLiteral<?> typeLiteral) {
return InstrumentedWithMetered.class.isAssignableFrom(typeLiteral.getRawType());
}
};
final Injector injector = Guice.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).withMatcher(matcher).build());
this.timedInstance = injector.getInstance(InstrumentedWithTimed.class);
this.meteredInstance = injector.getInstance(InstrumentedWithMetered.class);
}
@Test(groups = "fast")
void aTimedAnnotatedMethod() throws Exception {
timedInstance.doAThing();
final Timer metric = registry.getTimers().get(String.format("%s.%s",
InstrumentedWithTimed.class.getName(),
"things"));
assertNull(metric);
}
@Test(groups = "fast")
void aMeteredAnnotatedMethod() {
meteredInstance.doAThing();
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithMetered.class.getName(),
"things"));
assertNotNull(metric);
assertEquals(metric.getCount(), 1L);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/CountedTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/CountedTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.COUNTER_SUFFIX;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.COUNTER_SUFFIX_MONOTONIC;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.AssertJUnit.assertEquals;
public class CountedTest {
private InstrumentedWithCounter instance;
private MetricRegistry registry;
@BeforeMethod(groups = "fast")
void setup() {
this.registry = new NoOpMetricRegistry();
final Injector injector = Guice.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).build());
this.instance = injector.getInstance(InstrumentedWithCounter.class);
}
@Test(groups = "fast")
void aCounterAnnotatedMethod() {
instance.doAThing();
final Counter metric = registry.getCounters().get(String.format("%s.%s", InstrumentedWithCounter.class.getName(), "things"));
assertNotNull(metric);
assertEquals(metric.getCount(), (long) 1);
}
@Test(groups = "fast")
void aCounterAnnotatedMethodWithDefaultName() {
instance.doAnotherThing();
final Counter metric = registry.getCounters().get(String.format("%s.%s.%s",
InstrumentedWithCounter.class.getName(),
"doAnotherThing",
COUNTER_SUFFIX_MONOTONIC));
assertNotNull(metric);
assertEquals(metric.getCount(), (long) 1);
}
@Test(groups = "fast")
void aCounterAnnotatedMethodWithDefaultNameAndMonotonicFalse() {
instance.doYetAnotherThing();
final Counter metric = registry.getCounters().get(String.format("%s.%s.%s",
InstrumentedWithCounter.class.getName(),
"doYetAnotherThing",
COUNTER_SUFFIX));
assertNotNull(metric);
// if things are working well then this should still be zero...
assertEquals(metric.getCount(), (long) 0);
}
@Test(groups = "fast")
void aCounterAnnotatedMethodWithAbsoluteName() {
instance.doAThingWithAbsoluteName();
final Counter metric = registry.getCounters().get("absoluteName");
assertNotNull(metric);
assertEquals(metric.getCount(), (long) 1);
}
/**
* Test to document the current (correct but regrettable) behavior.
* <p>
* Crawling the injected class's supertype hierarchy doesn't really accomplish anything because AOPing supertype
* methods doesn't work.
* <p>
* In certain cases (e.g. a public type that inherits a public method from a non-public supertype), a synthetic
* bridge method is generated in the subtype that invokes the supertype method, and this does copy the annotations
* of the supertype method. However, we can't allow intercepting synthetic bridge methods in general: when a subtype
* overrides a generic supertype's method with a more specifically typed method that would not override the
* type-erased supertype method, a bridge method matching the supertype's erased signature is generated, but with
* the subtype's method's annotation. It's not OK to intercept that synthetic method because that would lead to
* double-counting, etc, since we also would intercept the regular non-synthetic method.
* <p>
* Thus, we cannot intercept synthetic methods to maintain correctness, so we also lose out on one small way that we
* could intercept annotated methods in superclasses.
*/
@Test(groups = "fast")
void aCounterForSuperclassMethod() {
instance.counterParent();
final Counter metric = registry.getCounters().get("counterParent");
// won't be created because we don't bother looking for supertype methods
assertNull(metric);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/MeteredTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/MeteredTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.METERED_SUFFIX;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class MeteredTest {
private InstrumentedWithMetered instance;
private MetricRegistry registry;
@BeforeMethod(groups = "fast")
void setup() {
this.registry = new NoOpMetricRegistry();
final Injector injector =
Guice.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).build());
this.instance = injector.getInstance(InstrumentedWithMetered.class);
}
@Test(groups = "fast")
void aMeteredAnnotatedMethod() {
instance.doAThing();
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithMetered.class.getName(),
"things"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void aMeteredAnnotatedMethodWithDefaultScope() {
final Meter metric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithMetered.class.getName(),
"doAThingWithDefaultScope",
METERED_SUFFIX));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
instance.doAThingWithDefaultScope();
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void aMeteredAnnotatedMethodWithProtectedScope() {
final Meter metric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithMetered.class.getName(),
"doAThingWithProtectedScope",
METERED_SUFFIX));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
instance.doAThingWithProtectedScope();
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void aMeteredAnnotatedMethodWithName() {
final Meter metric = registry.getMeters().get(String.format("%s.%s", InstrumentedWithMetered.class.getName(), "n"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
instance.doAThingWithName();
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void aMeteredAnnotatedMethodWithAbsoluteName() {
final Meter metric = registry.getMeters().get("nameAbs");
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
instance.doAThingWithAbsoluteName();
assertEquals(metric.getCount(), 1L);
}
private void assertMetricIsSetup(final Meter metric) {
assertNotNull(metric);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithMetered.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithMetered.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Metered;
@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"})
class InstrumentedWithMetered {
@Metered(name = "things")
public String doAThing() {
return "poop";
}
@Metered
String doAThingWithDefaultScope() {
return "defaultResult";
}
@Metered
protected String doAThingWithProtectedScope() {
return "defaultProtected";
}
@Metered(name = "n")
protected String doAThingWithName() {
return "withName";
}
@Metered(name = "nameAbs", absolute = true)
protected String doAThingWithAbsoluteName() {
return "absoluteName";
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/StringThing.java | metrics/src/test/java/org/killbill/commons/metrics/guice/StringThing.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Counted;
class StringThing extends GenericThing<String> {
@Override
@Counted(name = "stringThing", absolute = true, monotonic = true)
void doThing(final String s) {
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/GaugeInheritanceTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/GaugeInheritanceTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.Gauge;
import org.killbill.commons.metrics.guice.DeclaringClassMetricNamer;
import org.killbill.commons.metrics.guice.MetricsInstrumentationModule;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.testng.Assert.assertEquals;
public class GaugeInheritanceTest {
@Test(groups = "fast")
void testInheritance() {
final MetricRegistry registry = new NoOpMetricRegistry();
final Injector injector = Guice
.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).build());
injector.getInstance(Parent.class);
injector.getInstance(Child1.class);
injector.getInstance(Child2.class);
// gauge in parent class is registered separately for each
assertEquals(registry.getGauges().get(String.format("%s.%s.%s", Parent.class.getName(), "aGauge", DeclaringClassMetricNamer.GAUGE_SUFFIX))
.getValue(),
0);
assertEquals(registry.getGauges().get(String.format("%s.%s.%s", Child1.class.getName(), "aGauge", DeclaringClassMetricNamer.GAUGE_SUFFIX))
.getValue(),
1);
assertEquals(registry.getGauges().get(String.format("%s.%s.%s", Child2.class.getName(), "aGauge", DeclaringClassMetricNamer.GAUGE_SUFFIX))
.getValue(),
2);
}
static class Parent {
@Gauge
int aGauge() {
return complexInternalCalculation();
}
int complexInternalCalculation() {
return 0;
}
}
static class Child1 extends Parent {
@Override
int complexInternalCalculation() {
return 1;
}
}
static class Child2 extends Parent {
@Override
int complexInternalCalculation() {
return 2;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/ExceptionMeteredTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/ExceptionMeteredTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.METERED_SUFFIX;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.TIMED_SUFFIX;
import static org.killbill.commons.metrics.api.annotation.ExceptionMetered.DEFAULT_NAME_SUFFIX;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;
public class ExceptionMeteredTest {
private InstrumentedWithExceptionMetered instance;
private MetricRegistry registry;
@BeforeMethod(groups = "fast")
public void setup() {
this.registry = new NoOpMetricRegistry();
final Injector injector = Guice.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).build());
this.instance = injector.getInstance(InstrumentedWithExceptionMetered.class);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethodWithPublicScope() {
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"exceptionCounter"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.explodeWithPublicScope(true);
fail("Expected an exception to be thrown");
} catch (final RuntimeException e) {
// Swallow the expected exception
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithNoMetricName() {
final Meter metric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"explodeForUnnamedMetric",
DEFAULT_NAME_SUFFIX));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.explodeForUnnamedMetric();
fail("Expected an exception to be thrown");
} catch (final RuntimeException e) {
// Swallow the expected exception
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithName() {
final Meter metric = registry.getMeters().get(String.format("%s.%s", InstrumentedWithExceptionMetered.class.getName(), "n"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.explodeForMetricWithName();
fail("Expected an exception to be thrown");
} catch (final RuntimeException e) {
// Swallow the expected exception
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithAbsoluteName() {
final Meter metric = registry.getMeters().get("absoluteName");
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.explodeForMetricWithAbsoluteName();
fail("Expected an exception to be thrown");
} catch (final RuntimeException e) {
// Swallow the expected exception
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithPublicScopeButNoExceptionThrown() {
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"exceptionCounter"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
instance.explodeWithPublicScope(false);
assertEquals(metric.getCount(), 0L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithDefaultScope() {
final Meter metric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"explodeWithDefaultScope",
DEFAULT_NAME_SUFFIX));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.explodeWithDefaultScope();
fail("Expected an exception to be thrown");
} catch (final RuntimeException ignored) {
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithProtectedScope() {
final Meter metric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"explodeWithProtectedScope",
DEFAULT_NAME_SUFFIX));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.explodeWithProtectedScope();
fail("Expected an exception to be thrown");
} catch (final RuntimeException ignored) {
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithPublicScope_AndSpecificTypeOfException() {
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"failures"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.errorProneMethod(new MyException());
fail("Expected an exception to be thrown");
} catch (final MyException ignored) {
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithPublicScope_AndSubclassesOfSpecifiedException() {
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"failures"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.errorProneMethod(new MySpecialisedException());
fail("Expected an exception to be thrown");
} catch (final MyException ignored) {
}
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithPublicScope_ButDifferentTypeOfException() {
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"failures"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 0L);
try {
instance.errorProneMethod(new MyOtherException());
fail("Expected an exception to be thrown");
} catch (final MyOtherException ignored) {
}
assertEquals(metric.getCount(), 0L);
}
@Test(groups = "fast")
void anExceptionMeteredAnnotatedMethod_WithExtraOptions() {
try {
instance.causeAnOutOfBoundsException();
} catch (final ArrayIndexOutOfBoundsException ignored) {
}
final Meter metric = registry.getMeters().get(String.format("%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"things"));
assertMetricIsSetup(metric);
assertEquals(metric.getCount(), 1L);
}
@Test(groups = "fast")
void aMethodAnnotatedWithBothATimerAndAnExceptionCounter() {
final Timer timedMetric = registry.getTimers().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"timedAndException",
TIMED_SUFFIX));
final Meter errorMetric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"timedAndException",
DEFAULT_NAME_SUFFIX));
assertNotNull(timedMetric);
assertNotNull(errorMetric);
// Counts should start at zero
assertEquals(timedMetric.getCount(), 0L);
assertEquals(errorMetric.getCount(), 0L);
// Invoke, but don't throw an exception
instance.timedAndException(null);
assertEquals(timedMetric.getCount(), 1L);
assertEquals(errorMetric.getCount(), 0L);
// Invoke and throw an exception
try {
instance.timedAndException(new RuntimeException());
fail("Should have thrown an exception");
} catch (final Exception ignored) {
}
assertEquals(timedMetric.getCount(), 2L);
assertEquals(errorMetric.getCount(), 1L);
}
@Test(groups = "fast")
void aMethodAnnotatedWithBothAMeteredAndAnExceptionCounter() {
final Meter meteredMetric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"meteredAndException",
METERED_SUFFIX));
final Meter errorMetric = registry.getMeters().get(String.format("%s.%s.%s",
InstrumentedWithExceptionMetered.class.getName(),
"meteredAndException",
DEFAULT_NAME_SUFFIX));
assertNotNull(meteredMetric);
assertNotNull(errorMetric);
// Counts should start at zero
assertEquals(meteredMetric.getCount(), 0L);
assertEquals(errorMetric.getCount(), 0L);
// Invoke, but don't throw an exception
instance.meteredAndException(null);
assertEquals(meteredMetric.getCount(), 1L);
assertEquals(errorMetric.getCount(), 0L);
// Invoke and throw an exception
try {
instance.meteredAndException(new RuntimeException());
fail("Should have thrown an exception");
} catch (final Exception ignored) {
}
assertEquals(meteredMetric.getCount(),
2L);
assertEquals(errorMetric.getCount(), 1L);
}
private void assertMetricIsSetup(final Meter metric) {
assertNotNull(metric);
}
@SuppressWarnings("serial")
private static class MyOtherException extends RuntimeException {
}
@SuppressWarnings("serial")
private static class MySpecialisedException extends MyException {
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/MyException.java | metrics/src/test/java/org/killbill/commons/metrics/guice/MyException.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
class MyException extends RuntimeException {
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/DeclaringClassNamerGaugeTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/DeclaringClassNamerGaugeTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Gauge;
import org.testng.annotations.Test;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.GAUGE_SUFFIX;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class DeclaringClassNamerGaugeTest extends GaugeTestBase {
@Override
MetricNamer getMetricNamer() {
return new DeclaringClassMetricNamer();
}
@Test(groups = "fast")
void aGaugeWithoutNameInSuperclass() {
// named for the declaring class
final Gauge<?> metric =
registry.getGauges().get(String.format("%s.%s.%s",
InstrumentedWithGaugeParent.class.getName(),
"justAGaugeFromParent",
GAUGE_SUFFIX));
assertNotNull(metric);
assertEquals(metric.getValue(), "justAGaugeFromParent");
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/TimedTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/TimedTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.TIMED_SUFFIX;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class TimedTest {
private InstrumentedWithTimed instance;
private MetricRegistry registry;
@BeforeMethod(groups = "fast")
void setup() {
this.registry = new NoOpMetricRegistry();
final Injector injector = Guice.createInjector(MetricsInstrumentationModule.builder().withMetricRegistry(registry).build());
this.instance = injector.getInstance(InstrumentedWithTimed.class);
}
@Test(groups = "fast")
void aTimedAnnotatedMethod() throws Exception {
instance.doAThing();
final Timer metric = registry.getTimers().get(String.format("%s.%s",
InstrumentedWithTimed.class.getName(),
"things"));
assertMetricSetup(metric);
assertEquals(metric.getCount(), 1L);
//assertTrue(metric.getSnapshot().getMax() > NANOSECONDS.convert(5, MILLISECONDS));
//assertTrue(metric.getSnapshot().getMax() < NANOSECONDS.convert(15, MILLISECONDS));
}
@Test(groups = "fast")
void aTimedAnnotatedMethodWithDefaultScope() {
instance.doAThingWithDefaultScope();
final Timer metric = registry.getTimers().get(String.format("%s.%s.%s",
InstrumentedWithTimed.class.getName(),
"doAThingWithDefaultScope",
TIMED_SUFFIX));
assertMetricSetup(metric);
}
@Test(groups = "fast")
void aTimedAnnotatedMethodWithProtectedScope() {
instance.doAThingWithProtectedScope();
final Timer metric = registry.getTimers().get(String.format("%s.%s.%s",
InstrumentedWithTimed.class.getName(),
"doAThingWithProtectedScope",
TIMED_SUFFIX));
assertMetricSetup(metric);
}
@Test(groups = "fast")
void aTimedAnnotatedMethodWithAbsoluteName() {
instance.doAThingWithAbsoluteName();
final Timer metric = registry.getTimers().get("absoluteName");
assertMetricSetup(metric);
}
private void assertMetricSetup(final Timer metric) {
assertNotNull(metric);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/GaugeTestBase.java | metrics/src/test/java/org/killbill/commons/metrics/guice/GaugeTestBase.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Gauge;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.GAUGE_SUFFIX;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@SuppressWarnings("unchecked")
abstract class GaugeTestBase {
MetricRegistry registry;
private InstrumentedWithGauge instance;
@BeforeMethod(groups = "fast")
void setup() {
this.registry = new NoOpMetricRegistry();
final Injector injector =
Guice.createInjector(MetricsInstrumentationModule.builder()
.withMetricRegistry(registry)
.withMetricNamer(getMetricNamer())
.build());
this.instance = injector.getInstance(InstrumentedWithGauge.class);
}
abstract MetricNamer getMetricNamer();
@Test(groups = "fast")
void aGaugeAnnotatedMethod() {
instance.doAThing();
final Gauge<?> metric = registry.getGauges().get(String.format("%s.%s",
InstrumentedWithGauge.class.getName(),
"things"));
assertNotNull(metric);
assertEquals(metric.getValue(), "poop");
}
@Test(groups = "fast")
void aGaugeAnnotatedMethodWithDefaultName() {
instance.doAnotherThing();
final Gauge<?> metric = registry.getGauges().get(String.format("%s.%s.%s",
InstrumentedWithGauge.class.getName(),
"doAnotherThing",
GAUGE_SUFFIX));
assertNotNull(metric);
assertEquals(metric.getValue(), "anotherThing");
}
@Test(groups = "fast")
void aGaugeAnnotatedMethodWithAbsoluteName() {
instance.doAThingWithAbsoluteName();
final Gauge<?> metric = registry.getGauges().get("absoluteName");
assertNotNull(metric);
assertEquals(metric.getValue(), "anotherThingWithAbsoluteName");
}
@Test(groups = "fast")
void aGaugeInSuperclass() {
final Gauge<?> metric = registry.getGauges().get("gaugeParent");
assertNotNull(metric);
assertEquals(metric.getValue(), "gaugeParent");
}
@Test(groups = "fast")
void aPrivateGaugeInSuperclass() {
final Gauge<?> metric = registry.getGauges().get("gaugeParentPrivate");
assertNotNull(metric);
assertEquals(metric.getValue(), "gaugeParentPrivate");
}
@Test(groups = "fast")
void aPrivateGauge() {
final Gauge<?> metric = registry.getGauges().get(String.format("%s.%s",
InstrumentedWithGauge.class.getName(),
"gaugePrivate"));
assertNotNull(metric);
assertEquals(metric.getValue(), "gaugePrivate");
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithGaugeParent.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithGaugeParent.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Gauge;
class InstrumentedWithGaugeParent {
@Gauge(name = "gaugeParent", absolute = true)
public String gaugeParent() {
return "gaugeParent";
}
@Gauge(name = "gaugeParentPrivate", absolute = true)
private String gaugeParentPrivate() {
return "gaugeParentPrivate";
}
@Gauge
public String justAGaugeFromParent() {
return "justAGaugeFromParent";
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithCounter.java | metrics/src/test/java/org/killbill/commons/metrics/guice/InstrumentedWithCounter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.annotation.Counted;
@SuppressWarnings("UnusedReturnValue")
class InstrumentedWithCounter extends InstrumentedWithCounterParent {
@Counted(name = "things", monotonic = true)
String doAThing() {
return "poop";
}
@Counted(monotonic = true)
String doAnotherThing() {
return "anotherThing";
}
@SuppressWarnings("DefaultAnnotationParam")
@Counted(monotonic = false)
String doYetAnotherThing() {
return "anotherThing";
}
@Counted(name = "absoluteName", absolute = true, monotonic = true)
String doAThingWithAbsoluteName() {
return "anotherThingWithAbsoluteName";
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/GaugeInstanceClassNamerTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/GaugeInstanceClassNamerTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.killbill.commons.metrics.api.Gauge;
import org.testng.annotations.Test;
import static org.killbill.commons.metrics.guice.DeclaringClassMetricNamer.GAUGE_SUFFIX;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class GaugeInstanceClassNamerTest extends GaugeTestBase {
@Override
MetricNamer getMetricNamer() {
return new GaugeInstanceClassMetricNamer();
}
@Test
void aGaugeWithoutNameInSuperclass() {
// named for the instantiated class
final Gauge<?> metric =
registry.getGauges().get(String.format("%s.%s.%s",
InstrumentedWithGauge.class.getName(),
"justAGaugeFromParent",
GAUGE_SUFFIX));
assertNotNull(metric);
assertEquals(metric.getValue(), "justAGaugeFromParent");
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/annotation/ListAnnotationResolverTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/annotation/ListAnnotationResolverTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.reflect.Method;
import java.util.List;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
import org.testng.annotations.Test;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
public class ListAnnotationResolverTest {
@Test(groups = "fast")
public void testMixedAnnotations() throws Exception {
final ListAnnotationResolver annotationProvider = new ListAnnotationResolver(
List.of(new MethodAnnotationResolver(), new ClassAnnotationResolver())
);
final Class<MixedAnnotatedClass> klass = MixedAnnotatedClass.class;
final Method publicMethod = klass.getDeclaredMethod("publicMethod");
final Method protectedMethod = klass.getDeclaredMethod("protectedMethod");
final Method packagePrivateMethod = klass.getDeclaredMethod("packagePrivateMethod");
final Timed classTimed = annotationProvider.findAnnotation(Timed.class, publicMethod);
assertNotNull(classTimed);
assertFalse(classTimed.absolute());
assertNull(annotationProvider.findAnnotation(Metered.class, publicMethod));
assertNull(annotationProvider.findAnnotation(Counted.class, publicMethod));
assertNotNull(annotationProvider.findAnnotation(Timed.class, protectedMethod));
assertNotNull(annotationProvider.findAnnotation(Metered.class, protectedMethod));
assertNull(annotationProvider.findAnnotation(Counted.class, protectedMethod));
final Timed methodTimed = annotationProvider.findAnnotation(Timed.class, packagePrivateMethod);
assertNotNull(methodTimed);
assertTrue(methodTimed.absolute());
assertNull(annotationProvider.findAnnotation(Metered.class, packagePrivateMethod));
assertNull(annotationProvider.findAnnotation(Counted.class, packagePrivateMethod));
}
@SuppressWarnings("WeakerAccess")
@Timed
private static class MixedAnnotatedClass {
public void publicMethod() {
}
@Metered
protected void protectedMethod() {
}
@Timed(absolute = true)
void packagePrivateMethod() {
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/annotation/MethodAnnotationResolverTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/annotation/MethodAnnotationResolverTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.reflect.Method;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
class MethodAnnotationResolverTest {
@Test
void testMethodAnnotations() throws Exception {
final AnnotationResolver matcher = new MethodAnnotationResolver();
final Class<MethodAnnotatedClass> klass = MethodAnnotatedClass.class;
final Method publicMethod = klass.getDeclaredMethod("publicMethod");
final Method protectedMethod = klass.getDeclaredMethod("protectedMethod");
final Method packagePrivateMethod = klass.getDeclaredMethod("packagePrivateMethod");
assertNotNull(matcher.findAnnotation(Timed.class, publicMethod));
assertNotNull(matcher.findAnnotation(Metered.class, protectedMethod));
assertNotNull(matcher.findAnnotation(Counted.class, packagePrivateMethod));
assertNull(matcher.findAnnotation(Timed.class, packagePrivateMethod));
assertNull(matcher.findAnnotation(Counted.class, protectedMethod));
assertNull(matcher.findAnnotation(Metered.class, publicMethod));
}
@SuppressWarnings("WeakerAccess")
private static class MethodAnnotatedClass {
@Timed
public void publicMethod() {
}
@Metered
protected void protectedMethod() {
}
@Counted
void packagePrivateMethod() {
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/test/java/org/killbill/commons/metrics/guice/annotation/ClassAnnotationResolverTest.java | metrics/src/test/java/org/killbill/commons/metrics/guice/annotation/ClassAnnotationResolverTest.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.reflect.Method;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNotNull;
class ClassAnnotationResolverTest {
@Test
void testTypeLevelAnnotations() throws Exception {
final AnnotationResolver matcher = new ClassAnnotationResolver();
final Class<TypeLevelAnnotatedClass> klass = TypeLevelAnnotatedClass.class;
final Method publicMethod = klass.getDeclaredMethod("publicMethod");
final Method protectedMethod = klass.getDeclaredMethod("protectedMethod");
final Method packagePrivateMethod = klass.getDeclaredMethod("packagePrivateMethod");
assertNotNull(matcher.findAnnotation(Timed.class, publicMethod));
assertNotNull(matcher.findAnnotation(Metered.class, publicMethod));
assertNotNull(matcher.findAnnotation(Counted.class, publicMethod));
assertNotNull(matcher.findAnnotation(Timed.class, protectedMethod));
assertNotNull(matcher.findAnnotation(Metered.class, protectedMethod));
assertNotNull(matcher.findAnnotation(Counted.class, protectedMethod));
assertNotNull(matcher.findAnnotation(Timed.class, packagePrivateMethod));
assertNotNull(matcher.findAnnotation(Metered.class, packagePrivateMethod));
assertNotNull(matcher.findAnnotation(Counted.class, packagePrivateMethod));
}
@SuppressWarnings("WeakerAccess")
@Timed
@Metered
@Counted
private static class TypeLevelAnnotatedClass {
public void publicMethod() {
}
protected void protectedMethod() {
}
void packagePrivateMethod() {
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/servlets/HealthCheckJacksonModule.java | metrics/src/main/java/org/killbill/commons/metrics/servlets/HealthCheckJacksonModule.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.servlets;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import org.killbill.commons.health.api.Result;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleSerializers;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class HealthCheckJacksonModule extends Module {
@Override
public String getModuleName() {
return "healthchecks";
}
@Override
public Version version() {
return new Version(1, 0, 0, "", "org.kill-bill.commons", "killbill-metrics");
}
@Override
public void setupModule(final SetupContext context) {
context.addSerializers(new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer())));
}
private static class HealthCheckResultSerializer extends StdSerializer<Result> {
private static final long serialVersionUID = 1L;
private HealthCheckResultSerializer() {
super(Result.class);
}
@Override
public void serialize(final Result result,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
json.writeBooleanField("healthy", result.isHealthy());
final String message = result.getMessage();
if (message != null) {
json.writeStringField("message", message);
}
serializeThrowable(json, result.getError(), "error");
final Map<String, Object> details = result.getDetails();
if (details != null && !details.isEmpty()) {
for (final Map.Entry<String, Object> e : details.entrySet()) {
json.writeObjectField(e.getKey(), e.getValue());
}
}
json.writeEndObject();
}
private void serializeThrowable(final JsonGenerator json, final Throwable error, final String name) throws IOException {
if (error != null) {
json.writeObjectFieldStart(name);
json.writeStringField("type", error.getClass().getTypeName());
json.writeStringField("message", error.getMessage());
json.writeArrayFieldStart("stack");
for (final StackTraceElement element : error.getStackTrace()) {
json.writeString(element.toString());
}
json.writeEndArray();
if (error.getCause() != null) {
serializeThrowable(json, error.getCause(), "cause");
}
json.writeEndObject();
}
}
}
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/servlets/InstrumentedFilter.java | metrics/src/main/java/org/killbill/commons/metrics/servlets/InstrumentedFilter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.servlets;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
/**
* {@link Filter} implementation which captures request information and a breakdown of the response
* codes being returned.
* <p>Use it in your servlet.xml like this:<p>
* <pre>{@code
* <filter>
* <filter-name>instrumentedFilter</filter-name>
* <filter-class>org.killbill.commons.metrics.servlets.InstrumentedFilter</filter-class>
* </filter>
* <filter-mapping>
* <filter-name>instrumentedFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
* }</pre>
*/
public class InstrumentedFilter implements Filter {
public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry";
private static final String METRIC_PREFIX = "name-prefix";
private static final String NAME_PREFIX = "responseCodes.";
private static final int OK = 200;
private static final int CREATED = 201;
private static final int NO_CONTENT = 204;
private static final int BAD_REQUEST = 400;
private static final int NOT_FOUND = 404;
private static final int SERVER_ERROR = 500;
private final Map<Integer, String> meterNamesByStatusCode;
// initialized after call of init method
private ConcurrentMap<Integer, Meter> metersByStatusCode;
private Meter otherMeter;
private Meter timeoutsMeter;
private Meter errorsMeter;
private Counter activeRequests;
private Timer requestTimer;
public InstrumentedFilter() {
this.meterNamesByStatusCode = new HashMap<>(6);
meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok");
meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created");
meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent");
meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest");
meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound");
meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError");
}
@Override
public void init(final FilterConfig filterConfig) {
final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig);
String metricName = filterConfig.getInitParameter(METRIC_PREFIX);
if (metricName == null || metricName.isEmpty()) {
metricName = getClass().getName();
}
this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size());
for (final Entry<Integer, String> entry : meterNamesByStatusCode.entrySet()) {
metersByStatusCode.put(entry.getKey(),
metricsRegistry.meter(String.format("%s.%s", metricName, entry.getValue())));
}
this.otherMeter = metricsRegistry.meter(String.format("%s.%s", metricName, NAME_PREFIX + "other"));
this.timeoutsMeter = metricsRegistry.meter(String.format("%s.%s", metricName, "timeouts"));
this.errorsMeter = metricsRegistry.meter(String.format("%s.%s", metricName, "errors"));
this.activeRequests = metricsRegistry.counter(String.format("%s.%s", metricName, "activeRequests"));
this.requestTimer = metricsRegistry.timer(String.format("%s.%s", metricName, "requests"));
}
private MetricRegistry getMetricsFactory(final FilterConfig filterConfig) {
final MetricRegistry metricsRegistry;
final Object o = filterConfig.getServletContext().getAttribute(REGISTRY_ATTRIBUTE);
if (o instanceof MetricRegistry) {
metricsRegistry = (MetricRegistry) o;
} else {
metricsRegistry = new NoOpMetricRegistry();
}
return metricsRegistry;
}
@Override
public void destroy() {
}
@Override
public void doFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain) throws IOException, ServletException {
final StatusExposingServletResponse wrappedResponse = new StatusExposingServletResponse((HttpServletResponse) response);
activeRequests.inc(1);
final long start = System.nanoTime();
boolean error = false;
try {
chain.doFilter(request, wrappedResponse);
} catch (final IOException | RuntimeException | ServletException e) {
error = true;
throw e;
} finally {
if (!error && request.isAsyncStarted()) {
request.getAsyncContext().addListener(new AsyncResultListener(requestTimer, start));
} else {
requestTimer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS);
activeRequests.dec(1);
if (error) {
errorsMeter.mark(1);
} else {
markMeterForStatusCode(wrappedResponse.getStatus());
}
}
}
}
private void markMeterForStatusCode(final int status) {
final Meter metric = metersByStatusCode.get(status);
if (metric != null) {
metric.mark(1);
} else {
otherMeter.mark(1);
}
}
private static class StatusExposingServletResponse extends HttpServletResponseWrapper {
// The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200.
private int httpStatus = 200;
public StatusExposingServletResponse(final HttpServletResponse response) {
super(response);
}
@Override
public void sendError(final int sc) throws IOException {
httpStatus = sc;
super.sendError(sc);
}
@Override
public void sendError(final int sc, final String msg) throws IOException {
httpStatus = sc;
super.sendError(sc, msg);
}
@Override
@SuppressWarnings("deprecation")
public void setStatus(final int sc, final String sm) {
httpStatus = sc;
super.setStatus(sc, sm);
}
@Override
public int getStatus() {
return httpStatus;
}
@Override
public void setStatus(final int sc) {
httpStatus = sc;
super.setStatus(sc);
}
}
private class AsyncResultListener implements AsyncListener {
private final Timer timer;
private final long start;
private boolean done = false;
public AsyncResultListener(final Timer timer, final long start) {
this.timer = timer;
this.start = start;
}
@Override
public void onComplete(final AsyncEvent event) {
if (!done) {
final HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse();
timer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS);
activeRequests.dec(1);
markMeterForStatusCode(suppliedResponse.getStatus());
}
}
@Override
public void onTimeout(final AsyncEvent event) {
timer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS);
activeRequests.dec(1);
timeoutsMeter.mark(1);
done = true;
}
@Override
public void onError(final AsyncEvent event) {
timer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS);
activeRequests.dec(1);
errorsMeter.mark(1);
done = true;
}
@Override
public void onStartAsync(final AsyncEvent event) {
}
}
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/servlets/MetricsJacksonModule.java | metrics/src/main/java/org/killbill/commons/metrics/servlets/MetricsJacksonModule.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.servlets;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.Gauge;
import org.killbill.commons.metrics.api.Histogram;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Snapshot;
import org.killbill.commons.metrics.api.Timer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleSerializers;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class MetricsJacksonModule extends Module {
protected final TimeUnit rateUnit;
protected final TimeUnit durationUnit;
protected final boolean showSamples;
public MetricsJacksonModule(final TimeUnit rateUnit, final TimeUnit durationUnit, final boolean showSamples) {
this.rateUnit = rateUnit;
this.durationUnit = durationUnit;
this.showSamples = showSamples;
}
private static String calculateRateUnit(final TimeUnit unit, final String name) {
final String s = unit.toString().toLowerCase(Locale.US);
return name + '/' + s.substring(0, s.length() - 1);
}
@Override
public String getModuleName() {
return "metrics";
}
@Override
public Version version() {
return new Version(1, 0, 0, "", "org.kill-bill.commons", "killbill-metrics");
}
@Override
public void setupModule(final SetupContext context) {
context.addSerializers(new SimpleSerializers(Arrays.asList(
new GaugeSerializer(),
new CounterSerializer(),
new HistogramSerializer(showSamples),
new MeterSerializer(rateUnit),
new TimerSerializer(rateUnit, durationUnit, showSamples),
new MetricRegistrySerializer())));
}
@SuppressWarnings("rawtypes")
private static class GaugeSerializer extends StdSerializer<Gauge> {
private static final long serialVersionUID = 1L;
private GaugeSerializer() {
super(Gauge.class);
}
@Override
public void serialize(final Gauge gauge,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
final Object value;
try {
value = gauge.getValue();
json.writeObjectField("value", value);
} catch (final RuntimeException e) {
json.writeObjectField("error", e.toString());
}
json.writeEndObject();
}
}
private static class CounterSerializer extends StdSerializer<Counter> {
private static final long serialVersionUID = 1L;
private CounterSerializer() {
super(Counter.class);
}
@Override
public void serialize(final Counter counter,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
json.writeNumberField("count", counter.getCount());
json.writeEndObject();
}
}
private static class HistogramSerializer extends StdSerializer<Histogram> {
private static final long serialVersionUID = 1L;
private final boolean showSamples;
private HistogramSerializer(final boolean showSamples) {
super(Histogram.class);
this.showSamples = showSamples;
}
@Override
public void serialize(final Histogram histogram,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
final Snapshot snapshot = histogram.getSnapshot();
json.writeNumberField("count", histogram.getCount());
json.writeNumberField("max", snapshot.getMax());
json.writeNumberField("mean", snapshot.getMean());
json.writeNumberField("min", snapshot.getMin());
json.writeNumberField("p50", snapshot.getMedian());
json.writeNumberField("p75", snapshot.get75thPercentile());
json.writeNumberField("p95", snapshot.get95thPercentile());
json.writeNumberField("p98", snapshot.get98thPercentile());
json.writeNumberField("p99", snapshot.get99thPercentile());
json.writeNumberField("p999", snapshot.get999thPercentile());
if (showSamples) {
json.writeObjectField("values", snapshot.getValues());
}
json.writeNumberField("stddev", snapshot.getStdDev());
json.writeEndObject();
}
}
private static class MeterSerializer extends StdSerializer<Meter> {
private static final long serialVersionUID = 1L;
private final String rateUnit;
private final double rateFactor;
public MeterSerializer(final TimeUnit rateUnit) {
super(Meter.class);
this.rateFactor = rateUnit.toSeconds(1);
this.rateUnit = calculateRateUnit(rateUnit, "events");
}
@Override
public void serialize(final Meter meter,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
json.writeNumberField("count", meter.getCount());
json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor);
json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor);
json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor);
json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor);
json.writeStringField("units", rateUnit);
json.writeEndObject();
}
}
private static class TimerSerializer extends StdSerializer<Timer> {
private static final long serialVersionUID = 1L;
private final String rateUnit;
private final double rateFactor;
private final String durationUnit;
private final double durationFactor;
private final boolean showSamples;
private TimerSerializer(final TimeUnit rateUnit,
final TimeUnit durationUnit,
final boolean showSamples) {
super(Timer.class);
this.rateUnit = calculateRateUnit(rateUnit, "calls");
this.rateFactor = rateUnit.toSeconds(1);
this.durationUnit = durationUnit.toString().toLowerCase(Locale.US);
this.durationFactor = 1.0 / durationUnit.toNanos(1);
this.showSamples = showSamples;
}
@Override
public void serialize(final Timer timer,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
final Snapshot snapshot = timer.getSnapshot();
json.writeNumberField("count", timer.getCount());
json.writeNumberField("max", snapshot.getMax() * durationFactor);
json.writeNumberField("mean", snapshot.getMean() * durationFactor);
json.writeNumberField("min", snapshot.getMin() * durationFactor);
json.writeNumberField("p50", snapshot.getMedian() * durationFactor);
json.writeNumberField("p75", snapshot.get75thPercentile() * durationFactor);
json.writeNumberField("p95", snapshot.get95thPercentile() * durationFactor);
json.writeNumberField("p98", snapshot.get98thPercentile() * durationFactor);
json.writeNumberField("p99", snapshot.get99thPercentile() * durationFactor);
json.writeNumberField("p999", snapshot.get999thPercentile() * durationFactor);
if (showSamples) {
final long[] values = snapshot.getValues();
final double[] scaledValues = new double[values.length];
for (int i = 0; i < values.length; i++) {
scaledValues[i] = values[i] * durationFactor;
}
json.writeObjectField("values", scaledValues);
}
json.writeNumberField("stddev", snapshot.getStdDev() * durationFactor);
json.writeNumberField("m15_rate", timer.getFifteenMinuteRate() * rateFactor);
json.writeNumberField("m1_rate", timer.getOneMinuteRate() * rateFactor);
json.writeNumberField("m5_rate", timer.getFiveMinuteRate() * rateFactor);
json.writeNumberField("mean_rate", timer.getMeanRate() * rateFactor);
json.writeStringField("duration_units", durationUnit);
json.writeStringField("rate_units", rateUnit);
json.writeEndObject();
}
}
private static class MetricRegistrySerializer extends StdSerializer<MetricRegistry> {
private static final long serialVersionUID = 1L;
private MetricRegistrySerializer() {
super(MetricRegistry.class);
}
@Override
public void serialize(final MetricRegistry registry,
final JsonGenerator json,
final SerializerProvider provider) throws IOException {
json.writeStartObject();
json.writeObjectField("gauges", registry.getGauges());
json.writeObjectField("counters", registry.getCounters());
json.writeObjectField("histograms", registry.getHistograms());
json.writeObjectField("meters", registry.getMeters());
json.writeObjectField("timers", registry.getTimers());
json.writeEndObject();
}
}
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/servlets/ThreadDumpServlet.java | metrics/src/main/java/org/killbill/commons/metrics/servlets/ThreadDumpServlet.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.servlets;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.Thread.State;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ThreadDumpServlet extends HttpServlet {
private static final long serialVersionUID = -5131980901584483867L;
private static final String CONTENT_TYPE = "text/plain";
private transient ThreadDump threadDump;
private static Boolean getParam(final String initParam, final boolean defaultValue) {
return initParam == null ? defaultValue : Boolean.parseBoolean(initParam);
}
@Override
public void init() {
try {
// Some PaaS like Google App Engine blacklist java.lang.managament
this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean());
} catch (final NoClassDefFoundError ncdfe) {
this.threadDump = null; // we won't be able to provide thread dump
}
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws IOException {
final boolean includeMonitors = getParam(req.getParameter("monitors"), true);
final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true);
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType(CONTENT_TYPE);
resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
if (threadDump == null) {
resp.getWriter().println("Sorry your runtime environment does not allow to dump threads.");
return;
}
try (final OutputStream output = resp.getOutputStream()) {
threadDump.dump(includeMonitors, includeSynchronizers, output);
}
}
public static class ThreadDump {
private final ThreadMXBean threadMXBean;
public ThreadDump(final ThreadMXBean threadMXBean) {
this.threadMXBean = threadMXBean;
}
public void dump(final OutputStream out) {
this.dump(true, true, out);
}
public void dump(final boolean lockedMonitors, final boolean lockedSynchronizers, final OutputStream out) {
final ThreadInfo[] threads = this.threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers);
final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
for (int ti = threads.length - 1; ti >= 0; --ti) {
final ThreadInfo t = threads[ti];
writer.printf("\"%s\" id=%d state=%s", t.getThreadName(), t.getThreadId(), t.getThreadState());
final LockInfo lock = t.getLockInfo();
if (lock != null && t.getThreadState() != State.BLOCKED) {
writer.printf("%n - waiting on <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName());
writer.printf("%n - locked <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName());
} else if (lock != null && t.getThreadState() == State.BLOCKED) {
writer.printf("%n - waiting to lock <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName());
}
if (t.isSuspended()) {
writer.print(" (suspended)");
}
if (t.isInNative()) {
writer.print(" (running in native)");
}
writer.println();
if (t.getLockOwnerName() != null) {
writer.printf(" owned by %s id=%d%n", t.getLockOwnerName(), t.getLockOwnerId());
}
final StackTraceElement[] elements = t.getStackTrace();
final MonitorInfo[] monitors = t.getLockedMonitors();
int j;
for (int i = 0; i < elements.length; ++i) {
final StackTraceElement element = elements[i];
writer.printf(" at %s%n", element);
for (j = 1; j < monitors.length; ++j) {
final MonitorInfo monitor = monitors[j];
if (monitor.getLockedStackDepth() == i) {
writer.printf(" - locked %s%n", monitor);
}
}
}
writer.println();
final LockInfo[] locks = t.getLockedSynchronizers();
if (locks.length > 0) {
writer.printf(" Locked synchronizers: count = %d%n", locks.length);
final LockInfo[] var17 = locks;
j = locks.length;
for (int var18 = 0; var18 < j; ++var18) {
final LockInfo l = var17[var18];
writer.printf(" - %s%n", l);
}
writer.println();
}
}
writer.println();
writer.flush();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/servlets/HealthCheckServlet.java | metrics/src/main/java/org/killbill/commons/metrics/servlets/HealthCheckServlet.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.servlets;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.killbill.commons.health.api.HealthCheckRegistry;
import org.killbill.commons.health.api.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class HealthCheckServlet extends HttpServlet {
public static final String HEALTH_CHECK_REGISTRY = HealthCheckServlet.class.getCanonicalName() + ".registry";
public static final String HEALTH_CHECK_MAPPER = HealthCheckServlet.class.getCanonicalName() + ".mapper";
private static final long serialVersionUID = -128753347944002146L;
private static final String CONTENT_TYPE = "application/json";
private transient HealthCheckRegistry registry;
private transient ObjectMapper mapper;
public HealthCheckServlet() {
}
public HealthCheckServlet(final HealthCheckRegistry registry) {
this.registry = registry;
}
private static boolean isAllHealthy(final Map<String, Result> results) {
for (final Result result : results.values()) {
if (!result.isHealthy()) {
return false;
}
}
return true;
}
@Override
public void init(final ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY);
if (registryAttr instanceof HealthCheckRegistry) {
this.registry = (HealthCheckRegistry) registryAttr;
} else {
throw new ServletException("Couldn't find a HealthCheckRegistry instance.");
}
}
final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER);
if (mapperAttr instanceof ObjectMapper) {
this.mapper = (ObjectMapper) mapperAttr;
} else {
this.mapper = new ObjectMapper();
}
this.mapper.registerModule(new HealthCheckJacksonModule());
}
@Override
public void destroy() {
super.destroy();
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws IOException {
final SortedMap<String, Result> results = runHealthChecks();
resp.setContentType(CONTENT_TYPE);
resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
if (results.isEmpty()) {
resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else {
if (isAllHealthy(results)) {
resp.setStatus(HttpServletResponse.SC_OK);
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
try (final OutputStream output = resp.getOutputStream()) {
getWriter(req).writeValue(output, results);
}
}
private ObjectWriter getWriter(final ServletRequest request) {
final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty"));
if (prettyPrint) {
return mapper.writerWithDefaultPrettyPrinter();
}
return mapper.writer();
}
private SortedMap<String, Result> runHealthChecks() {
final SortedMap<String, Result> results = new TreeMap<>();
for (final String name : registry.getNames()) {
results.put(name, registry.runHealthCheck(name));
}
return results;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/servlets/MetricsServlet.java | metrics/src/main/java/org/killbill/commons/metrics/servlets/MetricsServlet.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.servlets;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.impl.NoOpMetricRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class MetricsServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(MetricsServlet.class);
public static final String METRICS_REGISTRY = MetricsServlet.class.getCanonicalName() + ".registry";
public static final String OBJECT_MAPPER = MetricsServlet.class.getCanonicalName() + ".mapper";
private static final long serialVersionUID = 5368376475901310760L;
private static final String CONTENT_TYPE = "application/json";
protected String allowedOrigin;
protected transient MetricRegistry registry;
protected transient ObjectMapper mapper;
@Override
public void init(final ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
if (registryAttr instanceof MetricRegistry) {
if (registryAttr instanceof NoOpMetricRegistry) {
logger.warn("Metrics are not enabled");
} else {
this.registry = (MetricRegistry) registryAttr;
}
} else {
throw new ServletException("Couldn't find a MetricRegistry instance.");
}
}
if (null == mapper) {
final Object mapperAttr = context.getAttribute(OBJECT_MAPPER);
if (mapperAttr instanceof ObjectMapper) {
this.mapper = (ObjectMapper) mapperAttr;
} else {
this.mapper = new ObjectMapper();
}
this.mapper.registerModule(new MetricsJacksonModule(TimeUnit.SECONDS,
TimeUnit.SECONDS,
false));
}
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws IOException {
resp.setContentType(CONTENT_TYPE);
if (allowedOrigin != null) {
resp.setHeader("Access-Control-Allow-Origin", allowedOrigin);
}
resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
resp.setStatus(HttpServletResponse.SC_OK);
try (final OutputStream output = resp.getOutputStream()) {
getWriter(req).writeValue(output, registry);
}
}
protected ObjectWriter getWriter(final ServletRequest request) {
final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty"));
if (prettyPrint) {
return mapper.writerWithDefaultPrettyPrinter();
}
return mapper.writer();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/CountedInterceptor.java | metrics/src/main/java/org/killbill/commons/metrics/guice/CountedInterceptor.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.annotation.Counted;
class CountedInterceptor implements MethodInterceptor {
private final Counter counter;
private final boolean decrementAfterMethod;
CountedInterceptor(final Counter counter, final Counted annotation) {
this.counter = counter;
decrementAfterMethod = !annotation.monotonic();
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
counter.inc(1);
try {
return invocation.proceed();
} finally {
if (decrementAfterMethod) {
counter.dec(1);
}
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/DeclaredMethodsTypeListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/DeclaredMethodsTypeListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
import org.aopalliance.intercept.MethodInterceptor;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;
/**
* A TypeListener which delegates to {@link DeclaredMethodsTypeListener#getInterceptor(Method)} for each method in the
* class's declared methods.
*/
abstract class DeclaredMethodsTypeListener implements TypeListener {
@Override
public <T> void hear(final TypeLiteral<T> literal, final TypeEncounter<T> encounter) {
final Class<? super T> klass = literal.getRawType();
for (final Method method : klass.getDeclaredMethods()) {
if (method.isSynthetic()) {
continue;
}
final MethodInterceptor interceptor = getInterceptor(method);
if (interceptor != null) {
encounter.bindInterceptor(Matchers.only(method), interceptor);
}
}
}
/**
* Called for every method on every class in the type hierarchy of the visited type
*
* @param method method to get interceptor for
* @return null if no interceptor should be applied, else an interceptor
*/
@Nullable
protected abstract MethodInterceptor getInterceptor(Method method);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/GaugeInstanceClassMetricNamer.java | metrics/src/main/java/org/killbill/commons/metrics/guice/GaugeInstanceClassMetricNamer.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import org.killbill.commons.metrics.api.annotation.Gauge;
/**
* For gauges (which can reside in superclasses of the type being instantiated), this will use the instantiated type for
* the resulting metric name no matter what superclass declares the gauge method. This allows for a gauge located in a
* superclass to be used by multiple inheritors without causing a duplicate metric name clash.
* <p>
* For other metric types, which are not available on superclass methods, the declaring class (which would be the same
* as the instantiated class) is used, as in {@link DeclaringClassMetricNamer}.
*/
public class GaugeInstanceClassMetricNamer extends DeclaringClassMetricNamer {
@Nonnull
@Override
public String getNameForGauge(@Nonnull final Class<?> instanceClass, @Nonnull final Method method, @Nonnull final Gauge gauge) {
if (gauge.absolute()) {
return gauge.name();
}
if (gauge.name().isEmpty()) {
return String.format("%s.%s.%s", instanceClass.getName(), method.getName(), GAUGE_SUFFIX);
}
return String.format("%s.%s", instanceClass.getName(), gauge.name());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/TimedInterceptor.java | metrics/src/main/java/org/killbill/commons/metrics/guice/TimedInterceptor.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.util.concurrent.TimeUnit;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.killbill.commons.metrics.api.Timer;
/**
* A method interceptor which times the execution of the annotated method.
*/
class TimedInterceptor implements MethodInterceptor {
private final Timer timer;
TimedInterceptor(final Timer timer) {
this.timer = timer;
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// Since these timers are always created via the default ctor (via MetricRegister#timer), they always use
// nanoTime, so we can save an allocation here by not using Context.
final long start = System.nanoTime();
try {
return invocation.proceed();
} finally {
timer.update(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/MetricsInstrumentationModule.java | metrics/src/main/java/org/killbill/commons/metrics/guice/MetricsInstrumentationModule.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import javax.annotation.Nonnull;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.api.annotation.ExceptionMetered;
import org.killbill.commons.metrics.api.annotation.Gauge;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matcher;
import com.google.inject.matcher.Matchers;
import org.killbill.commons.metrics.guice.annotation.AnnotationResolver;
import org.killbill.commons.metrics.guice.annotation.MethodAnnotationResolver;
import org.killbill.commons.utils.Preconditions;
/**
* A Guice module which instruments methods annotated with the {@link Metered}, {@link Timed}, {@link Gauge}, {@link
* Counted}, and {@link ExceptionMetered} annotations.
*
* @see Gauge
* @see Metered
* @see Timed
* @see ExceptionMetered
* @see Counted
* @see MeteredInterceptor
* @see TimedInterceptor
* @see GaugeInjectionListener
*/
public class MetricsInstrumentationModule extends AbstractModule {
private final MetricRegistry metricRegistry;
private final Matcher<? super TypeLiteral<?>> matcher;
private final MetricNamer metricNamer;
private final AnnotationResolver annotationResolver;
/**
* @param metricRegistry The registry to use when creating meters, etc. for annotated methods.
* @param matcher The matcher to determine which types to look for metrics in
* @param metricNamer The metric namer to use when creating names for metrics for annotated methods
* @param annotationResolver The annotation provider
*/
private MetricsInstrumentationModule(final MetricRegistry metricRegistry,
final Matcher<? super TypeLiteral<?>> matcher,
final MetricNamer metricNamer,
final AnnotationResolver annotationResolver) {
this.metricRegistry = metricRegistry;
this.matcher = matcher;
this.metricNamer = metricNamer;
this.annotationResolver = annotationResolver;
}
public static Builder builder() {
return new Builder();
}
@Override
protected void configure() {
bindListener(matcher, new MeteredListener(metricRegistry, metricNamer, annotationResolver));
bindListener(matcher, new TimedListener(metricRegistry, metricNamer, annotationResolver));
bindListener(matcher, new GaugeListener(metricRegistry, metricNamer, annotationResolver));
bindListener(matcher, new ExceptionMeteredListener(metricRegistry, metricNamer, annotationResolver));
bindListener(matcher, new CountedListener(metricRegistry, metricNamer, annotationResolver));
}
public static class Builder {
private MetricRegistry metricRegistry;
private Matcher<? super TypeLiteral<?>> matcher = Matchers.any();
private MetricNamer metricNamer = new GaugeInstanceClassMetricNamer();
private AnnotationResolver annotationResolver = new MethodAnnotationResolver();
/**
* @param metricRegistry The registry to use when creating meters, etc. for annotated methods.
* @return this
*/
@Nonnull
public Builder withMetricRegistry(@Nonnull final MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
return this;
}
/**
* @param matcher The matcher to determine which types to look for metrics in
* @return this
*/
@Nonnull
public Builder withMatcher(@Nonnull final Matcher<? super TypeLiteral<?>> matcher) {
this.matcher = matcher;
return this;
}
/**
* @param metricNamer The metric namer to use when creating names for metrics for annotated methods
* @return this
*/
@Nonnull
public Builder withMetricNamer(@Nonnull final MetricNamer metricNamer) {
this.metricNamer = metricNamer;
return this;
}
/**
* @param annotationResolver Annotation resolver to use
* @return this
*/
@Nonnull
public Builder withAnnotationMatcher(@Nonnull final AnnotationResolver annotationResolver) {
this.annotationResolver = annotationResolver;
return this;
}
@Nonnull
public MetricsInstrumentationModule build() {
return new MetricsInstrumentationModule(
Preconditions.checkNotNull(metricRegistry),
Preconditions.checkNotNull(matcher),
Preconditions.checkNotNull(metricNamer),
Preconditions.checkNotNull(annotationResolver)
);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/MetricNamer.java | metrics/src/main/java/org/killbill/commons/metrics/guice/MetricNamer.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.api.annotation.ExceptionMetered;
import org.killbill.commons.metrics.api.annotation.Gauge;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
/**
* Generates for the metrics corresponding to the various metric annotations.
*/
public interface MetricNamer {
@Nonnull
String getNameForCounted(@Nonnull Method method, @Nonnull Counted counted);
@Nonnull
String getNameForExceptionMetered(@Nonnull Method method, @Nonnull ExceptionMetered exceptionMetered);
/**
* For AOP-wrapped method invocations (which is how all metrics other than Gauges have to be handled), there isn't a
* way to handle annotated methods defined in superclasses since we can't AOP superclass methods. Gauges, however,
* are invoked without requiring AOP, so gauges from superclasses are available.
*
* @param instanceClass the type being instantiated
* @param method the annotated method (which may belong to a supertype)
* @param gauge the annotation
* @return a name
*/
@Nonnull
String getNameForGauge(@Nonnull Class<?> instanceClass, @Nonnull Method method, @Nonnull Gauge gauge);
@Nonnull
String getNameForMetered(@Nonnull Method method, @Nonnull Metered metered);
@Nonnull
String getNameForTimed(@Nonnull Method method, @Nonnull Timed timed);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/CountedListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/CountedListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
import org.aopalliance.intercept.MethodInterceptor;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.guice.annotation.AnnotationResolver;
/**
* A listener which adds method interceptors to counted methods.
*/
public class CountedListener extends DeclaredMethodsTypeListener {
private final MetricRegistry metricRegistry;
private final MetricNamer metricNamer;
private final AnnotationResolver annotationResolver;
public CountedListener(final MetricRegistry metricRegistry, final MetricNamer metricNamer,
final AnnotationResolver annotationResolver) {
this.metricRegistry = metricRegistry;
this.metricNamer = metricNamer;
this.annotationResolver = annotationResolver;
}
@Nullable
@Override
protected MethodInterceptor getInterceptor(final Method method) {
final Counted annotation = annotationResolver.findAnnotation(Counted.class, method);
if (annotation != null) {
final Counter counter = metricRegistry.counter(metricNamer.getNameForCounted(method, annotation));
return new CountedInterceptor(counter, annotation);
}
return null;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/GaugeInjectionListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/GaugeInjectionListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import org.killbill.commons.metrics.api.Gauge;
import org.killbill.commons.metrics.api.MetricRegistry;
import com.google.inject.spi.InjectionListener;
/**
* An injection listener which creates a gauge for the declaring class with the given name (or the method's name, if
* none was provided) which returns the value returned by the annotated method.
*/
public class GaugeInjectionListener<I> implements InjectionListener<I> {
private final MetricRegistry metricRegistry;
private final String metricName;
private final Method method;
public GaugeInjectionListener(final MetricRegistry metricRegistry, final String metricName, final Method method) {
this.metricRegistry = metricRegistry;
this.metricName = metricName;
this.method = method;
}
@Override
public void afterInjection(final I i) {
metricRegistry.gauge(metricName,
new Gauge<>() {
@Override
public Object getValue() {
try {
return method.invoke(i);
} catch (final Exception e) {
return new RuntimeException(e);
}
}
});
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/MeteredListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/MeteredListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
import org.aopalliance.intercept.MethodInterceptor;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.guice.annotation.AnnotationResolver;
/**
* A listener which adds method interceptors to metered methods.
*/
public class MeteredListener extends DeclaredMethodsTypeListener {
private final MetricRegistry metricRegistry;
private final MetricNamer metricNamer;
private final AnnotationResolver annotationResolver;
public MeteredListener(final MetricRegistry metricRegistry, final MetricNamer metricNamer,
final AnnotationResolver annotationResolver) {
this.metricRegistry = metricRegistry;
this.metricNamer = metricNamer;
this.annotationResolver = annotationResolver;
}
@Nullable
@Override
protected MethodInterceptor getInterceptor(final Method method) {
final Metered annotation = annotationResolver.findAnnotation(Metered.class, method);
if (annotation != null) {
final Meter meter = metricRegistry.meter(metricNamer.getNameForMetered(method, annotation));
return new MeteredInterceptor(meter);
}
return null;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/MeteredInterceptor.java | metrics/src/main/java/org/killbill/commons/metrics/guice/MeteredInterceptor.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.killbill.commons.metrics.api.Meter;
/**
* A method interceptor which creates a meter for the declaring class with the given name (or the method's name, if none
* was provided), and which measures the rate at which the annotated method is invoked.
*/
class MeteredInterceptor implements MethodInterceptor {
private final Meter meter;
MeteredInterceptor(final Meter meter) {
this.meter = meter;
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
meter.mark(1);
return invocation.proceed();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/GaugeListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/GaugeListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.Gauge;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;
import org.killbill.commons.metrics.guice.annotation.AnnotationResolver;
/**
* A listener which adds gauge injection listeners to classes with gauges.
*/
public class GaugeListener implements TypeListener {
private final MetricRegistry metricRegistry;
private final MetricNamer metricNamer;
private final AnnotationResolver annotationResolver;
public GaugeListener(final MetricRegistry metricRegistry, final MetricNamer metricNamer,
final AnnotationResolver annotationResolver) {
this.metricRegistry = metricRegistry;
this.metricNamer = metricNamer;
this.annotationResolver = annotationResolver;
}
@Override
public <I> void hear(final TypeLiteral<I> literal, final TypeEncounter<I> encounter) {
Class<? super I> klass = literal.getRawType();
final Class<?> instanceType = klass;
do {
for (final Method method : klass.getDeclaredMethods()) {
if (method.isSynthetic()) {
continue;
}
final Gauge annotation = annotationResolver.findAnnotation(Gauge.class, method);
if (annotation != null) {
if (method.getParameterTypes().length == 0) {
final String metricName = metricNamer.getNameForGauge(instanceType, method, annotation);
// deprecated method in java 9, but replacement is not available in java 8
if (!method.isAccessible()) {
method.setAccessible(true);
}
encounter.register(new GaugeInjectionListener<>(metricRegistry, metricName, method));
} else {
encounter.addError("Method %s is annotated with @Gauge but requires parameters.",
method);
}
}
}
} while ((klass = klass.getSuperclass()) != null);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/DeclaringClassMetricNamer.java | metrics/src/main/java/org/killbill/commons/metrics/guice/DeclaringClassMetricNamer.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import org.killbill.commons.metrics.api.annotation.Counted;
import org.killbill.commons.metrics.api.annotation.ExceptionMetered;
import org.killbill.commons.metrics.api.annotation.Gauge;
import org.killbill.commons.metrics.api.annotation.Metered;
import org.killbill.commons.metrics.api.annotation.Timed;
/**
* Uses the name fields in the metric annotations, if present, or the method declaring class and method name.
*/
public class DeclaringClassMetricNamer implements MetricNamer {
static final String COUNTER_SUFFIX = "counter";
static final String COUNTER_SUFFIX_MONOTONIC = "current";
static final String GAUGE_SUFFIX = "gauge";
static final String METERED_SUFFIX = "meter";
static final String TIMED_SUFFIX = "timer";
@Nonnull
@Override
public String getNameForCounted(@Nonnull final Method method, @Nonnull final Counted counted) {
if (counted.absolute()) {
return counted.name();
}
if (counted.name().isEmpty()) {
if (counted.monotonic()) {
return String.format("%s.%s.%s", method.getDeclaringClass().getName(), method.getName(), COUNTER_SUFFIX_MONOTONIC);
} else {
return String.format("%s.%s.%s", method.getDeclaringClass().getName(), method.getName(), COUNTER_SUFFIX);
}
}
return String.format("%s.%s", method.getDeclaringClass().getName(), counted.name());
}
@Nonnull
@Override
public String getNameForExceptionMetered(@Nonnull final Method method, @Nonnull final ExceptionMetered exceptionMetered) {
if (exceptionMetered.absolute()) {
return exceptionMetered.name();
}
if (exceptionMetered.name().isEmpty()) {
return String.format("%s.%s.%s", method.getDeclaringClass().getName(), method.getName(), ExceptionMetered.DEFAULT_NAME_SUFFIX);
}
return String.format("%s.%s", method.getDeclaringClass().getName(), exceptionMetered.name());
}
@Nonnull
@Override
public String getNameForGauge(@Nonnull final Class<?> instanceClass, @Nonnull final Method method, @Nonnull final Gauge gauge) {
if (gauge.absolute()) {
return gauge.name();
}
if (gauge.name().isEmpty()) {
return String.format("%s.%s.%s", method.getDeclaringClass().getName(), method.getName(), GAUGE_SUFFIX);
}
return String.format("%s.%s", method.getDeclaringClass().getName(), gauge.name());
}
@Nonnull
@Override
public String getNameForMetered(@Nonnull final Method method, @Nonnull final Metered metered) {
if (metered.absolute()) {
return metered.name();
}
if (metered.name().isEmpty()) {
return String.format("%s.%s.%s", method.getDeclaringClass().getName(), method.getName(), METERED_SUFFIX);
}
return String.format("%s.%s", method.getDeclaringClass().getName(), metered.name());
}
@Nonnull
@Override
public String getNameForTimed(@Nonnull final Method method, @Nonnull final Timed timed) {
if (timed.absolute()) {
return timed.name();
}
if (timed.name().isEmpty()) {
return String.format("%s.%s.%s", method.getDeclaringClass().getName(), method.getName(), TIMED_SUFFIX);
}
return String.format("%s.%s", method.getDeclaringClass().getName(), timed.name());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/ExceptionMeteredListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/ExceptionMeteredListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
import org.aopalliance.intercept.MethodInterceptor;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.annotation.ExceptionMetered;
import org.killbill.commons.metrics.guice.annotation.AnnotationResolver;
/**
* A listener which adds method interceptors to methods that should be instrumented for exceptions
*/
public class ExceptionMeteredListener extends DeclaredMethodsTypeListener {
private final MetricRegistry metricRegistry;
private final MetricNamer metricNamer;
private final AnnotationResolver annotationResolver;
public ExceptionMeteredListener(final MetricRegistry metricRegistry, final MetricNamer metricNamer,
final AnnotationResolver annotationResolver) {
this.metricRegistry = metricRegistry;
this.metricNamer = metricNamer;
this.annotationResolver = annotationResolver;
}
@Nullable
@Override
protected MethodInterceptor getInterceptor(final Method method) {
final ExceptionMetered annotation = annotationResolver.findAnnotation(ExceptionMetered.class, method);
if (annotation != null) {
final Meter meter = metricRegistry.meter(metricNamer.getNameForExceptionMetered(method, annotation));
return new ExceptionMeteredInterceptor(meter, annotation.cause());
}
return null;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/TimedListener.java | metrics/src/main/java/org/killbill/commons/metrics/guice/TimedListener.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
import org.aopalliance.intercept.MethodInterceptor;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.killbill.commons.metrics.api.annotation.Timed;
import org.killbill.commons.metrics.guice.annotation.AnnotationResolver;
/**
* A listener which adds method interceptors to timed methods.
*/
public class TimedListener extends DeclaredMethodsTypeListener {
private final MetricRegistry metricRegistry;
private final MetricNamer metricNamer;
private final AnnotationResolver annotationResolver;
public TimedListener(final MetricRegistry metricRegistry,
final MetricNamer metricNamer,
final AnnotationResolver annotationResolver) {
this.metricRegistry = metricRegistry;
this.metricNamer = metricNamer;
this.annotationResolver = annotationResolver;
}
@Nullable
@Override
protected MethodInterceptor getInterceptor(final Method method) {
final Timed annotation = annotationResolver.findAnnotation(Timed.class, method);
if (annotation != null) {
final Timer timer = metricRegistry.timer(metricNamer.getNameForTimed(method, annotation));
return new TimedInterceptor(timer);
}
return null;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/ExceptionMeteredInterceptor.java | metrics/src/main/java/org/killbill/commons/metrics/guice/ExceptionMeteredInterceptor.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.killbill.commons.metrics.api.Meter;
/**
* A method interceptor which measures the rate at which the annotated method throws exceptions of a given type.
*/
class ExceptionMeteredInterceptor implements MethodInterceptor {
private final Meter meter;
private final Class<? extends Throwable> klass;
ExceptionMeteredInterceptor(final Meter meter, final Class<? extends Throwable> klass) {
this.meter = meter;
this.klass = klass;
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
try {
return invocation.proceed();
} catch (final Throwable t) {
if (klass.isAssignableFrom(t.getClass())) {
meter.mark(1);
}
throw t;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/ClassAnnotationResolver.java | metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/ClassAnnotationResolver.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Looks for annotations on the enclosing class of the method.
*/
public class ClassAnnotationResolver implements AnnotationResolver {
@Override
@Nullable
public <T extends Annotation> T findAnnotation(@Nonnull final Class<T> annotationClass,
@Nonnull final Method method) {
return method.getDeclaringClass().getAnnotation(annotationClass);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/MethodAnnotationResolver.java | metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/MethodAnnotationResolver.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Looks for annotations on the method itself.
*/
public class MethodAnnotationResolver implements AnnotationResolver {
@Override
@Nullable
public <T extends Annotation> T findAnnotation(@Nonnull final Class<T> annotationClass,
@Nonnull final Method method) {
return method.getAnnotation(annotationClass);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/ListAnnotationResolver.java | metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/ListAnnotationResolver.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Delegates to the provided list of resolvers, applying each resolver in turn.
*/
public class ListAnnotationResolver implements AnnotationResolver {
private final List<AnnotationResolver> resolvers;
public ListAnnotationResolver(final List<AnnotationResolver> resolvers) {
this.resolvers = new ArrayList<>(resolvers);
}
@Nullable
@Override
public <T extends Annotation> T findAnnotation(@Nonnull final Class<T> annotationClass, @Nonnull final Method method) {
for (final AnnotationResolver resolver : resolvers) {
final T result = resolver.findAnnotation(annotationClass, method);
if (result != null) {
return result;
}
}
return null;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/AnnotationResolver.java | metrics/src/main/java/org/killbill/commons/metrics/guice/annotation/AnnotationResolver.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.guice.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Finds annotations, if any, pertaining to a particular Method. Extension point for customizing annotation lookup.
*/
public interface AnnotationResolver {
/**
* @param annotationClass Metrics annotation to look for
* @param method method that the corresponding metric may be applied to
* @param <T> annotation type
* @return a T instance, if found, else null
*/
@Nullable
<T extends Annotation> T findAnnotation(@Nonnull Class<T> annotationClass, @Nonnull Method method);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/health/KillBillHealthCheckRegistry.java | metrics/src/main/java/org/killbill/commons/metrics/health/KillBillHealthCheckRegistry.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.health;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject;
import org.killbill.commons.health.api.HealthCheck;
import org.killbill.commons.health.api.HealthCheckRegistry;
import org.killbill.commons.health.api.Result;
import org.killbill.commons.health.impl.UnhealthyResultBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KillBillHealthCheckRegistry implements HealthCheckRegistry {
private static final Logger logger = LoggerFactory.getLogger(KillBillHealthCheckRegistry.class);
private final ConcurrentMap<String, HealthCheck> healthChecks = new ConcurrentHashMap<>();
// Lazily register the healthchecks to help Guice with circular dependencies
@Inject
public void initialize(final Set<HealthCheck> healthChecks) {
for (final HealthCheck healthCheck : healthChecks) {
register(healthCheck.getClass().getName(), healthCheck);
}
}
@Override
public Set<String> getNames() {
return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet()));
}
@Override
public Result runHealthCheck(final String name) throws NoSuchElementException {
final HealthCheck healthCheck = healthChecks.get(name);
if (healthCheck == null) {
throw new NoSuchElementException("No health check named " + name + " exists");
}
final Result result = execute(healthCheck);
logUnHealthyResult(name, result);
return result;
}
/**
* Executes the health check, catching and handling any exceptions raised by {@link HealthCheck#check()}.
*
* @param healthCheck the healthcheck
* @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link Result} with a descriptive error message or exception
*/
public Result execute(final HealthCheck healthCheck) {
try {
return healthCheck.check();
} catch (final Exception e) {
return new UnhealthyResultBuilder().setError(e).createUnhealthyResult();
}
}
@Override
public void register(final String name, final HealthCheck healthCheck) {
synchronized (this) {
if (healthChecks.containsKey(name)) {
throw new IllegalArgumentException("A health check named " + name + " already exists");
}
healthChecks.put(name, healthCheck);
}
}
private void logUnHealthyResult(final String healthCheckName, final Result healthCheckResult) {
if (!healthCheckResult.isHealthy()) {
logger.warn("HealthCheck {} failed: {}", healthCheckName, healthCheckResult.toString());
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleCounter.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleCounter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Counter;
import com.codahale.metrics.Counting;
import com.codahale.metrics.Metric;
public class CodahaleCounter implements Metric, Counting {
private final Counter counter;
public CodahaleCounter(final Counter counter) {
this.counter = counter;
}
@Override
public long getCount() {
return counter.getCount();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleTimer.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleTimer.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import java.util.concurrent.TimeUnit;
import org.killbill.commons.metrics.api.Snapshot;
import org.killbill.commons.metrics.api.Timer;
public class KillBillCodahaleTimer implements Timer {
private final com.codahale.metrics.Timer dwTimer;
public KillBillCodahaleTimer(final com.codahale.metrics.Timer dwTimer) {
this.dwTimer = dwTimer;
}
@Override
public long getCount() {
return dwTimer.getCount();
}
@Override
public void update(final long duration, final TimeUnit unit) {
dwTimer.update(duration, unit);
}
@Override
public double getFifteenMinuteRate() {
return dwTimer.getFifteenMinuteRate();
}
@Override
public double getFiveMinuteRate() {
return dwTimer.getFiveMinuteRate();
}
@Override
public double getMeanRate() {
return dwTimer.getMeanRate();
}
@Override
public double getOneMinuteRate() {
return dwTimer.getOneMinuteRate();
}
@Override
public Snapshot getSnapshot() {
return new KillBillCodahaleSnapshot(dwTimer.getSnapshot());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleMetricRegistry.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleMetricRegistry.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.killbill.commons.metrics.api.Counter;
import org.killbill.commons.metrics.api.Gauge;
import org.killbill.commons.metrics.api.Histogram;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.Metric;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import com.codahale.metrics.MetricRegistry.MetricSupplier;
public class KillBillCodahaleMetricRegistry implements MetricRegistry {
private final com.codahale.metrics.MetricRegistry dwMetricRegistry;
public KillBillCodahaleMetricRegistry() {
this(new com.codahale.metrics.MetricRegistry());
}
public KillBillCodahaleMetricRegistry(final com.codahale.metrics.MetricRegistry dwMetricRegistry) {
this.dwMetricRegistry = dwMetricRegistry;
}
@Override
public Counter counter(final String name) {
return new KillBillCodahaleCounter(dwMetricRegistry.counter(name));
}
@Override
public <T> Gauge<T> gauge(final String name, final Gauge<T> supplier) {
return new KillBillCodahaleGauge<T>(dwMetricRegistry.gauge(name,
new MetricSupplier<>() {
@Override
public com.codahale.metrics.Gauge<T> newMetric() {
return new CodahaleGauge(supplier);
}
}));
}
@Override
public Histogram histogram(final String name) {
return new KillBillCodahaleHistogram(dwMetricRegistry.histogram(name));
}
@Override
public Meter meter(final String name) {
return new KillBillCodahaleMeter(dwMetricRegistry.meter(name));
}
@Override
public Timer timer(final String name) {
return new KillBillCodahaleTimer(dwMetricRegistry.timer(name));
}
@Override
public boolean remove(final String name) {
return false;
}
@Override
public Map<String, ?> getMetrics() {
return dwMetricRegistry.getMetrics();
}
@Override
public Map<String, Gauge<?>> getGauges() {
final Map<String, Gauge<?>> gauges = new HashMap<>();
for (final Entry<String, com.codahale.metrics.Gauge> entry : dwMetricRegistry.getGauges().entrySet()) {
gauges.put(entry.getKey(), new KillBillCodahaleGauge(entry.getValue()));
}
return gauges;
}
@Override
public Map<String, Meter> getMeters() {
final Map<String, Meter> meters = new HashMap<>();
for (final Entry<String, com.codahale.metrics.Meter> entry : dwMetricRegistry.getMeters().entrySet()) {
meters.put(entry.getKey(), new KillBillCodahaleMeter(entry.getValue()));
}
return meters;
}
@Override
public Map<String, Counter> getCounters() {
final Map<String, Counter> counters = new HashMap<>();
for (final Entry<String, com.codahale.metrics.Counter> entry : dwMetricRegistry.getCounters().entrySet()) {
counters.put(entry.getKey(), new KillBillCodahaleCounter(entry.getValue()));
}
return counters;
}
@Override
public Map<String, Histogram> getHistograms() {
final Map<String, Histogram> histograms = new HashMap<>();
for (final Entry<String, com.codahale.metrics.Histogram> entry : dwMetricRegistry.getHistograms().entrySet()) {
histograms.put(entry.getKey(), new KillBillCodahaleHistogram(entry.getValue()));
}
return histograms;
}
@Override
public Map<String, Timer> getTimers() {
final Map<String, Timer> timers = new HashMap<>();
for (final Entry<String, com.codahale.metrics.Timer> entry : dwMetricRegistry.getTimers().entrySet()) {
timers.put(entry.getKey(), new KillBillCodahaleTimer(entry.getValue()));
}
return timers;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleCounter.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleCounter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Counter;
public class KillBillCodahaleCounter implements Counter {
private final com.codahale.metrics.Counter dwCounter;
public KillBillCodahaleCounter(final com.codahale.metrics.Counter dwCounter) {
this.dwCounter = dwCounter;
}
@Override
public long getCount() {
return dwCounter.getCount();
}
@Override
public void inc(final long n) {
dwCounter.inc(n);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleMeter.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleMeter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Meter;
public class KillBillCodahaleMeter implements Meter {
private final com.codahale.metrics.Meter dwMeter;
public KillBillCodahaleMeter(final com.codahale.metrics.Meter dwMeter) {
this.dwMeter = dwMeter;
}
@Override
public long getCount() {
return dwMeter.getCount();
}
@Override
public void mark(final long n) {
dwMeter.mark(n);
}
@Override
public double getFifteenMinuteRate() {
return dwMeter.getFifteenMinuteRate();
}
@Override
public double getFiveMinuteRate() {
return dwMeter.getFiveMinuteRate();
}
@Override
public double getMeanRate() {
return dwMeter.getMeanRate();
}
@Override
public double getOneMinuteRate() {
return dwMeter.getOneMinuteRate();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleMetricRegistry.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleMetricRegistry.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.Timer;
public class CodahaleMetricRegistry extends MetricRegistry {
private final org.killbill.commons.metrics.api.MetricRegistry killbillMetricRegistry;
public CodahaleMetricRegistry(final org.killbill.commons.metrics.api.MetricRegistry killbillMetricRegistry) {
this.killbillMetricRegistry = killbillMetricRegistry;
}
@Override
public <T extends Metric> T register(final String name, final T metric) throws IllegalArgumentException {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public void registerAll(final MetricSet metrics) throws IllegalArgumentException {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Counter counter(final String name) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Counter counter(final String name, final MetricSupplier<Counter> supplier) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Histogram histogram(final String name) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Histogram histogram(final String name, final MetricSupplier<Histogram> supplier) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Meter meter(final String name) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Meter meter(final String name, final MetricSupplier<Meter> supplier) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Timer timer(final String name) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Timer timer(final String name, final MetricSupplier<Timer> supplier) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public <T extends Gauge> T gauge(final String name) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public <T extends Gauge> T gauge(final String name, final MetricSupplier<T> supplier) {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public boolean remove(final String name) {
throw new UnsupportedOperationException("Unregister via the Kill Bill MetricRegistry instead");
}
@Override
public void removeMatching(final MetricFilter filter) {
throw new UnsupportedOperationException("Unregister via the Kill Bill MetricRegistry instead");
}
@Override
public SortedSet<String> getNames() {
return Collections.unmodifiableSortedSet(new TreeSet<>(getMetrics().keySet()));
}
@Override
@SuppressWarnings("rawtypes")
public SortedMap<String, Gauge> getGauges() {
return getGauges(MetricFilter.ALL);
}
@Override
@SuppressWarnings("rawtypes")
public SortedMap<String, Gauge> getGauges(final MetricFilter filter) {
return getMetrics(Gauge.class, filter);
}
@Override
public SortedMap<String, Counter> getCounters() {
return getCounters(MetricFilter.ALL);
}
@Override
public SortedMap<String, Counter> getCounters(final MetricFilter filter) {
return getMetrics(Counter.class, filter);
}
@Override
public SortedMap<String, Histogram> getHistograms() {
return getHistograms(MetricFilter.ALL);
}
@Override
public SortedMap<String, Histogram> getHistograms(final MetricFilter filter) {
return getMetrics(Histogram.class, filter);
}
@Override
public SortedMap<String, Meter> getMeters() {
return getMeters(MetricFilter.ALL);
}
@Override
public SortedMap<String, Meter> getMeters(final MetricFilter filter) {
return getMetrics(Meter.class, filter);
}
@Override
public SortedMap<String, Timer> getTimers() {
return getTimers(MetricFilter.ALL);
}
@Override
public SortedMap<String, Timer> getTimers(final MetricFilter filter) {
return getMetrics(Timer.class, filter);
}
@SuppressWarnings("unchecked")
private <T extends Metric> SortedMap<String, T> getMetrics(final Class<T> klass, final MetricFilter filter) {
final TreeMap<String, T> timers = new TreeMap<>();
for (final Map.Entry<String, Metric> entry : getMetrics().entrySet()) {
if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(),
entry.getValue())) {
timers.put(entry.getKey(), (T) entry.getValue());
}
}
return Collections.unmodifiableSortedMap(timers);
}
@Override
public void registerAll(final String prefix, final MetricSet metrics) throws IllegalArgumentException {
throw new UnsupportedOperationException("Register via the Kill Bill MetricRegistry instead");
}
@Override
public Map<String, Metric> getMetrics() {
// Note that we don't cache anything as the Codahale MetricRegistry needs to reflect the Kill Bill one in real time
final ConcurrentMap<String, Metric> dropwizardMap = new ConcurrentHashMap<>();
for (final Entry<String, org.killbill.commons.metrics.api.Counter> entry : killbillMetricRegistry.getCounters().entrySet()) {
dropwizardMap.put(entry.getKey(), new CodahaleCounter(entry.getValue()));
}
for (final Entry<String, org.killbill.commons.metrics.api.Histogram> entry : killbillMetricRegistry.getHistograms().entrySet()) {
dropwizardMap.put(entry.getKey(), new CodahaleHistogram(entry.getValue()));
}
for (final Entry<String, org.killbill.commons.metrics.api.Gauge<?>> entry : killbillMetricRegistry.getGauges().entrySet()) {
dropwizardMap.put(entry.getKey(), new CodahaleGauge(entry.getValue()));
}
for (final Entry<String, org.killbill.commons.metrics.api.Meter> entry : killbillMetricRegistry.getMeters().entrySet()) {
dropwizardMap.put(entry.getKey(), new CodahaleMeter(entry.getValue()));
}
for (final Entry<String, org.killbill.commons.metrics.api.Timer> entry : killbillMetricRegistry.getTimers().entrySet()) {
dropwizardMap.put(entry.getKey(), new CodahaleTimer(entry.getValue()));
}
return dropwizardMap;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleGauge.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleGauge.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Gauge;
public class CodahaleGauge<T> implements com.codahale.metrics.Gauge<T> {
private final Gauge<T> gauge;
public CodahaleGauge(final Gauge<T> gauge) {
this.gauge = gauge;
}
@Override
public T getValue() {
return gauge.getValue();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleMeter.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleMeter.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Meter;
import com.codahale.metrics.Metered;
public class CodahaleMeter implements Metered {
private final Meter meter;
public CodahaleMeter(final Meter meter) {
this.meter = meter;
}
@Override
public long getCount() {
return meter.getCount();
}
@Override
public double getFifteenMinuteRate() {
return meter.getFifteenMinuteRate();
}
@Override
public double getFiveMinuteRate() {
return meter.getFiveMinuteRate();
}
@Override
public double getMeanRate() {
return meter.getMeanRate();
}
@Override
public double getOneMinuteRate() {
return meter.getOneMinuteRate();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleSnapshot.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleSnapshot.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import java.io.OutputStream;
import org.killbill.commons.metrics.api.Snapshot;
public class KillBillCodahaleSnapshot implements Snapshot {
private final com.codahale.metrics.Snapshot dwSnapshot;
public KillBillCodahaleSnapshot(final com.codahale.metrics.Snapshot dwSnapshot) {
this.dwSnapshot = dwSnapshot;
}
@Override
public double getValue(final double quantile) {
return dwSnapshot.getValue(quantile);
}
@Override
public long[] getValues() {
return dwSnapshot.getValues();
}
@Override
public int size() {
return dwSnapshot.size();
}
@Override
public long getMax() {
return dwSnapshot.getMax();
}
@Override
public double getMean() {
return dwSnapshot.getMean();
}
@Override
public long getMin() {
return dwSnapshot.getMin();
}
@Override
public double getStdDev() {
return dwSnapshot.getStdDev();
}
@Override
public void dump(final OutputStream output) {
dwSnapshot.dump(output);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleTimer.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleTimer.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Timer;
import com.codahale.metrics.Metered;
import com.codahale.metrics.Sampling;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.UniformSnapshot;
public class CodahaleTimer implements Metered, Sampling {
private final Timer timer;
public CodahaleTimer(final Timer timer) {
this.timer = timer;
}
@Override
public long getCount() {
return timer.getCount();
}
@Override
public double getFifteenMinuteRate() {
return timer.getFifteenMinuteRate();
}
@Override
public double getFiveMinuteRate() {
return timer.getFiveMinuteRate();
}
@Override
public double getMeanRate() {
return timer.getMeanRate();
}
@Override
public double getOneMinuteRate() {
return timer.getOneMinuteRate();
}
@Override
public Snapshot getSnapshot() {
return new UniformSnapshot(timer.getSnapshot().getValues());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleGauge.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleGauge.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Gauge;
public class KillBillCodahaleGauge<T> implements Gauge<T> {
private final com.codahale.metrics.Gauge<T> dwGauge;
public KillBillCodahaleGauge(final com.codahale.metrics.Gauge<T> dwGauge) {
this.dwGauge = dwGauge;
}
@Override
public T getValue() {
return dwGauge.getValue();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleHistogram.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/CodahaleHistogram.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Histogram;
import com.codahale.metrics.Counting;
import com.codahale.metrics.Metric;
import com.codahale.metrics.Sampling;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.UniformSnapshot;
public class CodahaleHistogram implements Metric, Sampling, Counting {
private final Histogram histogram;
public CodahaleHistogram(final Histogram histogram) {
this.histogram = histogram;
}
@Override
public long getCount() {
return histogram.getCount();
}
@Override
public Snapshot getSnapshot() {
return new UniformSnapshot(histogram.getSnapshot().getValues());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleHistogram.java | metrics/src/main/java/org/killbill/commons/metrics/dropwizard/KillBillCodahaleHistogram.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.dropwizard;
import org.killbill.commons.metrics.api.Histogram;
import org.killbill.commons.metrics.api.Snapshot;
public class KillBillCodahaleHistogram implements Histogram {
private final com.codahale.metrics.Histogram dwHistogram;
public KillBillCodahaleHistogram(final com.codahale.metrics.Histogram dwHistogram) {
this.dwHistogram = dwHistogram;
}
@Override
public long getCount() {
return dwHistogram.getCount();
}
@Override
public void update(final long value) {
dwHistogram.update(value);
}
@Override
public Snapshot getSnapshot() {
return new KillBillCodahaleSnapshot(dwHistogram.getSnapshot());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/modules/StatsModule.java | metrics/src/main/java/org/killbill/commons/metrics/modules/StatsModule.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.modules;
import java.util.Collections;
import java.util.List;
import org.killbill.commons.health.api.HealthCheck;
import org.killbill.commons.health.api.HealthCheckRegistry;
import org.killbill.commons.metrics.health.KillBillHealthCheckRegistry;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
public class StatsModule extends AbstractModule {
private final String healthCheckUri;
private final String metricsUri;
private final String threadsUri;
private final Iterable<Class<? extends HealthCheck>> healthChecks;
public StatsModule() {
this(Collections.emptyList());
}
public StatsModule(final Class<? extends HealthCheck> healthCheck) {
this(List.of(healthCheck));
}
public StatsModule(final Class<? extends HealthCheck>... healthChecks) {
this(List.of(healthChecks));
}
public StatsModule(final Iterable<Class<? extends HealthCheck>> healthChecks) {
this("/1.0/healthcheck", "/1.0/metrics", "/1.0/threads", healthChecks);
}
public StatsModule(final String healthCheckUri,
final String metricsUri,
final String threadsUri,
final Iterable<Class<? extends HealthCheck>> healthChecks) {
this.healthCheckUri = healthCheckUri;
this.metricsUri = metricsUri;
this.threadsUri = threadsUri;
this.healthChecks = healthChecks;
}
@Override
protected void configure() {
final Multibinder<HealthCheck> healthChecksBinder = Multibinder.newSetBinder(binder(), HealthCheck.class);
for (final Class<? extends HealthCheck> healthCheckClass : healthChecks) {
healthChecksBinder.addBinding().to(healthCheckClass).asEagerSingleton();
}
install(new AdminServletModule(healthCheckUri, metricsUri, threadsUri));
bind(HealthCheckRegistry.class).toInstance(createHealthCheckRegistry());
}
/**
* Override to provide a custom {@link HealthCheckRegistry}
*
* @return HealthCheckRegistry instance to bind
*/
protected HealthCheckRegistry createHealthCheckRegistry() {
return new KillBillHealthCheckRegistry();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/metrics/src/main/java/org/killbill/commons/metrics/modules/AdminServletModule.java | metrics/src/main/java/org/killbill/commons/metrics/modules/AdminServletModule.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.metrics.modules;
import org.killbill.commons.metrics.servlets.HealthCheckServlet;
import org.killbill.commons.metrics.servlets.MetricsServlet;
import org.killbill.commons.metrics.servlets.ThreadDumpServlet;
import com.google.inject.servlet.ServletModule;
public class AdminServletModule extends ServletModule {
private final String healthcheckUri;
private final String metricsUri;
private final String threadsUri;
public AdminServletModule(final String healthcheckUri,
final String metricsUri,
final String threadsUri) {
this.healthcheckUri = healthcheckUri;
this.metricsUri = metricsUri;
this.threadsUri = threadsUri;
}
@Override
protected void configureServlets() {
bind(HealthCheckServlet.class).asEagerSingleton();
bind(MetricsServlet.class).asEagerSingleton();
bind(ThreadDumpServlet.class).asEagerSingleton();
serve(healthcheckUri).with(HealthCheckServlet.class);
serve(metricsUri).with(MetricsServlet.class);
serve(threadsUri).with(ThreadDumpServlet.class);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/TestStrings.java | utils/src/test/java/org/killbill/commons/utils/TestStrings.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestStrings {
@DataProvider(name = "testContainsUpperCase")
public Object[][] testContainsUpperCaseData() {
return new Object[][] {
{"this_is_lower_case", false},
{"lower-case-with-dash", false},
{"lower-case-with_number-123", false},
{"lower-case_with_other_char-!@#$", false},
{"ALL_UPPER_CASE", true},
{"lower_UPPER_comBINED", true},
{null, false},
{"", false}
};
}
@Test(groups = "fast", dataProvider = "testContainsUpperCase")
public void testContainsUpperCase(final String sample, final boolean valid) {
Assert.assertEquals(Strings.containsUpperCase(sample), valid);
}
@DataProvider(name = "testToCamelCase")
public Object[][] testToCamelCaseData() {
return new Object[][] {
{"this_is_lower_case", "thisIsLowerCase"},
{"lower-case-with-dash", "lower-case-with-dash"},
{"lower-case-with_number-123", "lower-case-withNumber-123"},
{"lower-case_with_other_char-!@#$", "lower-caseWithOtherChar-!@#$"},
{"ALL_UPPER_CASE", "allUpperCase"},
{"__the_heart_of_life-_John-Mayer__", "theHeartOfLife-John-mayer"}
};
}
@Test(groups = "fast", dataProvider = "testToCamelCase")
public void testToCamelCase(final String sample, final String result) {
final String camelCase = Strings.toCamelCase(sample, false, '_');
// Test compatibility with Guava CaseFormat . Used in LowerToCamelBeanMapper.java
// final String camelCase = com.google.common.base.CaseFormat.LOWER_UNDERSCORE.to(com.google.common.base.CaseFormat.LOWER_CAMEL, sample);
Assert.assertEquals(camelCase, result);
}
@DataProvider(name = "testToSnakeCase")
public Object[][] testToSnakeCaseData() {
return new Object[][] {
{"thisIsASentence", "this_is_a_sentence"},
{"thisIsLowerCase", "this_is_lower_case"},
{"lower-case-with-dash", "lower-case-with-dash"},
{"lower-case-withNumber-123", "lower-case-with_number-123"},
{"lower-caseWithOtherChar-!@#$", "lower-case_with_other_char-!@#$"},
{"theHeartOfLife-John-mayer", "the_heart_of_life-_john-mayer"}
};
}
@Test(groups = "fast", dataProvider = "testToSnakeCase")
public void testToSnakeCase(final String sample, final String result) {
final String snakeCase = Strings.toSnakeCase(sample);
// Test compatibility with Guava CaseFormat . Used in LowerToCamelBeanMapper.java
// final String snakeCase = com.google.common.base.CaseFormat.LOWER_CAMEL.to(com.google.common.base.CaseFormat.LOWER_UNDERSCORE, sample);
Assert.assertEquals(snakeCase, result);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/TestTypeToken.java | utils/src/test/java/org/killbill/commons/utils/TestTypeToken.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestTypeToken {
private static class SuperList extends ArrayList<String> implements List<String>, Collection<String> {}
@Test(groups = "fast")
public void testGetRawTypes() {
Set<Class<?>> types = TypeToken.getRawTypes(Object.class);
Assert.assertEquals(types.size(), 1);
types = TypeToken.getRawTypes(Integer.class);
// class java.lang.Integer, interface java.lang.Comparable, class java.lang.Number, interface java.io.Serializable, class java.lang.Object
// FIXME-1615 : JDK 11 and JDK 17 produce different result.
// Assert.assertEquals(types.size(), 5);
// Guava version: com.google.common.reflect.TypeToken.of(SuperList.class).getTypes().rawTypes() . Size = 11.
types = TypeToken.getRawTypes(SuperList.class);
Assert.assertEquals(types.size(), 11);
types = TypeToken.getRawTypes(String.class);
// class java.lang.String, interface java.lang.Comparable, interface java.io.Serializable, interface java.lang.CharSequence, class java.lang.Object
// FIXME-1615 : JDK 11 and JDK 17 produce different result.
// Assert.assertEquals(types.size(), 5);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/TestMapJoiner.java | utils/src/test/java/org/killbill/commons/utils/TestMapJoiner.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils;
import java.util.Map;
import java.util.TreeMap;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestMapJoiner {
private static final String SEPARATOR = "=";
private static final String KV_SEPARATOR = "&";
private MapJoiner mapJoiner;
@BeforeMethod(groups = "fast")
public void beforeMethod() {
mapJoiner = new MapJoiner(SEPARATOR, KV_SEPARATOR);
}
@Test(groups = "fast")
public void testJoin() {
final Map<String, String> map = Map.of("usa", "washington",
"russia", "moscow",
"france", "paris",
"indonesia", "jakarta");
Assert.assertEquals(mapJoiner.join(new TreeMap<>(map)), "france=paris&indonesia=jakarta&russia=moscow&usa=washington");
}
@Test(groups = "fast")
public void testJoinWithEmptyEntry() {
Map<Object, Object> map = Map.of("", "washington",
"russia", "moscow",
"france", "",
"indonesia", "jakarta");
Assert.assertEquals(mapJoiner.join(new TreeMap<>(map)), "france=&indonesia=jakarta&russia=moscow");
map = Map.of("", false,
"france", "",
"indonesia", "jakarta",
"usa", "");
Assert.assertEquals(mapJoiner.join(new TreeMap<>(map)), "france=&indonesia=jakarta&usa=");
map = Map.of("germany", "berlin",
"france", "",
"indonesia", "");
Assert.assertEquals(mapJoiner.join(new TreeMap<>(map)), "france=&germany=berlin&indonesia=");
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/cache/TestDefaultCache.java | utils/src/test/java/org/killbill/commons/utils/cache/TestDefaultCache.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.cache;
import java.util.function.Function;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDefaultCache {
private static final int DEFAULT_MAX_SIZE = 3;
private DefaultCache<Integer, String> createDefaultCache() {
return new DefaultCache<>(DEFAULT_MAX_SIZE);
}
private DefaultCache<Integer, String> createDefaultCacheWithLoader(final Function<Integer, String> cacheLoader) {
return new DefaultCache<>(DEFAULT_MAX_SIZE, DefaultCache.NO_TIMEOUT, cacheLoader);
}
private DefaultCache<Integer, String> createDefaultCacheWithTimeout(final int timeout) {
return new DefaultCache<>(DEFAULT_MAX_SIZE, timeout, DefaultCache.noCacheLoader());
}
@Test(groups = "fast")
public void testConstructorArgs() {
try {
new DefaultCache<String, String>(0);
Assert.fail("maxSize should > 0");
} catch (final IllegalArgumentException e) {
Assert.assertEquals(e.getMessage(), "cache maxSize should > 0");
}
try {
new DefaultCache<String, String>(1, -1, DefaultCache.noCacheLoader());
} catch (final IllegalArgumentException e) {
Assert.assertEquals(e.getMessage(), "cache timeoutInSecond should >= 0");
}
try {
new DefaultCache<String, String>(1, DefaultCache.NO_TIMEOUT, null);
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "cacheLoader is null. Use DefaultCache#noCacheLoader() to create a cache without loader");
}
}
@Test(groups = "fast")
public void testPut() {
final DefaultCache<Integer, String> cache = createDefaultCache();
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.put(4, "D");
Assert.assertNull(cache.map.get(1)); // null, because maxSize = 3
Assert.assertNotNull(cache.map.get(2));
Assert.assertNotNull(cache.map.get(3));
Assert.assertNotNull(cache.map.get(4));
try {
cache.put(null, "A");
Assert.fail("Should throw NPE because key is null");
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "key in #put() is null");
}
try {
cache.put(5, null);
Assert.fail("Should throw NPE because value is null");
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "value in #put() is null");
}
}
@Test(groups = "fast")
public void testPutWithCacheLoader() {
// Cache loader algorithm should not affected #put() operation.
final DefaultCache<Integer, String> cache = createDefaultCacheWithLoader(key -> {
if (key == 5) {
return "E";
}
return null;
});
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.put(4, "D");
Assert.assertNull(cache.map.get(1));
Assert.assertNotNull(cache.map.get(2));
Assert.assertNotNull(cache.map.get(3));
Assert.assertNotNull(cache.map.get(4));
Assert.assertNull(cache.map.get(5)); // cache loader not playing a role here
}
@Test(groups = "fast")
public void testPutWithTimeout() throws InterruptedException {
final DefaultCache<Integer, String> cache = createDefaultCacheWithTimeout(2); // 2 sec
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.put(4, "D");
Assert.assertNull(cache.map.get(1));
Assert.assertNotNull(cache.map.get(2));
Assert.assertNotNull(cache.map.get(3));
Assert.assertNotNull(cache.map.get(4));
Thread.sleep(2100);
// call put here to trigger eviction
cache.put(5, "E");
Assert.assertNotNull(cache.map.get(5));
cache.get(2); // Needed to trigger eviction
cache.get(3); // Needed to trigger eviction
cache.get(4); // Needed to trigger eviction
Assert.assertNull(cache.map.get(2));
Assert.assertNull(cache.map.get(3));
Assert.assertNull(cache.map.get(4));
}
@Test(groups = "fast")
public void testGet() {
final DefaultCache<Integer, String> cache = createDefaultCache();
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.put(4, "D");
Assert.assertNull(cache.get(1)); // removed because eldest entry
Assert.assertNotNull(cache.get(2));
Assert.assertNotNull(cache.get(3));
Assert.assertNotNull(cache.get(4));
try {
cache.get(null);
Assert.fail("Should throw NPE because key is null");
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "Cannot #get() cache with key = null");
}
}
@Test(groups = "fast")
public void testGetWithLoader() {
final DefaultCache<Integer, String> cache = createDefaultCacheWithLoader(key -> {
switch (key) {
case 5: return "E";
case 6: return "F";
}
return null;
});
cache.put(1, "A");
cache.put(2, "B");
Assert.assertNotNull(cache.get(1));
Assert.assertNotNull(cache.get(2));
Assert.assertEquals(cache.map.size(), 2); // map size not affected by loader, yet
Assert.assertNotNull(cache.get(5));
Assert.assertNotNull(cache.get(6));
Assert.assertEquals(cache.map.size(), 3); // map size affected by loader, but "3" (instead of 4) because maxSize = 3.
}
@Test(groups = "fast")
public void testGetWithTimeout() throws InterruptedException {
final DefaultCache<Integer, String> cache = createDefaultCacheWithTimeout(1);
cache.put(1, "A");
cache.put(2, "B");
Assert.assertNotNull(cache.get(1));
Assert.assertNotNull(cache.get(2));
Assert.assertNull(cache.get(3));
Thread.sleep(1010);
// 2, because although expired, there's no operation that removed entry, performed
Assert.assertEquals(cache.map.size(), 2);
// Calling get will remove entry
Assert.assertNull(cache.get(1)); // null because expired
Assert.assertNull(cache.get(2)); // null because expired
Assert.assertNull(cache.get(3));
Assert.assertEquals(cache.map.size(), 0); // All expired
cache.put(1, "A");
cache.put(2, "B");
Assert.assertEquals(cache.map.size(), 2);
Thread.sleep(1010);
cache.put(1, "A");
cache.get(2); // Needed to trigger eviction
Assert.assertEquals(cache.map.size(), 1); // Because expired
}
@Test(groups = "fast")
public void testGetOrLoad() {
final DefaultCache<Integer, String> cache = createDefaultCache();
final Function<Integer, String> loader = key -> key + "00";
cache.put(1, "A");
cache.put(2, "B");
Assert.assertEquals(cache.getOrLoad(1, loader), "A");
Assert.assertEquals(cache.getOrLoad(2, loader), "B");
Assert.assertEquals(cache.getOrLoad(3, loader), "300");
Assert.assertNotNull(cache.getOrLoad(1, key -> null));
Assert.assertNotNull(cache.getOrLoad(2, key -> null));
try {
cache.getOrLoad(null, loader);
Assert.fail("Should throw NPE because key is null");
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "Cannot #get() cache with key = null");
}
try {
cache.getOrLoad(5, null);
Assert.fail("Should throw NPE because loader is null");
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "loader parameter in #getOrLoad() is null");
}
}
@Test(groups = "fast")
public void testGetOrLoadWithLoader() {
final DefaultCache<Integer, String> cache = createDefaultCacheWithLoader(key -> {
switch (key) {
case 3: return "C";
case 4: return "D";
}
return null;
});
final Function<Integer, String> localLoader = key -> {
switch (key) {
case 5: return "E";
case 6: return "F";
/*
* Should never showing up, as per {@link DefaultCache} javadoc: ".... cacheLoader also will take
* precedence over loader defined in getOrLoad(Object, Function)."
*/
case 4: return "D-override";
}
return null;
};
cache.put(1, "A");
cache.put(2, "B");
Assert.assertEquals(cache.getOrLoad(1, localLoader), "A");
Assert.assertEquals(cache.getOrLoad(2, localLoader), "B");
Assert.assertEquals(cache.map.size(), 2); // 2, because DefaultCache loader "load lazily"
Assert.assertEquals(cache.getOrLoad(3, localLoader), "C");
Assert.assertEquals(cache.getOrLoad(4, localLoader), "D");
// 3, because DefaultCache loader loaded, but when key '4' added, cache reach max size ....
Assert.assertEquals(cache.map.size(), 3);
// .... and thus 1 get removed
Assert.assertNull(cache.getOrLoad(1, localLoader));
Assert.assertEquals(cache.getOrLoad(5, localLoader), "E");
Assert.assertEquals(cache.getOrLoad(6, localLoader), "F");
Assert.assertEquals(cache.map.size(), 3); // still 3 because localLoader not affected cache.
Assert.assertNull(cache.getOrLoad(7, localLoader)); // null because 7 not defined everywhere
}
@Test(groups = "fast")
public void testGetOrLoadWithTimeout() throws InterruptedException {
final DefaultCache<Integer, String> cache = createDefaultCacheWithTimeout(1);
final Function<Integer, String> localLoader = key -> {
switch (key) {
case 3: return "C";
case 4: return "D";
}
return null;
};
cache.put(1, "A");
cache.put(2, "B");
Assert.assertEquals(cache.getOrLoad(1, localLoader), "A");
Assert.assertEquals(cache.getOrLoad(2, localLoader), "B");
Assert.assertEquals(cache.getOrLoad(3, localLoader), "C");
Thread.sleep(1010);
// 2, because although timeout, there's no operation that removed entry, performed
// Also 2, because "localLoader" not added to cache
Assert.assertEquals(cache.map.size(), 2);
// Calling get will remove entry
Assert.assertNull(cache.getOrLoad(1, localLoader)); // null because expired
Assert.assertNull(cache.getOrLoad(2, localLoader)); // null because expired
Assert.assertEquals(cache.getOrLoad(3, localLoader), "C");
Assert.assertEquals(cache.getOrLoad(4, localLoader), "D");
Assert.assertEquals(cache.map.size(), 0); // All expired
cache.put(1, "A");
cache.put(2, "B");
Assert.assertEquals(cache.map.size(), 2);
Thread.sleep(1010);
cache.put(1, "A");
cache.get(2); // Needed to trigger eviction
Assert.assertEquals(cache.map.size(), 1); // Because expired
}
@Test(groups = "fast")
public void testInvalidate() {
final DefaultCache<Integer, String> cache = createDefaultCacheWithTimeout(1);
cache.put(1, "A");
cache.put(2, "B");
cache.invalidate(1);
Assert.assertEquals(cache.map.size(), 1);
try {
cache.invalidate(null);
Assert.fail("Cannot invalidate with null key");
} catch (final NullPointerException e) {
Assert.assertEquals(e.getMessage(), "Cannot invalidate. Cache with null key is not allowed");
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/concurrent/TestThreadFactoryBuilder.java | utils/src/test/java/org/killbill/commons/utils/concurrent/TestThreadFactoryBuilder.java | /*
* Copyright (C) 2010 The Guava Authors
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.concurrent;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestThreadFactoryBuilder {
private final Runnable monitoredRunnable = () -> completed = true;
private static final UncaughtExceptionHandler UNCAUGHT_EXCEPTION_HANDLER =
new UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
// No-op
}
};
private ThreadFactoryBuilder builder;
private volatile boolean completed = false;
@BeforeMethod(groups = "fast")
public void setUp() {
builder = new ThreadFactoryBuilder();
completed = false;
}
@Test(groups = "fast")
public void testThreadFactoryBuilder_defaults() throws InterruptedException {
final ThreadFactory threadFactory = builder.build();
final Thread thread = threadFactory.newThread(monitoredRunnable);
checkThreadPoolName(thread, 1);
final Thread defaultThread = Executors.defaultThreadFactory().newThread(monitoredRunnable);
Assert.assertEquals(defaultThread.isDaemon(), thread.isDaemon());
Assert.assertEquals(defaultThread.getPriority(), thread.getPriority());
Assert.assertSame(defaultThread.getThreadGroup(), thread.getThreadGroup());
Assert.assertSame(defaultThread.getUncaughtExceptionHandler(), thread.getUncaughtExceptionHandler());
Assert.assertFalse(completed);
thread.start();
thread.join();
Assert.assertTrue(completed);
// Creating a new thread from the same ThreadFactory will have the same
// pool ID but a thread ID of 2.
final Thread thread2 = threadFactory.newThread(monitoredRunnable);
checkThreadPoolName(thread2, 2);
Assert.assertEquals(
thread.getName().substring(0, thread.getName().lastIndexOf('-')),
thread2.getName().substring(0, thread.getName().lastIndexOf('-')));
// Building again should give us a different pool ID.
final ThreadFactory threadFactory2 = builder.build();
final Thread thread3 = threadFactory2.newThread(monitoredRunnable);
checkThreadPoolName(thread3, 1);
Assert.assertNotEquals(thread2.getName().substring(0, thread.getName().lastIndexOf('-')),
thread3.getName().substring(0, thread.getName().lastIndexOf('-')));
}
private static void checkThreadPoolName(final Thread thread, final int threadId) {
Assert.assertTrue(thread.getName().matches("^pool-\\d+-thread-" + threadId + "$"));
}
@Test(groups = "fast")
public void testNameFormatWithPercentS_custom() {
final String format = "super-duper-thread-%s";
final ThreadFactory factory = builder.setNameFormat(format).build();
for (int i = 0; i < 11; i++) {
Assert.assertEquals(rootLocaleFormat(format, i), factory.newThread(monitoredRunnable).getName());
}
}
@Test(groups = "fast")
public void testNameFormatWithPercentD_custom() {
final String format = "super-duper-thread-%d";
final ThreadFactory factory = builder.setNameFormat(format).build();
for (int i = 0; i < 11; i++) {
Assert.assertEquals(rootLocaleFormat(format, i), factory.newThread(monitoredRunnable).getName());
}
}
@Test(groups = "fast")
public void testDaemon_false() {
final ThreadFactory factory = builder.setDaemon(false).build();
final Thread thread = factory.newThread(monitoredRunnable);
Assert.assertFalse(thread.isDaemon());
}
@Test(groups = "fast")
public void testDaemon_true() {
final ThreadFactory factory = builder.setDaemon(true).build();
final Thread thread = factory.newThread(monitoredRunnable);
Assert.assertTrue(thread.isDaemon());
}
@Test(groups = "fast")
public void testPriority_custom() {
for (int i = Thread.MIN_PRIORITY; i <= Thread.MAX_PRIORITY; i++) {
final ThreadFactory factory = builder.setPriority(i).build();
final Thread thread = factory.newThread(monitoredRunnable);
Assert.assertEquals(i, thread.getPriority());
}
}
@Test(groups = "fast")
public void testPriority_tooLow() {
try {
builder.setPriority(Thread.MIN_PRIORITY - 1);
Assert.fail();
} catch (final IllegalArgumentException expected) {
}
}
@Test(groups = "fast")
public void testPriority_tooHigh() {
try {
builder.setPriority(Thread.MAX_PRIORITY + 1);
Assert.fail();
} catch (final IllegalArgumentException expected) {
}
}
@Test(groups = "fast")
public void testUncaughtExceptionHandler_custom() {
Assert.assertEquals(
UNCAUGHT_EXCEPTION_HANDLER,
builder
.setUncaughtExceptionHandler(UNCAUGHT_EXCEPTION_HANDLER)
.build()
.newThread(monitoredRunnable)
.getUncaughtExceptionHandler());
}
@Test(groups = "fast")
public void testBuildMutateBuild() {
final ThreadFactory factory1 = builder.setPriority(1).build();
Assert.assertEquals(1, factory1.newThread(monitoredRunnable).getPriority());
final ThreadFactory factory2 = builder.setPriority(2).build();
Assert.assertEquals(1, factory1.newThread(monitoredRunnable).getPriority());
Assert.assertEquals(2, factory2.newThread(monitoredRunnable).getPriority());
}
@Test(groups = "fast")
public void testBuildTwice() {
ThreadFactory unused;
unused = builder.build(); // this is allowed
unused = builder.build(); // this is *also* allowed
}
@Test(groups = "fast")
public void testBuildMutate() {
final ThreadFactory factory1 = builder.setPriority(1).build();
Assert.assertEquals(1, factory1.newThread(monitoredRunnable).getPriority());
builder.setPriority(2); // change the state of the builder
Assert.assertEquals(1, factory1.newThread(monitoredRunnable).getPriority());
}
@Test(groups = "fast")
public void testThreadFactory() throws InterruptedException {
final String THREAD_NAME = "ludicrous speed";
final int THREAD_PRIORITY = 1;
final boolean THREAD_DAEMON = false;
final ThreadFactory backingThreadFactory =
new ThreadFactory() {
@Override
public Thread newThread(final Runnable r) {
final Thread thread = new Thread(r);
thread.setName(THREAD_NAME);
thread.setPriority(THREAD_PRIORITY);
thread.setDaemon(THREAD_DAEMON);
thread.setUncaughtExceptionHandler(UNCAUGHT_EXCEPTION_HANDLER);
return thread;
}
};
final Thread thread = builder.setThreadFactory(backingThreadFactory).build().newThread(monitoredRunnable);
Assert.assertEquals(THREAD_NAME, thread.getName());
Assert.assertEquals(THREAD_PRIORITY, thread.getPriority());
Assert.assertEquals(THREAD_DAEMON, thread.isDaemon());
Assert.assertSame(UNCAUGHT_EXCEPTION_HANDLER, thread.getUncaughtExceptionHandler());
Assert.assertSame(Thread.State.NEW, thread.getState());
Assert.assertFalse(completed);
thread.start();
thread.join();
Assert.assertTrue(completed);
}
private static String rootLocaleFormat(final String format, final Object... args) {
return String.format(Locale.ROOT, format, args);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/collect/TestIterables.java | utils/src/test/java/org/killbill/commons/utils/collect/TestIterables.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.collect;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public class TestIterables {
@Test(groups = "fast")
public void testGetLast() {
final List<KeyValue> keyValues = List.of(new KeyValue("a", "1"), new KeyValue("b", "2"), new KeyValue("c", "3"));
final KeyValue last = Iterables.getLast(keyValues);
assertNotNull(last);
assertEquals(last.getKey(), "c");
assertEquals(last.getValue(), "3");
}
@Test(groups = "fast")
public void testGetLastWithEmptyList() {
final List<KeyValue> keyValues = Collections.emptyList();
try {
Iterables.getLast(keyValues);
fail("iterable is empty");
} catch (final NoSuchElementException ignored) {}
}
@Test(groups = "fast")
public void testConcat() {
final Iterable<String> a = List.of("a", "b", "c");
final Iterable<String> b = List.of("d", "e");
final Iterable<String> c = List.of("1", "2", "3");
final Iterable<String> result = Iterables.concat(a, b, c);
assertNotNull(result);
assertEquals(Iterators.size(result.iterator()), 8);
}
@Test(groups = "fast")
public void testConcatWithNullElement() {
final Iterable<String> a = List.of("a", "b", "c");
final Iterable<String> b = List.of("1", "2", "3");
try {
Iterables.concat(a, null, b);
fail("One of iterable element is null");
} catch (NullPointerException ignored) {}
}
@Test(groups = "fast")
public void testIsEmpty() {
final Iterable<String> a = List.of("a", "b", "c");
final Iterable<String> b = Collections.emptyList();
assertFalse(Iterables.isEmpty(a));
assertTrue(Iterables.isEmpty(b));
}
@Test(groups = "fast")
public void testSize() {
final Iterable<String> a = List.of("a", "b", "c");
final Iterable<String> b = Collections.emptyList();
assertEquals(Iterables.size(a), 3);
assertEquals(Iterables.size(b), 0);
}
@Test(groups = "fast")
public void testContains() {
final Iterable<String> strings = List.of("a", "b", "c");
final Iterable<String> empty = Collections.emptyList();
final Iterable<KeyValue> keyValues = List.of(new KeyValue("a", "1"),
new KeyValue("b", "2"));
assertTrue(Iterables.contains(strings, "a"));
assertFalse(Iterables.contains(strings, "d"));
assertFalse(Iterables.contains(empty, "a"));
assertTrue(Iterables.contains(keyValues, new KeyValue("b", "2")));
assertFalse(Iterables.contains(keyValues, new KeyValue("a", "2")));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/collect/TestMultiValueHashMap.java | utils/src/test/java/org/killbill/commons/utils/collect/TestMultiValueHashMap.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.collect;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
public class TestMultiValueHashMap {
@Test(groups = "fast")
public void putElement() {
final MultiValueMap<String, KeyValue> multiValueMap = new MultiValueHashMap<>();
multiValueMap.putElement("one", new KeyValue("a", "A"));
multiValueMap.putElement("two", new KeyValue("b", "B"), new KeyValue("c", "C"));
assertEquals(multiValueMap.size(), 2);
assertEquals(multiValueMap.get("one").size(), 1);
assertEquals(multiValueMap.get("two").size(), 2);
multiValueMap.putElement("two", new KeyValue("c", "C")); // same element, to prove that values size will keep increase.
assertEquals(multiValueMap.size(), 2); // The MultiValueMap's size() itself remaining the same ....
assertEquals(multiValueMap.get("two").size(), 3); // .... But the value elements is up-to-date.
}
@Test(groups = "fast")
public void putElementThenThrowIllegalArgs() {
final MultiValueMap<String, KeyValue> multiValueMap = new MultiValueHashMap<>();
try {
multiValueMap.putElement("one", (KeyValue[]) null);
fail("IllegalArgumentException should be thrown because null element");
} catch (final IllegalArgumentException ignored) {}
try {
multiValueMap.putElement("one");
fail("IllegalArgumentException should be thrown because empty element");
} catch (final IllegalArgumentException ignored) {}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/collect/KeyValue.java | utils/src/test/java/org/killbill/commons/utils/collect/KeyValue.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.collect;
import java.util.Objects;
class KeyValue {
private final String key;
private final String value;
public KeyValue(final String key, final String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final KeyValue keyValue = (KeyValue) o;
return key.equals(keyValue.key) && value.equals(keyValue.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/collect/TestIterators.java | utils/src/test/java/org/killbill/commons/utils/collect/TestIterators.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.collect;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public class TestIterators {
@Test(groups = "fast")
public void testGetLast() {
final List<KeyValue> keyValues = List.of(new KeyValue("a", "1"), new KeyValue("b", "2"), new KeyValue("c", "3"));
final KeyValue last = Iterators.getLast(keyValues.iterator());
assertNotNull(last);
assertEquals(last.getKey(), "c");
assertEquals(last.getValue(), "3");
}
@Test(groups = "fast")
public void testGetLastWithEmptyList() {
final List<KeyValue> keyValues = Collections.emptyList();
try {
Iterators.getLast(keyValues.iterator());
fail("iterator is empty");
} catch (final NoSuchElementException ignored) {}
}
@Test(groups = "fast")
public void testTransform() {
final List<KeyValue> list = List.of(new KeyValue("a", "1"), new KeyValue("b", "2"), new KeyValue("c", "3"));
final Iterator<String> keyOnly = Iterators.transform(list.iterator(), KeyValue::getKey);
assertEquals(keyOnly.next(), "a");
assertEquals(keyOnly.next(), "b");
assertEquals(keyOnly.next(), "c");
}
@Test(groups = "fast")
public void testToUnmodifiableList() {
final Collection<KeyValue> set = new HashSet<>();
set.add(new KeyValue("a", "1"));
set.add(new KeyValue("b", "2"));
set.add(new KeyValue("b", "2")); // Duplicate. Note that Set.of cannot add duplicate element (IllegalArgumentException: duplicate element)
final List<KeyValue> list = Iterators.toUnmodifiableList(set.iterator());
assertNotNull(list);
assertEquals(list.size(), 2);
assertTrue(list.contains(new KeyValue("a", "1")));
assertTrue(list.contains(new KeyValue("b", "2")));
}
@Test(groups = "fast")
public void testSize() {
final List<String> strings = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
final int size = Iterators.size(strings.iterator());
assertEquals(size, 10);
}
@Test(groups = "fast")
public void testContains() {
final Iterator<String> strings = List.of("a", "b", "c").iterator();
final Iterator<String> empty = Collections.emptyIterator();
final Iterator<KeyValue> keyValues = List.of(new KeyValue("a", "1"),
new KeyValue("b", "2"))
.iterator();
assertTrue(Iterators.contains(strings, "a"));
assertFalse(Iterators.contains(strings, "d"));
assertFalse(Iterators.contains(empty, "a"));
assertTrue(Iterators.contains(keyValues, new KeyValue("b", "2")));
assertFalse(Iterators.contains(keyValues, new KeyValue("a", "2")));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/collect/TestEvictingQueue.java | utils/src/test/java/org/killbill/commons/utils/collect/TestEvictingQueue.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.collect;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestEvictingQueue {
private static final int MAX_SIZE = 100;
private EvictingQueue<Integer> createEvictingQueue() {
final EvictingQueue<Integer> result = new EvictingQueue<>(MAX_SIZE);
for (int i = 0; i < (MAX_SIZE - 3); i++) {
result.add(i);
}
return result;
}
@Test(groups = "fast", description = "Test several methods to make it more useful")
public void testAddPeekSizeContains() {
final EvictingQueue<Integer> evictingQueue = createEvictingQueue();
Assert.assertEquals(evictingQueue.peek(), 0);
evictingQueue.add(201);
Assert.assertEquals(evictingQueue.size(), 98);
Assert.assertEquals(evictingQueue.peek(), 0); // Peek keep 0 (not reached limit)
Assert.assertTrue(evictingQueue.contains(0));
Assert.assertTrue(evictingQueue.contains(1));
evictingQueue.add(202);
evictingQueue.add(203);
Assert.assertEquals(evictingQueue.size(), MAX_SIZE);
Assert.assertEquals(evictingQueue.peek(), 0); // Peek keep 0 (not reached limit)
Assert.assertTrue(evictingQueue.contains(0));
Assert.assertTrue(evictingQueue.contains(1));
evictingQueue.add(204);
evictingQueue.add(205);
Assert.assertEquals(evictingQueue.size(), MAX_SIZE);
Assert.assertEquals(evictingQueue.peek(), 2); // (reach limit peek changes)
Assert.assertFalse(evictingQueue.contains(0));
Assert.assertFalse(evictingQueue.contains(1));
Assert.assertTrue(evictingQueue.contains(2));
Assert.assertTrue(evictingQueue.contains(3));
evictingQueue.add(206);
evictingQueue.add(207);
Assert.assertEquals(evictingQueue.size(), MAX_SIZE);
Assert.assertEquals(evictingQueue.peek(), 4); // (reach limit peek changes)
Assert.assertFalse(evictingQueue.contains(2));
Assert.assertFalse(evictingQueue.contains(3));
Assert.assertTrue(evictingQueue.contains(4));
Assert.assertTrue(evictingQueue.contains(5));
}
@Test(groups = "fast")
public void testRemainingCapacity() {
final EvictingQueue<Integer> evictingQueue = createEvictingQueue();
evictingQueue.add(201);
Assert.assertEquals(evictingQueue.remainingCapacity(), 2);
evictingQueue.add(202);
Assert.assertEquals(evictingQueue.remainingCapacity(), 1);
evictingQueue.add(203);
Assert.assertEquals(evictingQueue.remainingCapacity(), 0);
evictingQueue.clear();
Assert.assertEquals(evictingQueue.remainingCapacity(), 100);
}
@Test(groups = "fast")
public void testAddAll() {
final EvictingQueue<Integer> evictingQueue = createEvictingQueue();
evictingQueue.addAll(List.of(201, 202));
Assert.assertEquals(evictingQueue.size(), 99);
Assert.assertEquals(evictingQueue.remainingCapacity(), 1);
evictingQueue.add(100);
Assert.assertEquals(evictingQueue.size(), 100);
Assert.assertEquals(evictingQueue.remainingCapacity(), 0);
evictingQueue.addAll(List.of(204, 205, 206));
Assert.assertEquals(evictingQueue.size(), 100);
Assert.assertEquals(evictingQueue.remainingCapacity(), 0);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/utils/collect/TestSets.java | utils/src/test/java/org/killbill/commons/utils/collect/TestSets.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils.collect;
import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestSets {
@Test(groups = "fast")
public void testDifference() {
final Set<String> s1 = Set.of("a", "b", "c", "d", "e");
final Set<String> s2 = Set.of("a", "c", "d");
final Set<String> diff = Sets.difference(s1, s2);
Assert.assertEquals(diff.size(), 2);
Assert.assertEquals(diff, Set.of("b", "e"));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.