proj_name stringclasses 131
values | relative_path stringlengths 30 228 | class_name stringlengths 1 68 | func_name stringlengths 1 48 | masked_class stringlengths 78 9.82k | func_body stringlengths 46 9.61k | len_input int64 29 2.01k | len_output int64 14 1.94k | total int64 55 2.05k | relevant_context stringlengths 0 38.4k |
|---|---|---|---|---|---|---|---|---|---|
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/concurrency/WorkQueue.java | WorkUnitWrapper | runWorkQueue | class WorkUnitWrapper<T> {
/** The work unit. */
final T workUnit;
/**
* Constructor.
*
* @param workUnit
* the work unit, or null to represent a poison pill.
*/
public WorkUnitWrapper(final T workUnit) {
this.workUnit... |
if (elements.isEmpty()) {
// Nothing to do
return;
}
// WorkQueue#close() is called when this try-with-resources block terminates, initiating a barrier wait
// while all worker threads complete.
try (WorkQueue<U> workQueue = new WorkQueue<>(elements, work... | 540 | 212 | 752 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/fastzipfilereader/NestedJarHandler.java | RecyclableInflater | openInflaterInputStream | class RecyclableInflater implements Resettable, AutoCloseable {
/**
* Create a new {@link Inflater} instance with the "nowrap" option (which is needed for zipfile entries).
*/
private final Inflater inflater = new Inflater(/* nowrap = */ true);
/**
* Get the {@link In... |
return new InputStream() {
// Gen Inflater instance with nowrap set to true (needed by zip entries)
private final RecyclableInflater recyclableInflater = inflaterRecycler.acquire();
private final Inflater inflater = recyclableInflater.getInflater();
private final... | 362 | 1,292 | 1,654 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/fastzipfilereader/PhysicalZipFile.java | PhysicalZipFile | equals | class PhysicalZipFile {
/** The {@link Path} backing this {@link PhysicalZipFile}, if any. */
private Path path;
/** The {@link File} backing this {@link PhysicalZipFile}, if any. */
private File file;
/** The path to the zipfile. */
private final String pathStr;
/** The {@link Slice} for... |
if (o == this) {
return true;
} else if (!(o instanceof PhysicalZipFile)) {
return false;
}
final PhysicalZipFile other = (PhysicalZipFile) o;
return Objects.equals(file, other.file);
| 1,727 | 72 | 1,799 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/fileslice/ArraySlice.java | ArraySlice | slice | class ArraySlice extends Slice {
/** The wrapped byte array. */
public byte[] arr;
/**
* Constructor for treating a range of an array as a slice.
*
* @param parentSlice
* the parent slice
* @param offset
* the offset of the sub-slice within the parent sli... |
if (this.isDeflatedZipEntry) {
throw new IllegalArgumentException("Cannot slice a deflated zip entry");
}
return new ArraySlice(this, offset, length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
| 1,061 | 67 | 1,128 | <methods>public void close() throws java.io.IOException,public boolean equals(java.lang.Object) ,public int hashCode() ,public abstract byte[] load() throws java.io.IOException,public java.lang.String loadAsString() throws java.io.IOException,public java.io.InputStream open() throws java.io.IOException,public java.io.I... |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/fileslice/reader/RandomAccessArrayReader.java | RandomAccessArrayReader | read | class RandomAccessArrayReader implements RandomAccessReader {
/** The array. */
private final byte[] arr;
/** The start index of the slice within the array. */
private final int sliceStartPos;
/** The length of the slice within the array. */
private final int sliceLength;
/**
* Const... |
if (numBytes == 0) {
return 0;
}
if (srcOffset < 0L || numBytes < 0 || numBytes > sliceLength - srcOffset) {
throw new IOException("Read index out of bounds");
}
try {
final int numBytesToRead = Math.max(Math.min(numBytes, dstBuf.capacity() - ... | 1,208 | 242 | 1,450 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/fileslice/reader/RandomAccessByteBufferReader.java | RandomAccessByteBufferReader | read | class RandomAccessByteBufferReader implements RandomAccessReader {
/** The byte buffer. */
private final ByteBuffer byteBuffer;
/** The slice start pos. */
private final int sliceStartPos;
/** The slice length. */
private final int sliceLength;
/**
* Constructor.
*
* @param... |
if (numBytes == 0) {
return 0;
}
if (srcOffset < 0L || numBytes < 0 || numBytes > sliceLength - srcOffset) {
throw new IOException("Read index out of bounds");
}
try {
final int numBytesToRead = Math.max(Math.min(numBytes, dstBuf.capacity() - ... | 1,104 | 279 | 1,383 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/fileslice/reader/RandomAccessFileChannelReader.java | RandomAccessFileChannelReader | readLong | class RandomAccessFileChannelReader implements RandomAccessReader {
/** The file channel. */
private final FileChannel fileChannel;
/** The slice start pos. */
private final long sliceStartPos;
/** The slice length. */
private final long sliceLength;
/** The reusable byte buffer. */
... |
if (read(offset, scratchByteBuf, 0, 8) < 8) {
throw new IOException("Premature EOF");
}
return ((scratchArr[7] & 0xffL) << 56) //
| ((scratchArr[6] & 0xffL) << 48) //
| ((scratchArr[5] & 0xffL) << 40) //
| ((scratchArr[4] & 0xffL) << 3... | 1,495 | 217 | 1,712 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/json/ClassFieldCache.java | NoConstructor | getDefaultConstructorForConcreteTypeOf | class NoConstructor {
/** Constructor for NoConstructor class. */
@SuppressWarnings("unused")
public NoConstructor() {
// Empty
}
}
/**
* Create a class field cache.
*
* @param forDeserialization
* Set this to true if the cache will be... |
if (cls == null) {
throw new IllegalArgumentException("Class reference cannot be null");
}
// Check cache
final Constructor<?> constructor = defaultConstructorForConcreteType.get(cls);
if (constructor != null) {
return constructor;
}
final... | 1,158 | 273 | 1,431 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/json/JSONArray.java | JSONArray | toJSONString | class JSONArray {
/** Array items. */
List<Object> items;
/**
* Constructor.
*/
public JSONArray() {
items = new ArrayList<>();
}
/**
* Constructor.
*
* @param items
* the items
*/
public JSONArray(final List<Object> items) {
th... |
final boolean prettyPrint = indentWidth > 0;
final int n = items.size();
if (n == 0) {
buf.append("[]");
} else {
buf.append('[');
if (prettyPrint) {
buf.append('\n');
}
for (int i = 0; i < n; i++) {
... | 278 | 252 | 530 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/json/JSONObject.java | JSONObject | toJSONString | class JSONObject {
/** Key/value mappings, in display order. */
List<Entry<String, Object>> items;
/** Object id for cross-references, if known. */
CharSequence objectId;
/**
* Constructor.
*
* @param sizeHint
* the size hint
*/
public JSONObject(final int s... |
final boolean prettyPrint = indentWidth > 0;
final int n = items.size();
int numDisplayedFields;
if (includeNullValuedFields) {
numDisplayedFields = n;
} else {
numDisplayedFields = 0;
for (final Entry<String, Object> item : items) {
... | 344 | 687 | 1,031 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/json/ParameterizedTypeImpl.java | ParameterizedTypeImpl | equals | class ParameterizedTypeImpl implements ParameterizedType {
/** The actual type arguments. */
private final Type[] actualTypeArguments;
/** The raw type. */
private final Class<?> rawType;
/** The owner type. */
private final Type ownerType;
/** The type parameters of {@link Map} instance... |
if (obj == this) {
return true;
} else if (!(obj instanceof ParameterizedType)) {
return false;
}
final ParameterizedType other = (ParameterizedType) obj;
return Objects.equals(ownerType, other.getOwnerType()) && Objects.equals(rawType, other.getRawType()... | 1,005 | 107 | 1,112 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/json/ReferenceEqualityKey.java | ReferenceEqualityKey | hashCode | class ReferenceEqualityKey<K> {
/** The wrapped key. */
private final K wrappedKey;
/**
* Constructor.
*
* @param wrappedKey
* the wrapped key
*/
public ReferenceEqualityKey(final K wrappedKey) {
this.wrappedKey = wrappedKey;
}
/**
* Get the wr... |
final K key = wrappedKey;
// Don't call key.hashCode(), because that can be an expensive (deep) hashing method,
// e.g. for ByteBuffer, it is based on the entire contents of the buffer
return key == null ? 0 : System.identityHashCode(key);
| 437 | 76 | 513 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/json/TypeResolutions.java | TypeResolutions | resolveTypeVariables | class TypeResolutions {
/** The type variables. */
private final TypeVariable<?>[] typeVariables;
/** The resolved type arguments. */
Type[] resolvedTypeArguments;
/**
* Produce a list of type variable resolutions from a resolved type, by comparing its actual type parameters
* with the ... |
if (type instanceof Class<?>) {
// Arrays and non-generic classes have no type variables
return type;
} else if (type instanceof ParameterizedType) {
// Recursively resolve parameterized types
final ParameterizedType parameterizedType = (ParameterizedTyp... | 453 | 923 | 1,376 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/recycler/Recycler.java | Recycler | acquire | class Recycler<T, E extends Exception> implements AutoCloseable {
/** Instances that have been allocated. */
private final Set<T> usedInstances = Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());
/** Instances that have been allocated but are unused. */
private final Queue<T> unusedInstan... |
final T instance;
final T recycledInstance = unusedInstances.poll();
if (recycledInstance == null) {
// Allocate a new instance -- may throw an exception of type E
final T newInstance = newInstance();
if (newInstance == null) {
throw new NullP... | 1,056 | 140 | 1,196 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/reflection/JVMDriverReflectionDriver.java | JVMDriverReflectionDriver | makeAccessible | class JVMDriverReflectionDriver extends ReflectionDriver {
private Object driver;
private final Method getDeclaredMethods;
private final Method getDeclaredConstructors;
private final Method getDeclaredFields;
private final Method getField;
private final Method setField;
private final Method ... |
try {
setAccessibleMethod.invoke(driver, accessibleObject, true);
} catch (final Throwable t) {
return false;
}
return true;
| 1,725 | 48 | 1,773 | <methods><variables>private static java.lang.reflect.Method canAccessMethod,private final SingletonMap<Class<?>,nonapi.io.github.classgraph.reflection.ReflectionDriver.ClassMemberCache,java.lang.Exception> classToClassMemberCache,private static java.lang.reflect.Method isAccessibleMethod |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/reflection/StandardReflectionDriver.java | PrivilegedActionInvocationHandler | tryMakeAccessible | class PrivilegedActionInvocationHandler<T> implements InvocationHandler {
private final Callable<T> callable;
public PrivilegedActionInvocationHandler(final Callable<T> callable) {
this.callable = callable;
}
@Override
public Object invoke(final Object proxy, final ... |
if (trySetAccessibleMethod != null) {
// JDK 9+
try {
return (Boolean) trySetAccessibleMethod.invoke(obj);
} catch (final Throwable e) {
// Ignore
}
}
if (setAccessibleMethod != null) {
// JDK 7/8
... | 365 | 140 | 505 | <methods><variables>private static java.lang.reflect.Method canAccessMethod,private final SingletonMap<Class<?>,nonapi.io.github.classgraph.reflection.ReflectionDriver.ClassMemberCache,java.lang.Exception> classToClassMemberCache,private static java.lang.reflect.Method isAccessibleMethod |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/scanspec/AcceptReject.java | AcceptRejectPrefix | acceptHasPrefix | class AcceptRejectPrefix extends AcceptReject {
/** Deserialization constructor. */
public AcceptRejectPrefix() {
super();
}
/**
* Instantiate a new accept/reject for prefix strings.
*
* @param separatorChar
* the separator char... |
throw new IllegalArgumentException("Can only find prefixes of whole strings");
| 959 | 19 | 978 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/types/TypeUtils.java | TypeUtils | modifiersToString | class TypeUtils {
/**
* Constructor.
*/
private TypeUtils() {
// Cannot be constructed
}
/**
* Parse a Java identifier, replacing '/' with '.'. Appends the identifier to the token buffer in the parser.
*
* @param parser
* The parser.
* @param stop... |
if ((modifiers & Modifier.PUBLIC) != 0) {
appendModifierKeyword(buf, "public");
} else if ((modifiers & Modifier.PRIVATE) != 0) {
appendModifierKeyword(buf, "private");
} else if ((modifiers & Modifier.PROTECTED) != 0) {
appendModifierKeyword(buf, "protected"... | 715 | 652 | 1,367 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/utils/Assert.java | Assert | isAnnotation | class Assert {
/**
* Throw {@link IllegalArgumentException} if the class is not an annotation.
*
* @param clazz
* the class.
* @throws IllegalArgumentException
* if the class is not an annotation.
*/
public static void isAnnotation(final Class<?> clazz)... |
if (!clazz.isAnnotation()) {
throw new IllegalArgumentException(clazz + " is not an annotation");
}
| 208 | 33 | 241 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/utils/CollectionUtils.java | CollectionUtils | sortCopy | class CollectionUtils {
/** Class can't be constructed. */
private CollectionUtils() {
// Empty
}
/**
* Sort a collection if it is not empty (to prevent {@link ConcurrentModificationException} if an immutable
* empty list that has been returned more than once is being sorted in one th... |
final List<T> sortedCopy = new ArrayList<>(elts);
if (sortedCopy.size() > 1) {
Collections.sort(sortedCopy);
}
return sortedCopy;
| 448 | 54 | 502 | <no_super_class> |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/utils/ProxyingInputStream.java | ProxyingInputStream | skipNBytes | class ProxyingInputStream extends InputStream {
private InputStream inputStream;
private static Method readAllBytes;
private static Method readNBytes1;
private static Method readNBytes3;
private static Method skipNBytes;
private static Method transferTo;
static {
// Use reflection ... |
if (skipNBytes == null) {
throw new UnsupportedOperationException();
}
try {
skipNBytes.invoke(inputStream, n);
} catch (final Exception e) {
throw new IOException(e);
}
| 1,271 | 64 | 1,335 | <methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(b... |
classgraph_classgraph | classgraph/src/main/java/nonapi/io/github/classgraph/utils/StringUtils.java | StringUtils | readString | class StringUtils {
/**
* Constructor.
*/
private StringUtils() {
// Cannot be constructed
}
/**
* Reads the "modified UTF8" format defined in the Java classfile spec, optionally replacing '/' with '.', and
* optionally removing the prefix "L" and the suffix ";".
*
... |
if (startOffset < 0L || numBytes < 0 || startOffset + numBytes > arr.length) {
throw new IllegalArgumentException("offset or numBytes out of range");
}
final char[] chars = new char[numBytes];
int byteIdx = 0;
int charIdx = 0;
for (; byteIdx < numBytes; byteI... | 872 | 895 | 1,767 | <no_super_class> |
prometheus_client_java | client_java/benchmarks/src/main/java/io/prometheus/metrics/benchmarks/CounterBenchmark.java | OpenTelemetryCounter | openTelemetryInc | class OpenTelemetryCounter {
final LongCounter longCounter;
final DoubleCounter doubleCounter;
final Attributes attributes;
public OpenTelemetryCounter() {
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(InMemoryMetr... |
for (int i=0; i<10*1024; i++) {
counter.longCounter.add(1, counter.attributes);
}
return counter.longCounter;
| 622 | 52 | 674 | <no_super_class> |
prometheus_client_java | client_java/benchmarks/src/main/java/io/prometheus/metrics/benchmarks/HistogramBenchmark.java | OpenTelemetryExponentialHistogram | openTelemetryExponential | class OpenTelemetryExponentialHistogram {
final io.opentelemetry.api.metrics.DoubleHistogram histogram;
public OpenTelemetryExponentialHistogram() {
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(InMemoryMetricReader.create())
... |
for (int i = 0; i < randomNumbers.randomNumbers.length; i++) {
histogram.histogram.record(randomNumbers.randomNumbers[i]);
}
return histogram.histogram;
| 800 | 60 | 860 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/GreetingServlet.java | GreetingServlet | doGet | class GreetingServlet extends HttpServlet {
private final Random random = new Random(0);
private final Histogram histogram;
public GreetingServlet() {
histogram = Histogram.builder()
.name("request_duration_seconds")
.help("request duration in seconds")
.unit(U... |
long start = System.nanoTime();
try {
Thread.sleep((long) (Math.abs((random.nextGaussian() + 1.0) * 100.0)));
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getWriter().println("Hello, World!");
} catch (InterruptedException e) {
... | 155 | 145 | 300 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/Main.java | Main | main | class Main {
public static void main(String[] args) throws LifecycleException {<FILL_FUNCTION_BODY>}
} |
JvmMetrics.builder().register();
Tomcat tomcat = new Tomcat();
tomcat.setPort(8081);
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
Tomcat.addServlet(ctx, "hello", new GreetingServlet());
ctx.addServletMappingDecoded("/*", "hello");
To... | 37 | 164 | 201 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/HelloWorldServlet.java | HelloWorldServlet | doGet | class HelloWorldServlet extends HttpServlet {
private final Random random = new Random(0);
private final Histogram histogram;
public HelloWorldServlet() {
histogram = Histogram.builder()
.name("request_duration_seconds")
.help("request duration in seconds")
... |
long start = System.nanoTime();
try {
Thread.sleep((long) (Math.abs((random.nextGaussian() + 1.0) * 100.0)));
String greeting = executeGreetingServiceRequest();
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getWriter().print(gre... | 265 | 156 | 421 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/Main.java | Main | main | class Main {
public static void main(String[] args) throws LifecycleException {<FILL_FUNCTION_BODY>}
} |
JvmMetrics.builder().register();
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
Tomcat.addServlet(ctx, "hello", new HelloWorldServlet());
ctx.addServletMappingDecoded("/*", "hello");
... | 37 | 164 | 201 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exporter-httpserver/src/main/java/io/prometheus/metrics/examples/httpserver/Main.java | Main | main | class Main {
public static void main(String[] args) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
} |
JvmMetrics.builder().register();
// Note: uptime_seconds_total is not a great example:
// The built-in JvmMetrics have an out-of-the-box metric named process_start_time_seconds
// with the start timestamp in seconds, so if you want to know the uptime you can simply
// run the ... | 37 | 263 | 300 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exporter-multi-target/src/main/java/io/prometheus/metrics/examples/multitarget/Main.java | Main | main | class Main {
public static void main(String[] args) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
} |
SampleMultiCollector xmc = new SampleMultiCollector();
PrometheusRegistry.defaultRegistry.register(xmc);
HTTPServer server = HTTPServer.builder()
.port(9401)
.buildAndStart();
System.out.println("HTTPServer listening on port http://localhost:" + server.... | 37 | 97 | 134 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exporter-multi-target/src/main/java/io/prometheus/metrics/examples/multitarget/SampleMultiCollector.java | SampleMultiCollector | collectMetricSnapshots | class SampleMultiCollector implements MultiCollector {
public SampleMultiCollector() {
super();
}
@Override
public MetricSnapshots collect() {
return new MetricSnapshots();
}
@Override
public MetricSnapshots collect(PrometheusScrapeRequest scrapeRequest) {
return collectMetricSnapshots(scrapeRequest);
... |
GaugeSnapshot.Builder gaugeBuilder = GaugeSnapshot.builder();
gaugeBuilder.name("x_load").help("process load");
CounterSnapshot.Builder counterBuilder = CounterSnapshot.builder();
counterBuilder.name(PrometheusNaming.sanitizeMetricName("x_calls_total")).help("invocations");
String[] targetNames = scrapeRe... | 194 | 645 | 839 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/Main.java | Main | main | class Main {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
// Note: Some JVM metrics are also defined as OpenTelemetry's semantic conventions.
// We have plans to implement a configuration option for JvmMetrics to use OpenTelemetry
// naming conventions rather than the Prometheus names.
JvmMetrics.builder().register();
// Note: uptime... | 33 | 295 | 328 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exporter-servlet-tomcat/src/main/java/io/prometheus/metrics/examples/tomcat_servlet/HelloWorldServlet.java | HelloWorldServlet | doGet | class HelloWorldServlet extends HttpServlet {
private final Random random = new Random(0);
// Note: The requests_total counter is not a great example, because the
// request_duration_seconds histogram below also has a count with the number of requests.
private final Counter counter = Counter.builder()... |
long start = System.nanoTime();
try {
Thread.sleep((long) (Math.abs((random.nextGaussian() + 1.0) * 100.0)));
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getWriter().println("Hello, World!");
} catch (InterruptedException e) {
... | 250 | 158 | 408 | <no_super_class> |
prometheus_client_java | client_java/examples/example-exporter-servlet-tomcat/src/main/java/io/prometheus/metrics/examples/tomcat_servlet/Main.java | Main | main | class Main {
public static void main(String[] args) throws LifecycleException, IOException {<FILL_FUNCTION_BODY>}
} |
JvmMetrics.builder().register();
Tomcat tomcat = new Tomcat();
Path tmpDir = Files.createTempDirectory("prometheus-tomcat-servlet-example-");
tomcat.setBaseDir(tmpDir.toFile().getAbsolutePath());
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
T... | 39 | 196 | 235 | <no_super_class> |
prometheus_client_java | client_java/examples/example-native-histogram/src/main/java/io/prometheus/metrics/examples/nativehistogram/Main.java | Main | main | class Main {
public static void main(String[] args) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
} |
JvmMetrics.builder().register();
Histogram histogram = Histogram.builder()
.name("request_latency_seconds")
.help("request latency in seconds")
.unit(Unit.SECONDS)
.labelNames("path", "status")
.register();
HTTPS... | 37 | 244 | 281 | <no_super_class> |
prometheus_client_java | client_java/examples/example-prometheus-properties/src/main/java/io/prometheus/metrics/examples/prometheus_properties/Main.java | Main | main | class Main {
public static void main(String[] args) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
} |
JvmMetrics.builder().register();
Histogram requestDuration = Histogram.builder()
.name("request_duration_seconds")
.help("request duration in seconds")
.unit(Unit.SECONDS)
.register();
Histogram requestSize = Histogram.builder()... | 37 | 277 | 314 | <no_super_class> |
prometheus_client_java | client_java/examples/example-simpleclient-bridge/src/main/java/io/prometheus/metrics/examples/simpleclient/Main.java | Main | main | class Main {
public static void main(String[] args) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
} |
// The following call will register all metrics from the old CollectorRegistry.defaultRegistry
// with the new PrometheusRegistry.defaultRegistry.
SimpleclientCollector.builder().register();
// Register a counter with the old CollectorRegistry.
// It doesn't matter whether th... | 37 | 232 | 269 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/ExemplarsProperties.java | ExemplarsProperties | load | class ExemplarsProperties {
private static final String MIN_RETENTION_PERIOD_SECONDS = "minRetentionPeriodSeconds";
private static final String MAX_RETENTION_PERIOD_SECONDS = "maxRetentionPeriodSeconds";
private static final String SAMPLE_INTERVAL_MILLISECONDS = "sampleIntervalMilliseconds";
private f... |
Integer minRetentionPeriodSeconds = Util.loadInteger(prefix + "." + MIN_RETENTION_PERIOD_SECONDS, properties);
Integer maxRetentionPeriodSeconds = Util.loadInteger(prefix + "." + MAX_RETENTION_PERIOD_SECONDS, properties);
Integer sampleIntervalMilliseconds = Util.loadInteger(prefix + "." + SAMP... | 856 | 390 | 1,246 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/ExporterFilterProperties.java | ExporterFilterProperties | load | class ExporterFilterProperties {
public static final String METRIC_NAME_MUST_BE_EQUAL_TO = "metricNameMustBeEqualTo";
public static final String METRIC_NAME_MUST_NOT_BE_EQUAL_TO = "metricNameMustNotBeEqualTo";
public static final String METRIC_NAME_MUST_START_WITH = "metricNameMustStartWith";
public st... |
List<String> allowedNames = Util.loadStringList(prefix + "." + METRIC_NAME_MUST_BE_EQUAL_TO, properties);
List<String> excludedNames = Util.loadStringList(prefix + "." + METRIC_NAME_MUST_NOT_BE_EQUAL_TO, properties);
List<String> allowedPrefixes = Util.loadStringList(prefix + "." + METRIC_NAME_... | 996 | 186 | 1,182 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/ExporterHttpServerProperties.java | ExporterHttpServerProperties | load | class ExporterHttpServerProperties {
private static final String PORT = "port";
private final Integer port;
private ExporterHttpServerProperties(Integer port) {
this.port = port;
}
public Integer getPort() {
return port;
}
/**
* Note that this will remove entries fro... |
Integer port = Util.loadInteger(prefix + "." + PORT, properties);
Util.assertValue(port, t -> t > 0, "Expecting value > 0", prefix, PORT);
return new ExporterHttpServerProperties(port);
| 253 | 64 | 317 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/ExporterOpenTelemetryProperties.java | ExporterOpenTelemetryProperties | load | class ExporterOpenTelemetryProperties {
// See https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk-extensions/autoconfigure/README.md
private static String PROTOCOL = "protocol"; // otel.exporter.otlp.protocol
private static String ENDPOINT = "endpoint"; // otel.exporter.otlp.endpoint
pr... |
String protocol = Util.loadString(prefix + "." + PROTOCOL, properties);
String endpoint = Util.loadString(prefix + "." + ENDPOINT, properties);
Map<String, String> headers = Util.loadMap(prefix + "." + HEADERS, properties);
Integer intervalSeconds = Util.loadInteger(prefix + "." + INTER... | 1,473 | 435 | 1,908 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/ExporterProperties.java | ExporterProperties | load | class ExporterProperties {
private static final String INCLUDE_CREATED_TIMESTAMPS = "includeCreatedTimestamps";
private static final String EXEMPLARS_ON_ALL_METRIC_TYPES = "exemplarsOnAllMetricTypes";
private final Boolean includeCreatedTimestamps;
private final Boolean exemplarsOnAllMetricTypes;
... |
Boolean includeCreatedTimestamps = Util.loadBoolean(prefix + "." + INCLUDE_CREATED_TIMESTAMPS, properties);
Boolean exemplarsOnAllMetricTypes = Util.loadBoolean(prefix + "." + EXEMPLARS_ON_ALL_METRIC_TYPES, properties);
return new ExporterProperties(includeCreatedTimestamps, exemplarsOnAllMetri... | 636 | 102 | 738 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/PrometheusPropertiesLoader.java | PrometheusPropertiesLoader | loadPropertiesFromClasspath | class PrometheusPropertiesLoader {
/**
* See {@link PrometheusProperties#get()}.
*/
public static PrometheusProperties load() throws PrometheusPropertiesException {
return load(new Properties());
}
public static PrometheusProperties load(Map<Object, Object> externalProperties) throws... |
Properties properties = new Properties();
try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("prometheus.properties")) {
properties.load(stream);
} catch (Exception ignored) {
}
return properties;
| 1,172 | 65 | 1,237 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-config/src/main/java/io/prometheus/metrics/config/Util.java | Util | loadStringList | class Util {
private static String getProperty(String name, Map<Object, Object> properties) {
Object object = properties.remove(name);
if (object != null) {
return object.toString();
}
return null;
}
static Boolean loadBoolean(String name, Map<Object, Object> pr... |
String property = getProperty(name, properties);
if (property != null) {
return Arrays.asList(property.split("\\s*,\\s*"));
}
return null;
| 1,262 | 53 | 1,315 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/datapoints/Timer.java | Timer | observeDuration | class Timer implements Closeable {
private final DoubleConsumer observeFunction;
private final long startTimeNanos = System.nanoTime();
/**
* Constructor is package private. Use the {@link TimerApi} provided by the implementation of the {@link DataPoint}.
*/
Timer(DoubleConsumer observeFunct... |
double elapsed = Unit.nanosToSeconds(System.nanoTime() - startTimeNanos);
observeFunction.accept(elapsed);
return elapsed;
| 194 | 46 | 240 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/exemplars/ExemplarSamplerConfig.java | ExemplarSamplerConfig | validate | class ExemplarSamplerConfig {
/**
* See {@link ExemplarsProperties#getMinRetentionPeriodSeconds()}
*/
public static final int DEFAULT_MIN_RETENTION_PERIOD_SECONDS = 7;
/**
* See {@link ExemplarsProperties#getMaxRetentionPeriodSeconds()}
*/
public static final int DEFAULT_MAX_RETENT... |
if (minRetentionPeriodMillis <= 0) {
throw new IllegalArgumentException(minRetentionPeriodMillis + ": minRetentionPeriod must be > 0.");
}
if (maxRetentionPeriodMillis <= 0) {
throw new IllegalArgumentException(maxRetentionPeriodMillis + ": maxRetentionPeriod must be > 0... | 1,201 | 360 | 1,561 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Buffer.java | Buffer | doAppend | class Buffer {
private static final long signBit = 1L << 63;
private final AtomicLong observationCount = new AtomicLong(0);
private double[] observationBuffer = new double[0];
private int bufferPos = 0;
private boolean reset = false;
private final Object appendLock = new Object();
private f... |
synchronized (appendLock) {
if (bufferPos >= observationBuffer.length) {
observationBuffer = Arrays.copyOf(observationBuffer, observationBuffer.length + 128);
}
observationBuffer[bufferPos] = amount;
bufferPos++;
}
| 518 | 72 | 590 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CallbackMetric.java | CallbackMetric | makeLabels | class CallbackMetric extends MetricWithFixedMetadata {
protected CallbackMetric(Builder<?, ?> builder) {
super(builder);
}
protected Labels makeLabels(String... labelValues) {<FILL_FUNCTION_BODY>}
static abstract class Builder<B extends Builder<B, M>, M extends CallbackMetric> extends MetricW... |
if (labelNames.length == 0) {
if (labelValues != null && labelValues.length > 0) {
throw new IllegalArgumentException("Cannot pass label values to a " + this.getClass().getSimpleName() + " that was created without label names.");
}
return constLabels;
... | 145 | 218 | 363 | <methods>public java.lang.String getPrometheusName() <variables>protected final non-sealed java.lang.String[] labelNames,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Counter.java | DataPoint | collect | class DataPoint implements CounterDataPoint {
private final DoubleAdder doubleValue = new DoubleAdder();
// LongAdder is 20% faster than DoubleAdder. So let's use the LongAdder for long observations,
// and DoubleAdder for double observations. If the user doesn't observe any double at all,
... |
// Read the exemplar first. Otherwise, there is a race condition where you might
// see an Exemplar for a value that's not counted yet.
// If there are multiple Exemplars (by default it's just one), use the newest.
Exemplar latestExemplar = null;
if (exemplar... | 710 | 184 | 894 | <methods>public void clear() ,public io.prometheus.metrics.model.snapshots.MetricSnapshot collect() ,public transient void initLabelValues(java.lang.String[]) ,public transient io.prometheus.metrics.core.datapoints.CounterDataPoint labelValues(java.lang.String[]) ,public transient void remove(java.lang.String[]) <varia... |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CounterWithCallback.java | CounterWithCallback | collect | class CounterWithCallback extends CallbackMetric {
@FunctionalInterface
public interface Callback {
void call(double value, String... labelValues);
}
private final Consumer<Callback> callback;
private CounterWithCallback(Builder builder) {
super(builder);
this.callback = b... |
List<CounterSnapshot.CounterDataPointSnapshot> dataPoints = new ArrayList<>();
callback.accept((value, labelValues) -> {
dataPoints.add(new CounterSnapshot.CounterDataPointSnapshot(value, makeLabels(labelValues), null, 0L));
});
return new CounterSnapshot(getMetadata(), data... | 588 | 85 | 673 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Gauge.java | Gauge | collect | class Gauge extends StatefulMetric<GaugeDataPoint, Gauge.DataPoint> implements GaugeDataPoint {
private final boolean exemplarsEnabled;
private final ExemplarSamplerConfig exemplarSamplerConfig;
private Gauge(Builder builder, PrometheusProperties prometheusProperties) {
super(builder);
Met... |
List<GaugeSnapshot.GaugeDataPointSnapshot> dataPointSnapshots = new ArrayList<>(labels.size());
for (int i = 0; i < labels.size(); i++) {
dataPointSnapshots.add(metricData.get(i).collect(labels.get(i)));
}
return new GaugeSnapshot(getMetadata(), dataPointSnapshots);
| 1,471 | 92 | 1,563 | <methods>public void clear() ,public io.prometheus.metrics.model.snapshots.MetricSnapshot collect() ,public transient void initLabelValues(java.lang.String[]) ,public transient io.prometheus.metrics.core.datapoints.GaugeDataPoint labelValues(java.lang.String[]) ,public transient void remove(java.lang.String[]) <variabl... |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/GaugeWithCallback.java | GaugeWithCallback | collect | class GaugeWithCallback extends CallbackMetric {
@FunctionalInterface
public interface Callback {
void call(double value, String... labelValues);
}
private final Consumer<Callback> callback;
private GaugeWithCallback(Builder builder) {
super(builder);
this.callback = build... |
List<GaugeSnapshot.GaugeDataPointSnapshot> dataPoints = new ArrayList<>();
callback.accept((value, labelValues) -> {
dataPoints.add(new GaugeSnapshot.GaugeDataPointSnapshot(value, makeLabels(labelValues), null, 0L));
});
return new GaugeSnapshot(getMetadata(), dataPoints);
... | 337 | 88 | 425 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Info.java | Builder | stripInfoSuffix | class Builder extends MetricWithFixedMetadata.Builder<Builder, Info> {
private Builder(PrometheusProperties config) {
super(Collections.emptyList(), config);
}
/**
* The {@code _info} suffix will automatically be appended if it's missing.
* <pre>{@code
* ... |
if (name != null && (name.endsWith("_info") || name.endsWith(".info"))) {
name = name.substring(0, name.length() - 5);
}
return name;
| 435 | 58 | 493 | <methods>public java.lang.String getPrometheusName() <variables>protected final non-sealed java.lang.String[] labelNames,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Metric.java | Builder | constLabels | class Builder<B extends Builder<B, M>, M extends Metric> {
protected final List<String> illegalLabelNames;
protected final PrometheusProperties properties;
protected Labels constLabels = Labels.EMPTY;
protected Builder(List<String> illegalLabelNames, PrometheusProperties properties) {
... |
for (Label label : constLabels) { // NPE if constLabels is null
if (illegalLabelNames.contains(label.getName())) {
throw new IllegalArgumentException(label.getName() + ": illegal label name for this metric type");
}
}
this.constLab... | 334 | 85 | 419 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/MetricWithFixedMetadata.java | MetricWithFixedMetadata | makeName | class MetricWithFixedMetadata extends Metric {
private final MetricMetadata metadata;
protected final String[] labelNames;
protected MetricWithFixedMetadata(Builder<?, ?> builder) {
super(builder);
this.metadata = new MetricMetadata(makeName(builder.name, builder.unit), builder.help, build... |
if (unit != null) {
if (!name.endsWith(unit.toString())) {
name = name + "_" + unit;
}
}
return name;
| 689 | 49 | 738 | <methods>public abstract io.prometheus.metrics.model.snapshots.MetricSnapshot collect() <variables>protected final non-sealed io.prometheus.metrics.model.snapshots.Labels constLabels |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/SlidingWindow.java | SlidingWindow | rotate | class SlidingWindow<T> {
private final Supplier<T> constructor;
private final ObjDoubleConsumer<T> observeFunction;
private final T[] ringBuffer;
private int currentBucket;
private long lastRotateTimestampMillis;
private final long durationBetweenRotatesMillis;
LongSupplier currentTimeMilli... |
long timeSinceLastRotateMillis = currentTimeMillis.getAsLong() - lastRotateTimestampMillis;
while (timeSinceLastRotateMillis > durationBetweenRotatesMillis) {
ringBuffer[currentBucket] = constructor.get();
if (++currentBucket >= ringBuffer.length) {
currentBucket... | 577 | 141 | 718 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StateSet.java | StateSet | collect | class StateSet extends StatefulMetric<StateSetDataPoint, StateSet.DataPoint> implements StateSetDataPoint {
private final boolean exemplarsEnabled;
private final String[] names;
private StateSet(Builder builder, PrometheusProperties prometheusProperties) {
super(builder);
MetricsProperties... |
List<StateSetSnapshot.StateSetDataPointSnapshot> data = new ArrayList<>(labels.size());
for (int i = 0; i < labels.size(); i++) {
data.add(new StateSetSnapshot.StateSetDataPointSnapshot(names, metricDataList.get(i).values, labels.get(i)));
}
return new StateSetSnapshot(getMe... | 1,007 | 97 | 1,104 | <methods>public void clear() ,public io.prometheus.metrics.model.snapshots.MetricSnapshot collect() ,public transient void initLabelValues(java.lang.String[]) ,public transient io.prometheus.metrics.core.datapoints.StateSetDataPoint labelValues(java.lang.String[]) ,public transient void remove(java.lang.String[]) <vari... |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java | StatefulMetric | getMetricProperties | class StatefulMetric<D extends DataPoint, T extends D> extends MetricWithFixedMetadata {
/**
* Map label values to data points.
*/
private final ConcurrentHashMap<List<String>, T> data = new ConcurrentHashMap<>();
/**
* Shortcut for data.get(Collections.emptyList())
*/
private vola... |
String metricName = getMetadata().getName();
if (prometheusProperties.getMetricProperties(metricName) != null) {
return new MetricsProperties[]{
prometheusProperties.getMetricProperties(metricName), // highest precedence
builder.toProperties(), // sec... | 1,571 | 172 | 1,743 | <methods>public java.lang.String getPrometheusName() <variables>protected final non-sealed java.lang.String[] labelNames,private final non-sealed io.prometheus.metrics.model.snapshots.MetricMetadata metadata |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Summary.java | Builder | maxAgeSeconds | class Builder extends StatefulMetric.Builder<Summary.Builder, Summary> {
/**
* 5 minutes. See {@link #maxAgeSeconds(long)}.
*/
public static final long DEFAULT_MAX_AGE_SECONDS = TimeUnit.MINUTES.toSeconds(5);
/**
* 5. See {@link #numberOfAgeBuckets(int)}
*/
... |
if (maxAgeSeconds <= 0) {
throw new IllegalArgumentException("maxAgeSeconds cannot be " + maxAgeSeconds);
}
this.maxAgeSeconds = maxAgeSeconds;
return this;
| 1,500 | 62 | 1,562 | <methods>public void clear() ,public io.prometheus.metrics.model.snapshots.MetricSnapshot collect() ,public transient void initLabelValues(java.lang.String[]) ,public transient io.prometheus.metrics.core.datapoints.DistributionDataPoint labelValues(java.lang.String[]) ,public transient void remove(java.lang.String[]) <... |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/SummaryWithCallback.java | SummaryWithCallback | collect | class SummaryWithCallback extends CallbackMetric {
@FunctionalInterface
public interface Callback {
void call(long count, double sum, Quantiles quantiles, String... labelValues);
}
private final Consumer<Callback> callback;
private SummaryWithCallback(Builder builder) {
super(buil... |
List<SummarySnapshot.SummaryDataPointSnapshot> dataPoints = new ArrayList<>();
callback.accept((count, sum, quantiles, labelValues) -> {
dataPoints.add(new SummarySnapshot.SummaryDataPointSnapshot(count, sum, quantiles, makeLabels(labelValues), Exemplars.EMPTY, 0L));
});
ret... | 342 | 99 | 441 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/util/Scheduler.java | DaemonThreadFactory | awaitInitialization | class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
}
private static final ScheduledExecutorService executor = Executors.newSingleThre... |
CountDownLatch latch = new CountDownLatch(1);
Scheduler.schedule(latch::countDown, 0, TimeUnit.MILLISECONDS);
latch.await();
| 181 | 55 | 236 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-common/src/main/java/io/prometheus/metrics/exporter/common/PrometheusScrapeHandler.java | PrometheusScrapeHandler | shouldUseCompression | class PrometheusScrapeHandler {
private final PrometheusRegistry registry;
private final ExpositionFormats expositionFormats;
private final Predicate<String> nameFilter;
private AtomicInteger lastResponseSize = new AtomicInteger(2 << 9); // 0.5 MB
public PrometheusScrapeHandler() {
this(P... |
Enumeration<String> encodingHeaders = request.getHeaders("Accept-Encoding");
if (encodingHeaders == null) {
return false;
}
while (encodingHeaders.hasMoreElements()) {
String encodingHeader = encodingHeaders.nextElement();
String[] encodings = encodin... | 1,558 | 127 | 1,685 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/DefaultHandler.java | DefaultHandler | handle | class DefaultHandler implements HttpHandler {
private final byte[] responseBytes;
private final String contentType;
public DefaultHandler() {
String responseString = "" +
"<html>\n" +
"<head><title>Prometheus Java Client</title></head>\n" +
"<body>\n... |
try {
exchange.getResponseHeaders().set("Content-Type", contentType);
exchange.getResponseHeaders().set("Content-Length", Integer.toString(responseBytes.length));
exchange.sendResponseHeaders(200, responseBytes.length);
exchange.getResponseBody().write(responseBy... | 1,043 | 91 | 1,134 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HTTPServer.java | BlockingRejectedExecutionHandler | rejectedExecution | class BlockingRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {<FILL_FUNCTION_BODY>}
} |
if (!threadPoolExecutor.isShutdown()) {
try {
threadPoolExecutor.getQueue().put(runnable);
} catch (InterruptedException ignored) {
}
}
| 56 | 52 | 108 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HealthyHandler.java | HealthyHandler | handle | class HealthyHandler implements HttpHandler {
private final byte[] responseBytes;
private final String contentType;
public HealthyHandler() {
String responseString = "Exporter is healthy.\n";
this.responseBytes = responseString.getBytes(StandardCharsets.UTF_8);
this.contentType = "... |
try {
exchange.getResponseHeaders().set("Content-Type", contentType);
exchange.getResponseHeaders().set("Content-Length", Integer.toString(responseBytes.length));
exchange.sendResponseHeaders(200, responseBytes.length);
exchange.getResponseBody().write(responseBy... | 125 | 91 | 216 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HttpExchangeAdapter.java | HttpResponse | sendErrorResponseWithStackTrace | class HttpResponse implements PrometheusHttpResponse {
@Override
public void setHeader(String name, String value) {
httpExchange.getResponseHeaders().set(name, value);
}
@Override
public OutputStream sendHeadersAndGetBody(int statusCode, int contentLength) throws IO... |
if (!responseSent) {
responseSent = true;
try {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
printWriter.write("An Exception occurred while scraping metrics: ");
r... | 280 | 418 | 698 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/NamedDaemonThreadFactory.java | NamedDaemonThreadFactory | newThread | class NamedDaemonThreadFactory implements ThreadFactory {
private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
private final int poolNumber = POOL_NUMBER.getAndIncrement();
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final ThreadFactory delegate;
priva... |
Thread t = delegate.newThread(r);
t.setName(String.format("prometheus-http-%d-%d", poolNumber, threadNumber.getAndIncrement()));
t.setDaemon(daemon);
return t;
| 199 | 65 | 264 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/PrometheusInstrumentationScope.java | PrometheusInstrumentationScope | loadInstrumentationScopeInfo | class PrometheusInstrumentationScope {
private static final String instrumentationScopePropertiesFile = "instrumentationScope.properties";
private static final String instrumentationScopeNameKey = "instrumentationScope.name";
private static final String instrumentationScopeVersionKey = "instrumentationScop... |
try {
Properties properties = new Properties();
properties.load(PrometheusInstrumentationScope.class.getClassLoader().getResourceAsStream(instrumentationScopePropertiesFile));
String instrumentationScopeName = properties.getProperty(instrumentationScopeNameKey);
... | 103 | 281 | 384 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/PrometheusMetricProducer.java | PrometheusMetricProducer | collectAllMetrics | class PrometheusMetricProducer implements CollectionRegistration {
private final PrometheusRegistry registry;
private final Resource resource;
private final InstrumentationScopeInfo instrumentationScopeInfo;
public PrometheusMetricProducer(PrometheusRegistry registry, InstrumentationScopeInfo instrume... |
// TODO: We could add a filter configuration for the OpenTelemetry exporter and call registry.scrape(filter) if a filter is configured, like in the Servlet exporter.
MetricSnapshots snapshots = registry.scrape();
Resource resourceWithTargetInfo = resource.merge(resourceFromTargetInfo(snapshots)... | 714 | 473 | 1,187 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/ResourceAttributes.java | ResourceAttributes | get | class ResourceAttributes {
// TODO: The OTel Java instrumentation also has a SpringBootServiceNameDetector, we should port this over.
public static Map<String, String> get(String instrumentationScopeName,
String serviceName,
St... |
Map<String, String> result = new HashMap<>();
ResourceAttributesFromOtelAgent.addIfAbsent(result, instrumentationScopeName);
putIfAbsent(result, "service.name", serviceName);
putIfAbsent(result, "service.namespace", serviceNamespace);
putIfAbsent(result, "service.instance.id", s... | 159 | 189 | 348 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/ResourceAttributesFromJarFileName.java | ResourceAttributesFromJarFileName | addIfAbsent | class ResourceAttributesFromJarFileName {
public static void addIfAbsent(Map<String, String> result) {<FILL_FUNCTION_BODY>}
private static Path getJarPathFromSunCommandLine() {
String programArguments = System.getProperty("sun.java.command");
if (programArguments == null) {
return ... |
if (result.containsKey("service.name")) {
return;
}
Path jarPath = getJarPathFromSunCommandLine();
if (jarPath == null) {
return;
}
String serviceName = getServiceName(jarPath);
result.putIfAbsent("service.name", serviceName);
| 387 | 85 | 472 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/ResourceAttributesFromOtelAgent.java | ResourceAttributesFromOtelAgent | copyOtelJarsToTempDir | class ResourceAttributesFromOtelAgent {
private static final String[] OTEL_JARS = new String[]{"opentelemetry-api-1.29.0.jar", "opentelemetry-context-1.29.0.jar"};
/**
* This grabs resource attributes like {@code service.name} and {@code service.instance.id} from
* the OTel Java agent (if present) a... |
URL[] result = new URL[OTEL_JARS.length];
for (int i = 0; i < OTEL_JARS.length; i++) {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lib/" + OTEL_JARS[i]);
if (inputStream == null) {
throw new IllegalStateException(... | 966 | 217 | 1,183 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/ExponentialHistogramBucketsImpl.java | ExponentialHistogramBucketsImpl | getTotalCount | class ExponentialHistogramBucketsImpl implements ExponentialHistogramBuckets {
private final int scale;
private final int offset;
private final List<Long> bucketCounts = new ArrayList<>();
ExponentialHistogramBucketsImpl(int scale, int offset) {
this.scale = scale;
this.offset = offset... |
long result = 0;
for (Long count : bucketCounts) {
result += count;
}
return result;
| 211 | 36 | 247 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/MetricDataFactory.java | MetricDataFactory | create | class MetricDataFactory {
private final Resource resource;
private final InstrumentationScopeInfo instrumentationScopeInfo;
private final long currentTimeMillis;
public MetricDataFactory(Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long currentTimeMillis) {
this.resour... |
if (!snapshot.getDataPoints().isEmpty()) {
HistogramSnapshot.HistogramDataPointSnapshot firstDataPoint = snapshot.getDataPoints().get(0);
if (firstDataPoint.hasNativeHistogramData()) {
return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusNativeHistogra... | 477 | 169 | 646 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusClassicHistogram.java | PrometheusClassicHistogram | toOtelDataPoint | class PrometheusClassicHistogram extends PrometheusData<HistogramPointData> implements HistogramData {
private final List<HistogramPointData> points;
PrometheusClassicHistogram(HistogramSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.HISTOGRAM);
this.points = snapshot.getData... |
if (!dataPoint.hasClassicHistogramData()) {
return null;
} else {
return new HistogramPointDataImpl(
dataPoint.hasSum() ? dataPoint.getSum() : Double.NaN,
dataPoint.hasCount() ? dataPoint.getCount() : calculateCount(dataPoint.getClassicBuc... | 503 | 198 | 701 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusCounter.java | PrometheusCounter | toOtelDataPoint | class PrometheusCounter extends PrometheusData<DoublePointData> implements SumData<DoublePointData> {
private final List<DoublePointData> points;
public PrometheusCounter(CounterSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.DOUBLE_SUM);
this.points = snapshot.getDataPoints(... |
return new DoublePointDataImpl(
dataPoint.getValue(),
getStartEpochNanos(dataPoint),
getEpochNanos(dataPoint, currentTimeMillis),
labelsToAttributes(dataPoint.getLabels()),
convertExemplar(dataPoint.getExemplar())
);
| 261 | 80 | 341 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusData.java | PrometheusData | toDoubleExemplarData | class PrometheusData<T extends PointData> implements Data<T> {
private final MetricDataType type;
public PrometheusData(MetricDataType type) {
this.type = type;
}
public MetricDataType getType() {
return type;
}
protected Attributes labelsToAttributes(Labels labels) {
... |
if (exemplar == null) {
return null;
}
AttributesBuilder filteredAttributesBuilder = Attributes.builder();
String traceId = null;
String spanId = null;
for (Label label : exemplar.getLabels()) {
if (label.getName().equals(Exemplar.TRACE_I... | 501 | 293 | 794 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusGauge.java | PrometheusGauge | toOtelDataPoint | class PrometheusGauge extends PrometheusData<DoublePointData> implements GaugeData<DoublePointData> {
private final List<DoublePointData> points;
public PrometheusGauge(GaugeSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.DOUBLE_GAUGE);
this.points = snapshot.getDataPoints().... |
return new DoublePointDataImpl(
dataPoint.getValue(),
getStartEpochNanos(dataPoint),
getEpochNanos(dataPoint, currentTimeMillis),
labelsToAttributes(dataPoint.getLabels()),
convertExemplar(dataPoint.getExemplar())
);
| 204 | 80 | 284 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusInfo.java | PrometheusInfo | toOtelDataPoint | class PrometheusInfo extends PrometheusData<DoublePointData> implements SumData<DoublePointData> {
private final List<DoublePointData> points;
public PrometheusInfo(InfoSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.DOUBLE_SUM);
this.points = snapshot.getDataPoints().stream(... |
return new DoublePointDataImpl(
1.0,
getStartEpochNanos(dataPoint),
getEpochNanos(dataPoint, currentTimeMillis),
labelsToAttributes(dataPoint.getLabels()),
Collections.emptyList()
);
| 261 | 72 | 333 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusMetricData.java | PrometheusMetricData | convertUnit | class PrometheusMetricData<T extends PrometheusData<?>> implements MetricData {
private final Resource resource;
private final InstrumentationScopeInfo instrumentationScopeInfo;
private final String name;
private final String description;
private final String unit;
T data;
PrometheusMetric... |
if (unit == null) {
return null;
}
switch (unit.toString()) {
// Time
case "days": return "d";
case "hours": return "h";
case "minutes": return "min";
case "seconds": return "s";
case "milliseconds": return "ms"... | 722 | 370 | 1,092 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusNativeHistogram.java | PrometheusNativeHistogram | toOtelDataPoint | class PrometheusNativeHistogram extends PrometheusData<ExponentialHistogramPointData> implements ExponentialHistogramData {
private final List<ExponentialHistogramPointData> points;
PrometheusNativeHistogram(HistogramSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.EXPONENTIAL_HISTOGR... |
if (!dataPoint.hasNativeHistogramData()) {
return null;
}
return new ExponentialHistogramPointDataImpl(
dataPoint.getNativeSchema(),
dataPoint.hasSum() ? dataPoint.getSum() : Double.NaN,
dataPoint.hasCount() ? dataPoint.getCount() : ca... | 651 | 228 | 879 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusStateSet.java | PrometheusStateSet | toOtelDataPoint | class PrometheusStateSet extends PrometheusData<DoublePointData> implements SumData<DoublePointData> {
private final List<DoublePointData> points;
public PrometheusStateSet(StateSetSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.DOUBLE_SUM);
this.points = new ArrayList<>();
... |
return new DoublePointDataImpl(
dataPoint.isTrue(i) ? 1.0 : 0.0,
getStartEpochNanos(dataPoint),
getEpochNanos(dataPoint, currentTimeMillis),
labelsToAttributes(dataPoint.getLabels().merge(Labels.of(snapshot.getMetadata().getName(), dataPoint.getNa... | 311 | 110 | 421 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusSummary.java | PrometheusSummary | toOtelDataPoint | class PrometheusSummary extends PrometheusData<SummaryPointData> implements SummaryData {
private final List<SummaryPointData> points;
PrometheusSummary(SummarySnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.SUMMARY);
this.points = snapshot.getDataPoints().stream()
... |
SummaryPointDataImpl result = new SummaryPointDataImpl(
dataPoint.hasSum() ? dataPoint.getSum() : Double.NaN,
dataPoint.hasCount() ? dataPoint.getCount() : 0,
getStartEpochNanos(dataPoint),
getEpochNanos(dataPoint, currentTimeM... | 188 | 162 | 350 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusUnknown.java | PrometheusUnknown | toOtelDataPoint | class PrometheusUnknown extends PrometheusData<DoublePointData> implements GaugeData<DoublePointData> {
private final List<DoublePointData> points;
public PrometheusUnknown(UnknownSnapshot snapshot, long currentTimeMillis) {
super(MetricDataType.DOUBLE_GAUGE);
this.points = snapshot.getDataPoi... |
return new DoublePointDataImpl(
dataPoint.getValue(),
getStartEpochNanos(dataPoint),
getEpochNanos(dataPoint, currentTimeMillis),
labelsToAttributes(dataPoint.getLabels()),
convertExemplar(dataPoint.getExemplar())
);
| 199 | 80 | 279 | <methods>public void <init>(MetricDataType) ,public MetricDataType getType() <variables>private final non-sealed MetricDataType type |
prometheus_client_java | client_java/prometheus-metrics-exporter-servlet-jakarta/src/main/java/io/prometheus/metrics/exporter/servlet/jakarta/HttpExchangeAdapter.java | Request | getRequestPath | class Request implements PrometheusHttpRequest {
private final HttpServletRequest request;
public Request(HttpServletRequest request) {
this.request = request;
}
@Override
public String getQueryString() {
return request.getQueryString();
}
@O... |
StringBuilder uri = new StringBuilder();
String contextPath = request.getContextPath();
if (contextPath.startsWith("/")) {
uri.append(contextPath);
}
String servletPath = request.getServletPath();
if (servletPath.startsWith("/")) {... | 156 | 132 | 288 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exporter-servlet-javax/src/main/java/io/prometheus/metrics/exporter/servlet/javax/HttpExchangeAdapter.java | Response | sendHeadersAndGetBody | class Response implements PrometheusHttpResponse {
private final HttpServletResponse response;
/**
* Constructs a new Response with the given HttpServletResponse.
*
* @param response the HttpServletResponse to be adapted
*/
public Response(HttpServletRespons... |
if (response.getHeader("Content-Length") == null && contentLength > 0) {
response.setContentLength(contentLength);
}
response.setStatus(statusCode);
return response.getOutputStream();
| 157 | 57 | 214 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/ExpositionFormats.java | ExpositionFormats | init | class ExpositionFormats {
private final PrometheusProtobufWriter prometheusProtobufWriter;
private final PrometheusTextFormatWriter prometheusTextFormatWriter;
private final OpenMetricsTextFormatWriter openMetricsTextFormatWriter;
private ExpositionFormats(PrometheusProtobufWriter prometheusProtobufWr... |
return new ExpositionFormats(
new PrometheusProtobufWriter(),
new PrometheusTextFormatWriter(properties.getIncludeCreatedTimestamps()),
new OpenMetricsTextFormatWriter(properties.getIncludeCreatedTimestamps(), properties.getExemplarsOnAllMetricTypes())
);... | 408 | 76 | 484 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/ProtobufUtil.java | ProtobufUtil | timestampFromMillis | class ProtobufUtil {
static Timestamp timestampFromMillis(long timestampMillis) {<FILL_FUNCTION_BODY>}
} |
return Timestamp.newBuilder()
.setSeconds(timestampMillis / 1000L)
.setNanos((int) (timestampMillis % 1000L * 1000000L))
.build();
| 38 | 67 | 105 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/TextFormatUtil.java | TextFormatUtil | writeLabels | class TextFormatUtil {
static void writeLong(OutputStreamWriter writer, long value) throws IOException {
writer.append(Long.toString(value));
}
static void writeDouble(OutputStreamWriter writer, double d) throws IOException {
if (d == Double.POSITIVE_INFINITY) {
writer.write("+... |
writer.write('{');
for (int i = 0; i < labels.size(); i++) {
if (i > 0) {
writer.write(",");
}
writer.write(labels.getPrometheusName(i));
writer.write("=\"");
writeEscapedLabelValue(writer, labels.getValue(i));
writ... | 458 | 185 | 643 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExports.java | Builder | build | class Builder {
private MetricRegistry registry;
private MetricFilter metricFilter;
private CustomLabelMapper labelMapper;
private Builder() {
this.metricFilter = MetricFilter.ALL;
}
public Builder dropwizardRegistry(MetricRegistry registry) {
th... |
if (registry == null) {
throw new IllegalArgumentException("MetricRegistry must be set");
}
if (labelMapper == null) {
return new DropwizardExports(registry, metricFilter);
} else {
return new DropwizardExports(registry, me... | 246 | 83 | 329 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/CustomLabelMapper.java | CustomLabelMapper | getNameAndLabels | class CustomLabelMapper {
private final List<CompiledMapperConfig> compiledMapperConfigs;
public CustomLabelMapper(final List<MapperConfig> mapperConfigs) {
if (mapperConfigs == null || mapperConfigs.isEmpty()) {
throw new IllegalArgumentException("CustomLabelMapper needs some mapper confi... |
final String metricName = formatTemplate(config.getName(), parameters);
final List<String> labels = new ArrayList<String>(config.getLabels().size());
final List<String> labelValues = new ArrayList<String>(config.getLabels().size());
for (Map.Entry<String, String> entry : config.getLabel... | 938 | 138 | 1,076 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/GraphiteNamePattern.java | GraphiteNamePattern | extractParameters | class GraphiteNamePattern {
private static final Pattern VALIDATION_PATTERN = Pattern.compile(METRIC_GLOB_REGEX);
private Pattern pattern;
private String patternStr;
/**
* Creates a new GraphiteNamePattern from the given simplified glob pattern.
*
* @param pattern The glob style pattern... |
final Matcher matcher = this.pattern.matcher(metricName);
final Map<String, String> params = new HashMap<String, String>();
if (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
params.put(String.format("${%d}", i - 1), matcher.group(i));
... | 675 | 111 | 786 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfig.java | MapperConfig | equals | class MapperConfig {
// each part of the metric name between dots
private static final String METRIC_PART_REGEX = "[a-zA-Z_0-9](-?[a-zA-Z0-9_])+";
// Simplified GLOB: we can have "*." at the beginning and "*" only at the end
static final String METRIC_GLOB_REGEX = "^(\\*\\.|" + METRIC_PART_REGEX + "\\.)... |
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MapperConfig that = (MapperConfig) o;
if (match != null ? !match.equals(that.match) : that.match != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) ... | 1,369 | 132 | 1,501 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmBufferPoolMetrics.java | JvmBufferPoolMetrics | register | class JvmBufferPoolMetrics {
private static final String JVM_BUFFER_POOL_USED_BYTES = "jvm_buffer_pool_used_bytes";
private static final String JVM_BUFFER_POOL_CAPACITY_BYTES = "jvm_buffer_pool_capacity_bytes";
private static final String JVM_BUFFER_POOL_USED_BUFFERS = "jvm_buffer_pool_used_buffers";
... |
GaugeWithCallback.builder(config)
.name(JVM_BUFFER_POOL_USED_BYTES)
.help("Used bytes of a given JVM buffer pool.")
.unit(Unit.BYTES)
.labelNames("pool")
.callback(callback -> {
for (BufferPoolMXBean pool : buf... | 522 | 363 | 885 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetrics.java | JvmClassLoadingMetrics | register | class JvmClassLoadingMetrics {
private static final String JVM_CLASSES_CURRENTLY_LOADED = "jvm_classes_currently_loaded";
private static final String JVM_CLASSES_LOADED_TOTAL = "jvm_classes_loaded_total";
private static final String JVM_CLASSES_UNLOADED_TOTAL = "jvm_classes_unloaded_total";
private fi... |
GaugeWithCallback.builder(config)
.name(JVM_CLASSES_CURRENTLY_LOADED)
.help("The number of classes that are currently loaded in the JVM")
.callback(callback -> callback.call(classLoadingBean.getLoadedClassCount()))
.register(registry);
C... | 465 | 254 | 719 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmCompilationMetrics.java | JvmCompilationMetrics | register | class JvmCompilationMetrics {
private static final String JVM_COMPILATION_TIME_SECONDS_TOTAL = "jvm_compilation_time_seconds_total";
private final PrometheusProperties config;
private final CompilationMXBean compilationBean;
private JvmCompilationMetrics(CompilationMXBean compilationBean, PrometheusP... |
if (compilationBean == null || !compilationBean.isCompilationTimeMonitoringSupported()) {
return;
}
CounterWithCallback.builder(config)
.name(JVM_COMPILATION_TIME_SECONDS_TOTAL)
.help("The total time in seconds taken for HotSpot class compilation")
... | 406 | 138 | 544 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmGarbageCollectorMetrics.java | Builder | register | class Builder {
private final PrometheusProperties config;
private List<GarbageCollectorMXBean> garbageCollectorBeans;
private Builder(PrometheusProperties config) {
this.config = config;
}
/**
* Package private. For testing only.
*/
Build... |
List<GarbageCollectorMXBean> garbageCollectorBeans = this.garbageCollectorBeans;
if (garbageCollectorBeans == null) {
garbageCollectorBeans = ManagementFactory.getGarbageCollectorMXBeans();
}
new JvmGarbageCollectorMetrics(garbageCollectorBeans, config).r... | 180 | 96 | 276 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetrics.java | JvmMemoryPoolAllocationMetrics | register | class JvmMemoryPoolAllocationMetrics {
private static final String JVM_MEMORY_POOL_ALLOCATED_BYTES_TOTAL = "jvm_memory_pool_allocated_bytes_total";
private final PrometheusProperties config;
private final List<GarbageCollectorMXBean> garbageCollectorBeans;
private JvmMemoryPoolAllocationMetrics(List<... |
Counter allocatedCounter = Counter.builder()
.name(JVM_MEMORY_POOL_ALLOCATED_BYTES_TOTAL)
.help("Total bytes allocated in a given JVM memory pool. Only updated after GC, not continuously.")
.labelNames("pool")
.register(registry);
Alloca... | 1,205 | 182 | 1,387 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMetrics.java | Builder | register | class Builder {
private final PrometheusProperties config;
private Builder(PrometheusProperties config) {
this.config = config;
}
/**
* Register all JVM metrics with the default registry.
* <p>
* It's safe to call this multiple times:
* ... |
JvmThreadsMetrics.builder(config).register(registry);
JvmBufferPoolMetrics.builder(config).register(registry);
JvmClassLoadingMetrics.builder(config).register(registry);
JvmCompilationMetrics.builder(config).register(registry);
JvmGarbageCollectorMetrics.buil... | 230 | 175 | 405 | <no_super_class> |
prometheus_client_java | client_java/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetrics.java | JvmNativeMemoryMetrics | makeCallback | class JvmNativeMemoryMetrics {
private static final String JVM_NATIVE_MEMORY_RESERVED_BYTES = "jvm_native_memory_reserved_bytes";
private static final String JVM_NATIVE_MEMORY_COMMITTED_BYTES = "jvm_native_memory_committed_bytes";
private static final Pattern pattern = Pattern.compile("\\s*([A-Z][A-Za-z\\s]*[A-Z... |
return callback -> {
String summary = vmNativeMemorySummaryInBytesOrEmpty();
if (!summary.isEmpty()) {
Matcher matcher = pattern.matcher(summary);
while (matcher.find()) {
String category = matcher.group(1);
long value;
if (reserved) {
value = L... | 1,096 | 141 | 1,237 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.