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 = workUnit; } } /** * A work unit processor. * * @param <T> * The type of work unit to process. */ public interface WorkUnitProcessor<T> { /** * Process a work unit. * * @param workUnit * The work unit. * @param workQueue * The work queue. * @param log * The log. * @throws InterruptedException * If the worker thread is interrupted. */ void processWorkUnit(T workUnit, WorkQueue<T> workQueue, LogNode log) throws InterruptedException; } /** * Start a work queue on the elements in the provided collection, blocking until all work units have been * completed. * * @param <U> * The type of the work queue units. * @param elements * The work queue units to process. * @param executorService * The {@link ExecutorService}. * @param interruptionChecker * the interruption checker * @param numParallelTasks * The number of parallel tasks. * @param log * The log. * @param workUnitProcessor * The {@link WorkUnitProcessor}. * @throws InterruptedException * If the work was interrupted. * @throws ExecutionException * If a worker throws an uncaught exception. */ public static <U> void runWorkQueue(final Collection<U> elements, final ExecutorService executorService, final InterruptionChecker interruptionChecker, final int numParallelTasks, final LogNode log, final WorkUnitProcessor<U> workUnitProcessor) throws InterruptedException, ExecutionException {<FILL_FUNCTION_BODY>
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, workUnitProcessor, numParallelTasks, interruptionChecker, log)) { // Start (numParallelTasks - 1) worker threads (may start zero threads if numParallelTasks == 1) workQueue.startWorkers(executorService, numParallelTasks - 1); // Use the current thread to do work too, in case there is only one thread available in the // ExecutorService, or in case numParallelTasks is greater than the number of available threads in the // ExecutorService. workQueue.runWorkLoop(); }
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 Inflater} instance. * * @return the {@link Inflater} instance. */ public Inflater getInflater() { return inflater; } /** * Called when an {@link Inflater} instance is recycled, to reset the inflater so it can accept new input. */ @Override public void reset() { inflater.reset(); } /** Called when the {@link Recycler} instance is closed, to destroy the {@link Inflater} instance. */ @Override public void close() { inflater.end(); } } /** * Wrap an {@link InputStream} with an {@link InflaterInputStream}, recycling the {@link Inflater} instance. * * @param rawInputStream * the raw input stream * @return the inflater input stream * @throws IOException * Signals that an I/O exception has occurred. */ public InputStream openInflaterInputStream(final InputStream rawInputStream) throws IOException {<FILL_FUNCTION_BODY>
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 AtomicBoolean closed = new AtomicBoolean(); private final byte[] buf = new byte[INFLATE_BUF_SIZE]; private static final int INFLATE_BUF_SIZE = 8192; @Override public int read() throws IOException { if (closed.get()) { throw new IOException("Already closed"); } else if (inflater.finished()) { return -1; } final int numDeflatedBytesRead = read(buf, 0, 1); if (numDeflatedBytesRead < 0) { return -1; } else { return buf[0] & 0xff; } } @Override public int read(final byte[] outBuf, final int off, final int len) throws IOException { if (closed.get()) { throw new IOException("Already closed"); } else if (len < 0) { throw new IllegalArgumentException("len cannot be negative"); } else if (len == 0) { return 0; } try { // Keep fetching data from rawInputStream until buffer is full or inflater has finished int totInflatedBytes = 0; while (!inflater.finished() && totInflatedBytes < len) { final int numInflatedBytes = inflater.inflate(outBuf, off + totInflatedBytes, len - totInflatedBytes); if (numInflatedBytes == 0) { if (inflater.needsDictionary()) { // Should not happen for jarfiles throw new IOException("Inflater needs preset dictionary"); } else if (inflater.needsInput()) { // Read a chunk of data from the raw InputStream final int numRawBytesRead = rawInputStream.read(buf, 0, buf.length); if (numRawBytesRead == -1) { // An extra dummy byte is needed at the end of the input stream when // using the "nowrap" Inflater option. // See: ZipFile.ZipFileInflaterInputStream.fill() buf[0] = (byte) 0; inflater.setInput(buf, 0, 1); } else { // Deflate the chunk of data inflater.setInput(buf, 0, numRawBytesRead); } } } else { totInflatedBytes += numInflatedBytes; } } if (totInflatedBytes == 0) { // If no bytes were inflated, return -1 as required by read() API contract return -1; } return totInflatedBytes; } catch (final DataFormatException e) { throw new ZipException( e.getMessage() != null ? e.getMessage() : "Invalid deflated zip entry data"); } } @Override public long skip(final long numToSkip) throws IOException { if (closed.get()) { throw new IOException("Already closed"); } else if (numToSkip < 0) { throw new IllegalArgumentException("numToSkip cannot be negative"); } else if (numToSkip == 0) { return 0; } else if (inflater.finished()) { return -1; } long totBytesSkipped = 0L; for (;;) { final int readLen = (int) Math.min(numToSkip - totBytesSkipped, buf.length); final int numBytesRead = read(buf, 0, readLen); if (numBytesRead > 0) { totBytesSkipped -= numBytesRead; } else { break; } } return totBytesSkipped; } @Override public int available() throws IOException { if (closed.get()) { throw new IOException("Already closed"); } // We don't know how many bytes are available, but have to return greater than // zero if there is still input, according to the API contract. Hopefully nothing // relies on this and ends up reading just one byte at a time. return inflater.finished() ? 0 : 1; } @Override public synchronized void mark(final int readlimit) { throw new IllegalArgumentException("Not supported"); } @Override public synchronized void reset() throws IOException { throw new IllegalArgumentException("Not supported"); } @Override public boolean markSupported() { return false; } @Override public void close() { if (!closed.getAndSet(true)) { try { rawInputStream.close(); } catch (final Exception e) { // Ignore } // Reset and recycle inflater instance inflaterRecycler.recycle(recyclableInflater); } } };
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 the zipfile. */ Slice slice; /** The nested jar handler. */ NestedJarHandler nestedJarHandler; /** The cached hashCode. */ private int hashCode; /** * Construct a {@link PhysicalZipFile} from a file on disk. * * @param file * the file * @param nestedJarHandler * the nested jar handler * @param log * the log * @throws IOException * if an I/O exception occurs. */ PhysicalZipFile(final File file, final NestedJarHandler nestedJarHandler, final LogNode log) throws IOException { this.nestedJarHandler = nestedJarHandler; this.file = file; this.pathStr = FastPathResolver.resolve(FileUtils.currDirPath(), file.getPath()); this.slice = new FileSlice(file, nestedJarHandler, log); } /** * Construct a {@link PhysicalZipFile} from a {@link Path}. * * @param path * the path * @param nestedJarHandler * the nested jar handler * @param log * the log * @throws IOException * if an I/O exception occurs. */ PhysicalZipFile(final Path path, final NestedJarHandler nestedJarHandler, final LogNode log) throws IOException { this.nestedJarHandler = nestedJarHandler; this.path = path; this.pathStr = FastPathResolver.resolve(FileUtils.currDirPath(), path.toString()); this.slice = new PathSlice(path, nestedJarHandler); } /** * Construct a {@link PhysicalZipFile} from a byte array. * * @param arr * the array containing the zipfile. * @param outermostFile * the outermost file * @param pathStr * the path * @param nestedJarHandler * the nested jar handler * @throws IOException * if an I/O exception occurs. */ PhysicalZipFile(final byte[] arr, final File outermostFile, final String pathStr, final NestedJarHandler nestedJarHandler) throws IOException { this.nestedJarHandler = nestedJarHandler; this.file = outermostFile; this.pathStr = pathStr; this.slice = new ArraySlice(arr, /* isDeflatedZipEntry = */ false, /* inflatedSizeHint = */ 0L, nestedJarHandler); } /** * Construct a {@link PhysicalZipFile} by reading from the {@link InputStream} to an array in RAM, or spill to * disk if the {@link InputStream} is too long. * * @param inputStream * the input stream * @param inputStreamLengthHint * The number of bytes to read in inputStream, or -1 if unknown. * @param pathStr * the source URL the InputStream was opened from, or the zip entry path of this entry in the parent * zipfile * @param nestedJarHandler * the nested jar handler * @param log * the log * @throws IOException * if an I/O exception occurs. */ PhysicalZipFile(final InputStream inputStream, final long inputStreamLengthHint, final String pathStr, final NestedJarHandler nestedJarHandler, final LogNode log) throws IOException { this.nestedJarHandler = nestedJarHandler; this.pathStr = pathStr; // Try downloading the InputStream to a byte array. If this succeeds, this will result in an ArraySlice. // If it fails, the InputStream will be spilled to disk, resulting in a FileSlice. this.slice = nestedJarHandler.readAllBytesWithSpilloverToDisk(inputStream, /* tempFileBaseName = */ pathStr, inputStreamLengthHint, log); this.file = this.slice instanceof FileSlice ? ((FileSlice) this.slice).file : null; } /** * Get the {@link Path} for the outermost jar file of this PhysicalZipFile. * * @return the {@link Path} for the outermost jar file of this PhysicalZipFile, or null if this file was * downloaded from a URL directly to RAM, or is backed by a {@link File}. */ public Path getPath() { return path; } /** * Get the {@link File} for the outermost jar file of this PhysicalZipFile. * * @return the {@link File} for the outermost jar file of this PhysicalZipFile, or null if this file was * downloaded from a URL directly to RAM, or is backed by a {@link Path}. */ public File getFile() { return file; } /** * Get the path for this PhysicalZipFile, which is the file path, if it is file-backed, or a compound nested jar * path, if it is memory-backed. * * @return the path for this PhysicalZipFile, which is the file path, if it is file-backed, or a compound nested * jar path, if it is memory-backed. */ public String getPathStr() { return pathStr; } /** * Get the length of the mapped file, or the initial remaining bytes in the wrapped ByteBuffer if a buffer was * wrapped. * * @return the length of the mapped file */ public long length() { return slice.sliceLength; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { if (hashCode == 0) { hashCode = (file == null ? 0 : file.hashCode()); if (hashCode == 0) { hashCode = 1; } } return hashCode; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object o) {<FILL_FUNCTION_BODY>} /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return pathStr; } }
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 slice * @param length * the length of the sub-slice * @param isDeflatedZipEntry * true if this is a deflated zip entry * @param inflatedLengthHint * the uncompressed size of a deflated zip entry, or -1 if unknown, or 0 of this is not a deflated * zip entry. * @param nestedJarHandler * the nested jar handler */ private ArraySlice(final ArraySlice parentSlice, final long offset, final long length, final boolean isDeflatedZipEntry, final long inflatedLengthHint, final NestedJarHandler nestedJarHandler) { super(parentSlice, offset, length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler); this.arr = parentSlice.arr; } /** * Constructor for treating a whole array as a slice. * * @param arr * the array containing the slice. * @param isDeflatedZipEntry * true if this is a deflated zip entry * @param inflatedLengthHint * the uncompressed size of a deflated zip entry, or -1 if unknown, or 0 of this is not a deflated * zip entry. * @param nestedJarHandler * the nested jar handler */ public ArraySlice(final byte[] arr, final boolean isDeflatedZipEntry, final long inflatedLengthHint, final NestedJarHandler nestedJarHandler) { super(arr.length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler); this.arr = arr; } /** * Slice this slice to form a sub-slice. * * @param offset * the offset relative to the start of this slice to use as the start of the sub-slice. * @param length * the length of the sub-slice. * @param isDeflatedZipEntry * the is deflated zip entry * @param inflatedLengthHint * the uncompressed size of a deflated zip entry, or -1 if unknown, or 0 of this is not a deflated * zip entry. * @return the slice */ @Override public Slice slice(final long offset, final long length, final boolean isDeflatedZipEntry, final long inflatedLengthHint) {<FILL_FUNCTION_BODY>} /** * Load the slice as a byte array. * * @return the byte[] * @throws IOException * Signals that an I/O exception has occurred. */ @Override public byte[] load() throws IOException { if (isDeflatedZipEntry) { // Deflate into RAM if necessary try (InputStream inputStream = open()) { return NestedJarHandler.readAllBytesAsArray(inputStream, inflatedLengthHint); } } else if (sliceStartPos == 0L && sliceLength == arr.length) { // Fast path -- return whole array, if the array is the whole slice and is not deflated return arr; } else { // Copy range of array, if it is a slice and it is not deflated return Arrays.copyOfRange(arr, (int) sliceStartPos, (int) (sliceStartPos + sliceLength)); } } /** * Return a new random access reader. * * @return the random access reader */ @Override public RandomAccessReader randomAccessReader() { return new RandomAccessArrayReader(arr, (int) sliceStartPos, (int) sliceLength); } @Override public boolean equals(final Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } }
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.InputStream open(io.github.classgraph.Resource) throws java.io.IOException,public abstract nonapi.io.github.classgraph.fileslice.reader.RandomAccessReader randomAccessReader() ,public java.nio.ByteBuffer read() throws java.io.IOException,public abstract nonapi.io.github.classgraph.fileslice.Slice slice(long, long, boolean, long) <variables>private int hashCode,public final non-sealed long inflatedLengthHint,public final non-sealed boolean isDeflatedZipEntry,protected final non-sealed nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler nestedJarHandler,protected final non-sealed nonapi.io.github.classgraph.fileslice.Slice parentSlice,public long sliceLength,public final non-sealed long sliceStartPos
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; /** * Constructor for slicing an array. * * @param arr * the array to slice. * @param sliceStartPos * the start index of the slice within the array. * @param sliceLength * the length of the slice within the array. */ public RandomAccessArrayReader(final byte[] arr, final int sliceStartPos, final int sliceLength) { this.arr = arr; this.sliceStartPos = sliceStartPos; this.sliceLength = sliceLength; } @Override public int read(final long srcOffset, final byte[] dstArr, final int dstArrStart, final int numBytes) throws IOException { 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, dstArr.length - dstArrStart), 0); if (numBytesToRead == 0) { return -1; } final int srcStart = (int) (sliceStartPos + srcOffset); System.arraycopy(arr, srcStart, dstArr, dstArrStart, numBytesToRead); return numBytesToRead; } catch (final IndexOutOfBoundsException e) { throw new IOException("Read index out of bounds"); } } @Override public int read(final long srcOffset, final ByteBuffer dstBuf, final int dstBufStart, final int numBytes) throws IOException {<FILL_FUNCTION_BODY>} @Override public byte readByte(final long offset) throws IOException { final int idx = sliceStartPos + (int) offset; return arr[idx]; } @Override public int readUnsignedByte(final long offset) throws IOException { final int idx = sliceStartPos + (int) offset; return arr[idx] & 0xff; } @Override public short readShort(final long offset) throws IOException { return (short) readUnsignedShort(offset); } @Override public int readUnsignedShort(final long offset) throws IOException { final int idx = sliceStartPos + (int) offset; return ((arr[idx + 1] & 0xff) << 8) // | (arr[idx] & 0xff); } @Override public int readInt(final long offset) throws IOException { final int idx = sliceStartPos + (int) offset; return ((arr[idx + 3] & 0xff) << 24) // | ((arr[idx + 2] & 0xff) << 16) // | ((arr[idx + 1] & 0xff) << 8) // | (arr[idx] & 0xff); } @Override public long readUnsignedInt(final long offset) throws IOException { return readInt(offset) & 0xffffffffL; } @Override public long readLong(final long offset) throws IOException { final int idx = sliceStartPos + (int) offset; return ((arr[idx + 7] & 0xffL) << 56) // | ((arr[idx + 6] & 0xffL) << 48) // | ((arr[idx + 5] & 0xffL) << 40) // | ((arr[idx + 4] & 0xffL) << 32) // | ((arr[idx + 3] & 0xffL) << 24) // | ((arr[idx + 2] & 0xffL) << 16) // | ((arr[idx + 1] & 0xffL) << 8) // | (arr[idx] & 0xffL); } @Override public String readString(final long offset, final int numBytes, final boolean replaceSlashWithDot, final boolean stripLSemicolon) throws IOException { final int idx = sliceStartPos + (int) offset; return StringUtils.readString(arr, idx, numBytes, replaceSlashWithDot, stripLSemicolon); } @Override public String readString(final long offset, final int numBytes) throws IOException { return readString(offset, numBytes, false, false); } }
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() - dstBufStart), 0); if (numBytesToRead == 0) { return -1; } final int srcStart = (int) (sliceStartPos + srcOffset); ((Buffer) dstBuf).position(dstBufStart); ((Buffer) dstBuf).limit(dstBufStart + numBytesToRead); dstBuf.put(arr, srcStart, numBytesToRead); return numBytesToRead; } catch (BufferUnderflowException | IndexOutOfBoundsException | ReadOnlyBufferException e) { throw new IOException("Read index out of bounds"); }
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 byteBuffer * the byte buffer * @param sliceStartPos * the slice start pos * @param sliceLength * the slice length */ public RandomAccessByteBufferReader(final ByteBuffer byteBuffer, final long sliceStartPos, final long sliceLength) { this.byteBuffer = byteBuffer.duplicate(); this.byteBuffer.order(ByteOrder.LITTLE_ENDIAN); this.sliceStartPos = (int) sliceStartPos; this.sliceLength = (int) sliceLength; ((Buffer) this.byteBuffer).position(this.sliceStartPos); ((Buffer) this.byteBuffer).limit(this.sliceStartPos + this.sliceLength); } @Override public int read(final long srcOffset, final byte[] dstArr, final int dstArrStart, final int numBytes) throws IOException { 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, dstArr.length - dstArrStart), 0); if (numBytesToRead == 0) { return -1; } final int srcStart = (int) srcOffset; ((Buffer) byteBuffer).position(sliceStartPos + srcStart); byteBuffer.get(dstArr, dstArrStart, numBytesToRead); ((Buffer) byteBuffer).position(sliceStartPos); return numBytesToRead; } catch (final IndexOutOfBoundsException e) { throw new IOException("Read index out of bounds"); } } @Override public int read(final long srcOffset, final ByteBuffer dstBuf, final int dstBufStart, final int numBytes) throws IOException {<FILL_FUNCTION_BODY>} @Override public byte readByte(final long offset) throws IOException { final int idx = (int) (sliceStartPos + offset); return byteBuffer.get(idx); } @Override public int readUnsignedByte(final long offset) throws IOException { final int idx = (int) (sliceStartPos + offset); return byteBuffer.get(idx) & 0xff; } @Override public int readUnsignedShort(final long offset) throws IOException { final int idx = (int) (sliceStartPos + offset); return byteBuffer.getShort(idx) & 0xff; } @Override public short readShort(final long offset) throws IOException { return (short) readUnsignedShort(offset); } @Override public int readInt(final long offset) throws IOException { final int idx = (int) (sliceStartPos + offset); return byteBuffer.getInt(idx); } @Override public long readUnsignedInt(final long offset) throws IOException { return readInt(offset) & 0xffffffffL; } @Override public long readLong(final long offset) throws IOException { final int idx = (int) (sliceStartPos + offset); return byteBuffer.getLong(idx); } @Override public String readString(final long offset, final int numBytes, final boolean replaceSlashWithDot, final boolean stripLSemicolon) throws IOException { final int idx = (int) (sliceStartPos + offset); final byte[] arr = new byte[numBytes]; if (read(offset, arr, 0, numBytes) < numBytes) { throw new IOException("Premature EOF while reading string"); } return StringUtils.readString(arr, idx, numBytes, replaceSlashWithDot, stripLSemicolon); } @Override public String readString(final long offset, final int numBytes) throws IOException { return readString(offset, numBytes, false, false); } }
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() - dstBufStart), 0); if (numBytesToRead == 0) { return -1; } final int srcStart = (int) (sliceStartPos + srcOffset); ((Buffer) byteBuffer).position(srcStart); ((Buffer) dstBuf).position(dstBufStart); ((Buffer) dstBuf).limit(dstBufStart + numBytesToRead); dstBuf.put(byteBuffer); ((Buffer) byteBuffer).limit(sliceStartPos + sliceLength); ((Buffer) byteBuffer).position(sliceStartPos); return numBytesToRead; } catch (BufferUnderflowException | IndexOutOfBoundsException | ReadOnlyBufferException e) { throw new IOException("Read index out of bounds"); }
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. */ private ByteBuffer reusableByteBuffer; /** The scratch arr. */ private final byte[] scratchArr = new byte[8]; /** The scratch byte buf. */ private final ByteBuffer scratchByteBuf = ByteBuffer.wrap(scratchArr); /** The utf 8 bytes. */ private byte[] utf8Bytes; /** * Constructor. * * @param fileChannel * the file channel * @param sliceStartPos * the slice start pos * @param sliceLength * the slice length */ public RandomAccessFileChannelReader(final FileChannel fileChannel, final long sliceStartPos, final long sliceLength) { this.fileChannel = fileChannel; this.sliceStartPos = sliceStartPos; this.sliceLength = sliceLength; } @Override public int read(final long srcOffset, final ByteBuffer dstBuf, final int dstBufStart, final int numBytes) throws IOException { if (numBytes == 0) { return 0; } try { if (srcOffset < 0L || numBytes < 0 || numBytes > sliceLength - srcOffset) { throw new IOException("Read index out of bounds"); } final long srcStart = sliceStartPos + srcOffset; ((Buffer) dstBuf).position(dstBufStart); ((Buffer) dstBuf).limit(dstBufStart + numBytes); final int numBytesRead = fileChannel.read(dstBuf, srcStart); return numBytesRead == 0 ? -1 : numBytesRead; } catch (BufferUnderflowException | IndexOutOfBoundsException e) { throw new IOException("Read index out of bounds"); } } @Override public int read(final long srcOffset, final byte[] dstArr, final int dstArrStart, final int numBytes) throws IOException { if (numBytes == 0) { return 0; } try { if (srcOffset < 0L || numBytes < 0 || numBytes > sliceLength - srcOffset) { throw new IOException("Read index out of bounds"); } if (reusableByteBuffer == null || reusableByteBuffer.array() != dstArr) { // If reusableByteBuffer is not set, or wraps a different array from a previous operation, // wrap dstArr with a new ByteBuffer reusableByteBuffer = ByteBuffer.wrap(dstArr); } // Read into reusableByteBuffer, which is backed with dstArr return read(srcOffset, reusableByteBuffer, dstArrStart, numBytes); } catch (BufferUnderflowException | IndexOutOfBoundsException e) { throw new IOException("Read index out of bounds"); } } @Override public byte readByte(final long offset) throws IOException { if (read(offset, scratchByteBuf, 0, 1) < 1) { throw new IOException("Premature EOF"); } return scratchArr[0]; } @Override public int readUnsignedByte(final long offset) throws IOException { if (read(offset, scratchByteBuf, 0, 1) < 1) { throw new IOException("Premature EOF"); } return scratchArr[0] & 0xff; } @Override public short readShort(final long offset) throws IOException { return (short) readUnsignedShort(offset); } @Override public int readUnsignedShort(final long offset) throws IOException { if (read(offset, scratchByteBuf, 0, 2) < 2) { throw new IOException("Premature EOF"); } return ((scratchArr[1] & 0xff) << 8) // | (scratchArr[0] & 0xff); } @Override public int readInt(final long offset) throws IOException { if (read(offset, scratchByteBuf, 0, 4) < 4) { throw new IOException("Premature EOF"); } return ((scratchArr[3] & 0xff) << 24) // | ((scratchArr[2] & 0xff) << 16) // | ((scratchArr[1] & 0xff) << 8) // | (scratchArr[0] & 0xff); } @Override public long readUnsignedInt(final long offset) throws IOException { return readInt(offset) & 0xffffffffL; } @Override public long readLong(final long offset) throws IOException {<FILL_FUNCTION_BODY>} @Override public String readString(final long offset, final int numBytes, final boolean replaceSlashWithDot, final boolean stripLSemicolon) throws IOException { // Reuse UTF8 buffer array if it's non-null from a previous call, and if it's big enough if (utf8Bytes == null || utf8Bytes.length < numBytes) { utf8Bytes = new byte[numBytes]; } if (read(offset, utf8Bytes, 0, numBytes) < numBytes) { throw new IOException("Premature EOF"); } return StringUtils.readString(utf8Bytes, 0, numBytes, replaceSlashWithDot, stripLSemicolon); } @Override public String readString(final long offset, final int numBytes) throws IOException { return readString(offset, numBytes, false, false); } }
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) << 32) // | ((scratchArr[3] & 0xffL) << 24) // | ((scratchArr[2] & 0xffL) << 16) // | ((scratchArr[1] & 0xffL) << 8) // | (scratchArr[0] & 0xffL);
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 used for deserialization (or both serialization and * deserialization), or false if just used for serialization (for speed). * @param onlySerializePublicFields * Set this to true if you only want to serialize public fields (ignored for deserialization). */ ClassFieldCache(final boolean forDeserialization, final boolean onlySerializePublicFields, final ReflectionUtils reflectionUtils) { this.resolveTypes = forDeserialization; this.onlySerializePublicFields = !forDeserialization && onlySerializePublicFields; this.reflectionUtils = reflectionUtils; } /** * For a given resolved type, find the visible and accessible fields, resolve the types of any generically typed * fields, and return the resolved fields. * * @param cls * the cls * @return the class fields */ ClassFields get(final Class<?> cls) { ClassFields classFields = classToClassFields.get(cls); if (classFields == null) { classToClassFields.put(cls, classFields = new ClassFields(cls, resolveTypes, onlySerializePublicFields, this, reflectionUtils)); } return classFields; } /** * Get the concrete type for a map or collection whose raw type is an interface or abstract class. * * @param rawType * the raw type * @param returnNullIfNotMapOrCollection * return null if not map or collection * @return the concrete type */ private static Class<?> getConcreteType(final Class<?> rawType, final boolean returnNullIfNotMapOrCollection) { // This list is not complete (e.g. EnumMap cannot be instantiated directly, you need to pass the // enum key type into a factory method), but this should cover a lot of the common types if (rawType == Map.class || rawType == AbstractMap.class || rawType == HashMap.class) { return HashMap.class; } else if (rawType == ConcurrentMap.class || rawType == ConcurrentHashMap.class) { return ConcurrentHashMap.class; } else if (rawType == SortedMap.class || rawType == NavigableMap.class || rawType == TreeMap.class) { return TreeMap.class; } else if (rawType == ConcurrentNavigableMap.class || rawType == ConcurrentSkipListMap.class) { return ConcurrentSkipListMap.class; } else if (rawType == List.class || rawType == AbstractList.class || rawType == ArrayList.class || rawType == Collection.class) { return ArrayList.class; } else if (rawType == AbstractSequentialList.class || rawType == LinkedList.class) { return LinkedList.class; } else if (rawType == Set.class || rawType == AbstractSet.class || rawType == HashSet.class) { return HashSet.class; } else if (rawType == SortedSet.class || rawType == TreeSet.class) { return TreeSet.class; } else if (rawType == Queue.class || rawType == AbstractQueue.class || rawType == Deque.class || rawType == ArrayDeque.class) { return ArrayDeque.class; } else if (rawType == BlockingQueue.class || rawType == LinkedBlockingQueue.class) { return LinkedBlockingQueue.class; } else if (rawType == BlockingDeque.class || rawType == LinkedBlockingDeque.class) { return LinkedBlockingDeque.class; } else if (rawType == TransferQueue.class || rawType == LinkedTransferQueue.class) { return LinkedTransferQueue.class; } else { return returnNullIfNotMapOrCollection ? null : rawType; } } /** * Get the concrete type of the given class, then return the default constructor for that type. * * @param cls * the class * @return the default constructor for concrete type of class * @throws IllegalArgumentException * if no default constructor is both found and accessible. */ Constructor<?> getDefaultConstructorForConcreteTypeOf(final Class<?> cls) {<FILL_FUNCTION_BODY>
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 Class<?> concreteType = getConcreteType(cls, /* returnNullIfNotMapOrCollection = */ false); for (Class<?> c = concreteType; c != null && (c != Object.class || cls == Object.class); c = c.getSuperclass()) { try { final Constructor<?> defaultConstructor = c.getDeclaredConstructor(); JSONUtils.makeAccessible(defaultConstructor, reflectionUtils); // Store found constructor in cache defaultConstructorForConcreteType.put(cls, defaultConstructor); return defaultConstructor; } catch (final ReflectiveOperationException | SecurityException e) { // Ignore } } throw new IllegalArgumentException("Class " + cls.getName() // + " does not have an accessible default (no-arg) constructor");
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) { this.items = items; } /** * Serialize this JSONArray to a string. * * @param jsonReferenceToId * the map from json reference to id * @param includeNullValuedFields * whether to include null-valued fields * @param depth * the nesting depth * @param indentWidth * the indent width * @param buf * the buf */ void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId, final boolean includeNullValuedFields, final int depth, final int indentWidth, final StringBuilder buf) {<FILL_FUNCTION_BODY>} }
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++) { final Object item = items.get(i); if (prettyPrint) { JSONUtils.indent(depth + 1, indentWidth, buf); } JSONSerializer.jsonValToJSONString(item, jsonReferenceToId, includeNullValuedFields, depth + 1, indentWidth, buf); if (i < n - 1) { buf.append(','); } if (prettyPrint) { buf.append('\n'); } } if (prettyPrint) { JSONUtils.indent(depth, indentWidth, buf); } buf.append(']'); }
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 sizeHint) { items = new ArrayList<>(sizeHint); } /** * Constructor. * * @param items * the items */ public JSONObject(final List<Entry<String, Object>> items) { this.items = items; } /** * Serialize this JSONObject to a string. * * @param jsonReferenceToId * a map from json reference to id * @param includeNullValuedFields * if true, include null valued fields * @param depth * the nesting depth * @param indentWidth * the indent width * @param buf * the buf */ void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId, final boolean includeNullValuedFields, final int depth, final int indentWidth, final StringBuilder buf) {<FILL_FUNCTION_BODY>} }
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) { if (item.getValue() != null) { numDisplayedFields++; } } } if (objectId == null && numDisplayedFields == 0) { buf.append("{}"); } else { buf.append(prettyPrint ? "{\n" : "{"); if (objectId != null) { // id will be non-null if this object does not have an @Id field, but was referenced by // another object (need to include ID_TAG) if (prettyPrint) { JSONUtils.indent(depth + 1, indentWidth, buf); } buf.append('"'); buf.append(JSONUtils.ID_KEY); buf.append(prettyPrint ? "\": " : "\":"); JSONSerializer.jsonValToJSONString(objectId, jsonReferenceToId, includeNullValuedFields, depth + 1, indentWidth, buf); if (numDisplayedFields > 0) { buf.append(','); } if (prettyPrint) { buf.append('\n'); } } for (int i = 0, j = 0; i < n; i++) { final Entry<String, Object> item = items.get(i); final Object val = item.getValue(); if (val != null || includeNullValuedFields) { final String key = item.getKey(); if (key == null) { // Keys must be quoted, so the unquoted null value cannot be a key // (Should not happen -- JSONParser.parseJSONObject checks for null keys) throw new IllegalArgumentException("Cannot serialize JSON object with null key"); } if (prettyPrint) { JSONUtils.indent(depth + 1, indentWidth, buf); } buf.append('"'); JSONUtils.escapeJSONString(key, buf); buf.append(prettyPrint ? "\": " : "\":"); JSONSerializer.jsonValToJSONString(val, jsonReferenceToId, includeNullValuedFields, depth + 1, indentWidth, buf); if (++j < numDisplayedFields) { buf.append(','); } if (prettyPrint) { buf.append('\n'); } } } if (prettyPrint) { JSONUtils.indent(depth, indentWidth, buf); } buf.append('}'); }
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} instances of unknown generic type. */ public static final Type MAP_OF_UNKNOWN_TYPE = new ParameterizedTypeImpl(Map.class, new Type[] { Object.class, Object.class }, null); /** The type parameter of {@link List} instances of unknown generic type. */ public static final Type LIST_OF_UNKNOWN_TYPE = new ParameterizedTypeImpl(List.class, new Type[] { Object.class }, null); /** * Constructor. * * @param rawType * the raw type * @param actualTypeArguments * the actual type arguments * @param ownerType * the owner type */ ParameterizedTypeImpl(final Class<?> rawType, final Type[] actualTypeArguments, final Type ownerType) { this.actualTypeArguments = actualTypeArguments; this.rawType = rawType; this.ownerType = (ownerType != null) ? ownerType : rawType.getDeclaringClass(); if (rawType.getTypeParameters().length != actualTypeArguments.length) { throw new IllegalArgumentException("Argument length mismatch"); } } /* (non-Javadoc) * @see java.lang.reflect.ParameterizedType#getActualTypeArguments() */ @Override public Type[] getActualTypeArguments() { return actualTypeArguments.clone(); } /* (non-Javadoc) * @see java.lang.reflect.ParameterizedType#getRawType() */ @Override public Class<?> getRawType() { return rawType; } /* (non-Javadoc) * @see java.lang.reflect.ParameterizedType#getOwnerType() */ @Override public Type getOwnerType() { return ownerType; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) {<FILL_FUNCTION_BODY>} /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return Arrays.hashCode(actualTypeArguments) ^ Objects.hashCode(ownerType) ^ Objects.hashCode(rawType); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { final StringBuilder buf = new StringBuilder(); if (ownerType == null) { buf.append(rawType.getName()); } else { if (ownerType instanceof Class) { buf.append(((Class<?>) ownerType).getName()); } else { buf.append(ownerType); } buf.append('$'); if (ownerType instanceof ParameterizedTypeImpl) { final String simpleName = rawType.getName() .replace(((ParameterizedTypeImpl) ownerType).rawType.getName() + "$", ""); buf.append(simpleName); } else { buf.append(rawType.getSimpleName()); } } if (actualTypeArguments != null && actualTypeArguments.length > 0) { buf.append('<'); boolean first = true; for (final Type t : actualTypeArguments) { if (first) { first = false; } else { buf.append(", "); } buf.append(t.toString()); } buf.append('>'); } return buf.toString(); } }
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()) && Arrays.equals(actualTypeArguments, other.getActualTypeArguments());
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 wrapped key. * * @return the wrapped key. */ public K get() { return wrappedKey; } /** * Hash code. * * @return the int */ /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() {<FILL_FUNCTION_BODY>} /** * Equals. * * @param obj * the obj * @return true, if successful */ /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (!(obj instanceof ReferenceEqualityKey)) { return false; } return wrappedKey == ((ReferenceEqualityKey<?>) obj).wrappedKey; } /** * To string. * * @return the string */ /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { final K key = wrappedKey; return key == null ? "null" : key.toString(); } }
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 generic (declared) parameters of its generic type. * * @param resolvedType * the resolved type */ TypeResolutions(final ParameterizedType resolvedType) { typeVariables = ((Class<?>) resolvedType.getRawType()).getTypeParameters(); resolvedTypeArguments = resolvedType.getActualTypeArguments(); if (resolvedTypeArguments.length != typeVariables.length) { throw new IllegalArgumentException("Type parameter count mismatch"); } } /** * Resolve the type variables in a type using a type variable resolution list, producing a resolved type. * * @param type * the type * @return the resolved type */ Type resolveTypeVariables(final Type type) {<FILL_FUNCTION_BODY>} /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { if (typeVariables.length == 0) { return "{ }"; } else { final StringBuilder buf = new StringBuilder(); buf.append("{ "); for (int i = 0; i < typeVariables.length; i++) { if (i > 0) { buf.append(", "); } buf.append(typeVariables[i]).append(" => ").append(resolvedTypeArguments[i]); } buf.append(" }"); return buf.toString(); } } }
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 = (ParameterizedType) type; final Type[] typeArgs = parameterizedType.getActualTypeArguments(); Type[] typeArgsResolved = null; for (int i = 0; i < typeArgs.length; i++) { // Recursively revolve each parameter of the type final Type typeArgResolved = resolveTypeVariables(typeArgs[i]); // Only compare typeArgs to typeArgResolved until the first difference is found if (typeArgsResolved == null) { if (!typeArgResolved.equals(typeArgs[i])) { // After the first difference is found, lazily allocate typeArgsResolved typeArgsResolved = new Type[typeArgs.length]; // Go back and copy all the previous args System.arraycopy(typeArgs, 0, typeArgsResolved, 0, i); // Insert the first different arg typeArgsResolved[i] = typeArgResolved; } } else { // After the first difference is found, keep copying the resolved args into the array typeArgsResolved[i] = typeArgResolved; } } if (typeArgsResolved == null) { // There were no type parameters to resolve return type; } else { // Return new ParameterizedType that wraps the resolved type args return new ParameterizedTypeImpl((Class<?>) parameterizedType.getRawType(), typeArgsResolved, parameterizedType.getOwnerType()); } } else if (type instanceof TypeVariable<?>) { // Look up concrete type for type variable final TypeVariable<?> typeVariable = (TypeVariable<?>) type; for (int i = 0; i < typeVariables.length; i++) { if (typeVariables[i].getName().equals(typeVariable.getName())) { return resolvedTypeArguments[i]; } } // Could not resolve type variable return type; } else if (type instanceof GenericArrayType) { // Count the array dimensions, and resolve the innermost type of the array int numArrayDims = 0; Type t = type; while (t instanceof GenericArrayType) { numArrayDims++; t = ((GenericArrayType) t).getGenericComponentType(); } final Type innermostType = t; final Type innermostTypeResolved = resolveTypeVariables(innermostType); if (!(innermostTypeResolved instanceof Class<?>)) { throw new IllegalArgumentException("Could not resolve generic array type " + type); } final Class<?> innermostTypeResolvedClass = (Class<?>) innermostTypeResolved; // Build an array to hold the size of each dimension, filled with zeroes final int[] dims = (int[]) Array.newInstance(int.class, numArrayDims); // Build a zero-sized array of the required number of dimensions, using the resolved innermost class final Object arrayInstance = Array.newInstance(innermostTypeResolvedClass, dims); // Get the class of this array instance -- this is the resolved array type return arrayInstance.getClass(); } else if (type instanceof WildcardType) { // TODO: Support WildcardType throw new RuntimeException("WildcardType not yet supported: " + type); } else { throw new RuntimeException("Got unexpected type: " + type); }
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> unusedInstances = new ConcurrentLinkedQueue<>(); /** * Create a new instance. This should either return a non-null instance of type T, or throw an exception of type * E. * * @return The new instance. * @throws E * If an exception of type E was thrown during instantiation. */ public abstract T newInstance() throws E; /** * Acquire on object instance of type T, either by reusing a previously recycled instance if possible, or if * there are no currently-unused instances, by allocating a new instance. * * @return Either a new or a recycled object instance. * @throws E * if {@link #newInstance()} threw an exception of type E. * @throws NullPointerException * if {@link #newInstance()} returned null. */ public T acquire() throws E {<FILL_FUNCTION_BODY>} /** * Acquire a Recyclable wrapper around an object instance, which can be used to recycle object instances at the * end of a try-with-resources block. * * @return Either a new or a recycled object instance. * @throws E * If anything goes wrong when trying to allocate a new object instance. */ public RecycleOnClose<T, E> acquireRecycleOnClose() throws E { return new RecycleOnClose<>(this, acquire()); } /** * Recycle an object for reuse by a subsequent call to {@link #acquire()}. If the object is an instance of * {@link Resettable}, then {@link Resettable#reset()} will be called on the instance before recycling it. * * @param instance * the instance to recycle. * @throws IllegalArgumentException * if the object instance was not originally obtained from this {@link Recycler}. */ public final void recycle(final T instance) { if (instance != null) { if (!usedInstances.remove(instance)) { throw new IllegalArgumentException("Tried to recycle an instance that was not in use"); } if (instance instanceof Resettable) { ((Resettable) instance).reset(); } if (!unusedInstances.add(instance)) { throw new IllegalArgumentException("Tried to recycle an instance twice"); } } } /** * Free all unused instances. Calls {@link AutoCloseable#close()} on any unused instances that implement * {@link AutoCloseable}. * * <p> * The {@link Recycler} may continue to be used to acquire new instances after calling this close method, and * then this close method may be called again in future, i.e. the effect of calling this method is to simply * clear out the recycler of unused instances, closing any {@link AutoCloseable} instances. */ @Override public void close() { for (T unusedInstance; (unusedInstance = unusedInstances.poll()) != null;) { if (unusedInstance instanceof AutoCloseable) { try { ((AutoCloseable) unusedInstance).close(); } catch (final Exception e) { // Ignore } } } } /** * Force-close this {@link Recycler}, by forcibly moving any instances that have been acquired but not yet * recycled into the unused instances list, then calling {@link #close()} to close any {@link AutoCloseable} * instances and discard all instances. */ public void forceClose() { // Move all elements from usedInstances to unusedInstances in a threadsafe way for (final T usedInstance : new ArrayList<>(usedInstances)) { if (usedInstances.remove(usedInstance)) { unusedInstances.add(usedInstance); } } close(); } }
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 NullPointerException("Failed to allocate a new recyclable instance"); } instance = newInstance; } else { // Reuse an unused instance instance = recycledInstance; } usedInstances.add(instance); return instance;
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 invokeMethod; private final Method setAccessibleMethod; private static interface ClassFinder { Class<?> findClass(String className) throws Exception; } private ClassFinder classFinder; JVMDriverReflectionDriver() throws Exception { // Construct a jvm-driver Driver instance via reflection, so that there is no runtime dependency final StandardReflectionDriver drv = new StandardReflectionDriver(); // driverClass = drv.findClass("io.github.toolfactory.jvm.Driver"); // Class<?> driverFactoryClass = drv.findClass("io.github.toolfactory.jvm.Driver$Factory"); // driver = drv.invokeStaticMethod(drv.findMethod(driverFactoryClass, "getNew")); // if (driverInstance == null) { // throw new IllegalArgumentException("Could not load jvm-driver library"); // } final Class<?> driverClass = drv.findClass("io.github.toolfactory.jvm.DefaultDriver"); for (final Constructor<?> constructor : drv.getDeclaredConstructors(driverClass)) { if (constructor.getParameterTypes().length == 0) { driver = constructor.newInstance(); break; } } if (driver == null) { throw new IllegalArgumentException("Could not instantiate jvm.DefaultDriver"); } // Look up needed methods getDeclaredMethods = drv.findInstanceMethod(driver, "getDeclaredMethods", Class.class); getDeclaredConstructors = drv.findInstanceMethod(driver, "getDeclaredConstructors", Class.class); getDeclaredFields = drv.findInstanceMethod(driver, "getDeclaredFields", Class.class); getField = drv.findInstanceMethod(driver, "getFieldValue", Object.class, Field.class); setField = drv.findInstanceMethod(driver, "setFieldValue", Object.class, Field.class, Object.class); invokeMethod = drv.findInstanceMethod(driver, "invoke", Object.class, Method.class, Object[].class); setAccessibleMethod = drv.findInstanceMethod(driver, "setAccessible", AccessibleObject.class, boolean.class); try { // JDK 7 and 8 final Method forName0_method = findStaticMethod(Class.class, "forName0", String.class, boolean.class, ClassLoader.class); classFinder = new ClassFinder() { @Override public Class<?> findClass(final String className) throws Exception { return (Class<?>) forName0_method.invoke(null, className, true, Thread.currentThread().getContextClassLoader()); } }; } catch (final Throwable t) { // Fall through } if (classFinder == null) { try { // JDK 16 (and possibly earlier) final Method forName0_method = findStaticMethod(Class.class, "forName0", String.class, boolean.class, ClassLoader.class, Class.class); classFinder = new ClassFinder() { @Override public Class<?> findClass(final String className) throws Exception { return (Class<?>) forName0_method.invoke(null, className, true, Thread.currentThread().getContextClassLoader(), JVMDriverReflectionDriver.class); } }; } catch (final Throwable t) { // Fall through } } if (classFinder == null) { try { // IBM Semeru final Method forNameImpl_method = findStaticMethod(Class.class, "forNameImpl", String.class, boolean.class, ClassLoader.class); classFinder = new ClassFinder() { @Override public Class<?> findClass(final String className) throws Exception { return (Class<?>) forNameImpl_method.invoke(null, className, true, Thread.currentThread().getContextClassLoader()); } }; } catch (final Throwable t) { // Fall through } } if (classFinder == null) { // Fallback if the above fails: just use Class.forName. // This won't find private non-exported classes in other modules. final Method forName_method = findStaticMethod(Class.class, "forName", String.class); classFinder = new ClassFinder() { @Override public Class<?> findClass(final String className) throws Exception { return (Class<?>) forName_method.invoke(null, className); } }; } } @Override public boolean makeAccessible(final Object instance, final AccessibleObject accessibleObject) {<FILL_FUNCTION_BODY>} @Override Class<?> findClass(final String className) throws Exception { return classFinder.findClass(className); } @Override Method[] getDeclaredMethods(final Class<?> cls) throws Exception { return (Method[]) getDeclaredMethods.invoke(driver, cls); } @SuppressWarnings("unchecked") @Override <T> Constructor<T>[] getDeclaredConstructors(final Class<T> cls) throws Exception { return (Constructor<T>[]) getDeclaredConstructors.invoke(driver, cls); } @Override Field[] getDeclaredFields(final Class<?> cls) throws Exception { return (Field[]) getDeclaredFields.invoke(driver, cls); } @Override Object getField(final Object object, final Field field) throws Exception { return getField.invoke(driver, object, field); } @Override void setField(final Object object, final Field field, final Object value) throws Exception { setField.invoke(driver, object, field, value); } @Override Object getStaticField(final Field field) throws Exception { return getField.invoke(driver, null, field); } @Override void setStaticField(final Field field, final Object value) throws Exception { setField.invoke(driver, null, field, value); } @Override Object invokeMethod(final Object object, final Method method, final Object... args) throws Exception { return invokeMethod.invoke(driver, object, method, args); } @Override Object invokeStaticMethod(final Method method, final Object... args) throws Exception { return invokeMethod.invoke(driver, null, method, args); } }
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 Method method, final Object[] args) throws Throwable { return callable.call(); } } /** * Call a method in the AccessController.doPrivileged(PrivilegedAction) context, using reflection, if possible * (AccessController is deprecated in JDK 17). */ @SuppressWarnings("unchecked") private <T> T doPrivileged(final Callable<T> callable) throws Throwable { if (accessControllerDoPrivileged != null) { final Object privilegedAction = Proxy.newProxyInstance(privilegedActionClass.getClassLoader(), new Class<?>[] { privilegedActionClass }, new PrivilegedActionInvocationHandler<T>(callable)); return (T) accessControllerDoPrivileged.invoke(null, privilegedAction); } else { // Fall back to invoking in a non-privileged context return callable.call(); } } // ------------------------------------------------------------------------------------------------------------- private static boolean tryMakeAccessible(final AccessibleObject obj) {<FILL_FUNCTION_BODY>
if (trySetAccessibleMethod != null) { // JDK 9+ try { return (Boolean) trySetAccessibleMethod.invoke(obj); } catch (final Throwable e) { // Ignore } } if (setAccessibleMethod != null) { // JDK 7/8 try { setAccessibleMethod.invoke(obj, true); return true; } catch (final Throwable e) { // Ignore } } return false;
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 */ public AcceptRejectPrefix(final char separatorChar) { super(separatorChar); } /** * Add to the accept. * * @param str * the string to accept */ @Override public void addToAccept(final String str) { if (str.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + str); } if (this.acceptPrefixesSet == null) { this.acceptPrefixesSet = new HashSet<>(); } this.acceptPrefixesSet.add(str); } /** * Add to the reject. * * @param str * the string to reject */ @Override public void addToReject(final String str) { if (str.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + str); } if (this.rejectPrefixes == null) { this.rejectPrefixes = new ArrayList<>(); } this.rejectPrefixes.add(str); } /** * Check if the requested string has an accepted/non-rejected prefix. * * @param str * the string to test * @return true if string is accepted and not rejected */ @Override public boolean isAcceptedAndNotRejected(final String str) { boolean isAccepted = acceptPrefixes == null; if (!isAccepted) { for (final String prefix : acceptPrefixes) { if (str.startsWith(prefix)) { isAccepted = true; break; } } } if (!isAccepted) { return false; } if (rejectPrefixes != null) { for (final String prefix : rejectPrefixes) { if (str.startsWith(prefix)) { return false; } } } return true; } /** * Check if the requested string has an accepted prefix. * * @param str * the string to test * @return true if string is accepted */ @Override public boolean isAccepted(final String str) { boolean isAccepted = acceptPrefixes == null; if (!isAccepted) { for (final String prefix : acceptPrefixes) { if (str.startsWith(prefix)) { isAccepted = true; break; } } } return isAccepted; } /** * Prefix-of-prefix is invalid -- throws {@link IllegalArgumentException}. * * @param str * the string to test * @return (does not return, throws exception) * @throws IllegalArgumentException * always */ @Override public boolean acceptHasPrefix(final String str) {<FILL_FUNCTION_BODY>} /** * Check if the requested string has a rejected prefix. * * @param str * the string to test * @return true if the string has a rejected prefix */ @Override public boolean isRejected(final String str) { if (rejectPrefixes != null) { for (final String prefix : rejectPrefixes) { if (str.startsWith(prefix)) { return true; } } } return false; } }
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 stopAtDollarSign * If true, stop parsing when the first '$' is hit. * @return true if at least one identifier character was parsed. */ public static boolean getIdentifierToken(final Parser parser, final boolean stopAtDollarSign) { boolean consumedChar = false; while (parser.hasMore()) { final char c = parser.peek(); if (c == '/') { parser.appendToToken('.'); parser.next(); consumedChar = true; } else if (c != ';' && c != '[' && c != '<' && c != '>' && c != ':' && (!stopAtDollarSign || c != '$')) { parser.appendToToken(c); parser.next(); consumedChar = true; } else { break; } } return consumedChar; } /** The origin of the modifier bits. */ public enum ModifierType { /** The modifier bits apply to a class. */ CLASS, /** The modifier bits apply to a method. */ METHOD, /** The modifier bits apply to a field. */ FIELD } /** * Append a space if necessary (if not at the beginning of the buffer, and the last character is not already a * space), then append a modifier keyword. * * @param buf * the buf * @param modifierKeyword * the modifier keyword */ private static void appendModifierKeyword(final StringBuilder buf, final String modifierKeyword) { if (buf.length() > 0 && buf.charAt(buf.length() - 1) != ' ') { buf.append(' '); } buf.append(modifierKeyword); } /** * Convert modifiers into a string representation, e.g. "public static final". * * @param modifiers * The field or method modifiers. * @param modifierType * The {@link ModifierType} these modifiers apply to. * @param isDefault * for methods, true if this is a default method (else ignored). * @param buf * The buffer to write the result into. */ public static void modifiersToString(final int modifiers, final ModifierType modifierType, final boolean isDefault, final StringBuilder buf) {<FILL_FUNCTION_BODY>} }
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"); } if (modifierType != ModifierType.FIELD && (modifiers & Modifier.ABSTRACT) != 0) { appendModifierKeyword(buf, "abstract"); } if ((modifiers & Modifier.STATIC) != 0) { appendModifierKeyword(buf, "static"); } if (modifierType == ModifierType.FIELD) { if ((modifiers & Modifier.VOLATILE) != 0) { // "bridge" and "volatile" overlap in bit 0x40 appendModifierKeyword(buf, "volatile"); } if ((modifiers & Modifier.TRANSIENT) != 0) { appendModifierKeyword(buf, "transient"); } } if ((modifiers & Modifier.FINAL) != 0) { appendModifierKeyword(buf, "final"); } if (modifierType == ModifierType.METHOD) { if ((modifiers & Modifier.SYNCHRONIZED) != 0) { appendModifierKeyword(buf, "synchronized"); } if (isDefault) { appendModifierKeyword(buf, "default"); } } if ((modifiers & 0x1000) != 0) { appendModifierKeyword(buf, "synthetic"); } if (modifierType != ModifierType.FIELD && (modifiers & 0x40) != 0) { // "bridge" and "volatile" overlap in bit 0x40 appendModifierKeyword(buf, "bridge"); } if (modifierType == ModifierType.METHOD && (modifiers & Modifier.NATIVE) != 0) { appendModifierKeyword(buf, "native"); } if (modifierType != ModifierType.FIELD && (modifiers & Modifier.STRICT) != 0) { appendModifierKeyword(buf, "strictfp"); } // Ignored: // ACC_SUPER (0x0020): Treat superclass methods specially when invoked by the invokespecial instruction
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) {<FILL_FUNCTION_BODY>} /** * Throw {@link IllegalArgumentException} if the class is not an interface. * * @param clazz * the class. * @throws IllegalArgumentException * if the class is not an interface. */ public static void isInterface(final Class<?> clazz) { if (!clazz.isInterface()) { throw new IllegalArgumentException(clazz + " is not an interface"); } } }
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 thread and iterated through in * another thread -- #334). * * @param <T> * the element type * @param list * the list */ public static <T extends Comparable<? super T>> void sortIfNotEmpty(final List<T> list) { if (list.size() > 1) { Collections.sort(list); } } /** * 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 thread and iterated through in * another thread -- #334). * * @param <T> * the element type * @param list * the list * @param comparator * the comparator */ public static <T> void sortIfNotEmpty(final List<T> list, final Comparator<? super T> comparator) { if (list.size() > 1) { Collections.sort(list, comparator); } } /** * Copy and sort a collection. * * @param elts * the collection to copy and sort * @return a sorted copy of the collection */ public static <T extends Comparable<T>> List<T> sortCopy(final Collection<T> elts) {<FILL_FUNCTION_BODY>} }
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 for InputStream methods not present in JDK 7. // TODO Switch to direct method calls once JDK 8 is required, and add back missing @Override annotations try { readAllBytes = InputStream.class.getDeclaredMethod("readAllBytes"); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } try { readNBytes1 = InputStream.class.getDeclaredMethod("readNBytes", int.class); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } try { readNBytes3 = InputStream.class.getDeclaredMethod("readNBytes", byte[].class, int.class, int.class); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } try { skipNBytes = InputStream.class.getDeclaredMethod("skipNBytes", long.class); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } try { transferTo = InputStream.class.getDeclaredMethod("transferTo", OutputStream.class); } catch (NoSuchMethodException | SecurityException e1) { // Ignore } } /** * A proxying {@link InputStream} implementation that compiles for JDK 7 but can support the methods added in * JDK 8 by reflection. * * @param inputStream * the {@link InputStream} to wrap. */ public ProxyingInputStream(final InputStream inputStream) { this.inputStream = inputStream; } @Override public int read() throws IOException { return inputStream.read(); } @Override public int read(final byte[] b) throws IOException { return inputStream.read(b); } @Override public int read(final byte[] b, final int off, final int len) throws IOException { return inputStream.read(b, off, len); } // No @Override, since this method is not present in JDK 7 public byte[] readAllBytes() throws IOException { if (readAllBytes == null) { throw new UnsupportedOperationException(); } try { return (byte[]) readAllBytes.invoke(inputStream); } catch (final Exception e) { throw new IOException(e); } } // No @Override, since this method is not present in JDK 7 public byte[] readNBytes(final int len) throws IOException { if (readNBytes1 == null) { throw new UnsupportedOperationException(); } try { return (byte[]) readNBytes1.invoke(inputStream, len); } catch (final Exception e) { throw new IOException(e); } } // No @Override, since this method is not present in JDK 7 public int readNBytes(final byte[] b, final int off, final int len) throws IOException { if (readNBytes3 == null) { throw new UnsupportedOperationException(); } try { return (int) readNBytes3.invoke(inputStream, b, off, len); } catch (final Exception e) { throw new IOException(e); } } @Override public int available() throws IOException { return inputStream.available(); } @Override public boolean markSupported() { return inputStream.markSupported(); } @Override public synchronized void mark(final int readlimit) { inputStream.mark(readlimit); } @Override public synchronized void reset() throws IOException { inputStream.reset(); } @Override public long skip(final long n) throws IOException { return inputStream.skip(n); } // No @Override, since this method is not present in JDK 7 public void skipNBytes(final long n) throws IOException {<FILL_FUNCTION_BODY>} // No @Override, since this method is not present in JDK 7 public long transferTo(final OutputStream out) throws IOException { if (transferTo == null) { throw new UnsupportedOperationException(); } try { return (long) transferTo.invoke(inputStream, out); } catch (final Exception e) { throw new IOException(e); } } @Override public String toString() { return inputStream.toString(); } @Override public void close() throws IOException { if (inputStream != null) { try { inputStream.close(); } finally { inputStream = null; } } } }
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(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
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 ";". * * @param arr * the array to read the string from * @param startOffset * The start offset of the string within the array. * @param numBytes * The number of bytes of the UTF8 encoding of the string. * @param replaceSlashWithDot * If true, replace '/' with '.'. * @param stripLSemicolon * If true, string final ';' character. * @return The string. * @throws IllegalArgumentException * If string could not be parsed. */ public static String readString(final byte[] arr, final int startOffset, final int numBytes, final boolean replaceSlashWithDot, final boolean stripLSemicolon) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} /** * A replacement for Java 8's String.join(). * * @param buf * The buffer to append to. * @param addAtBeginning * The token to add at the beginning of the string. * @param sep * The separator string. * @param addAtEnd * The token to add at the end of the string. * @param iterable * The {@link Iterable} to join. */ public static void join(final StringBuilder buf, final String addAtBeginning, final String sep, final String addAtEnd, final Iterable<?> iterable) { if (!addAtBeginning.isEmpty()) { buf.append(addAtBeginning); } boolean first = true; for (final Object item : iterable) { if (first) { first = false; } else { buf.append(sep); } buf.append(item == null ? "null" : item.toString()); } if (!addAtEnd.isEmpty()) { buf.append(addAtEnd); } } /** * A replacement for Java 8's String.join(). * * @param sep * The separator string. * @param iterable * The {@link Iterable} to join. * @return The string representation of the joined elements. */ public static String join(final String sep, final Iterable<?> iterable) { final StringBuilder buf = new StringBuilder(); join(buf, "", sep, "", iterable); return buf.toString(); } /** * A replacement for Java 8's String.join(). * * @param sep * The separator string. * @param items * The items to join. * @return The string representation of the joined items. */ public static String join(final String sep, final Object... items) { final StringBuilder buf = new StringBuilder(); boolean first = true; for (final Object item : items) { if (first) { first = false; } else { buf.append(sep); } buf.append(item.toString()); } return buf.toString(); } }
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; byteIdx++) { final int c = arr[startOffset + byteIdx] & 0xff; if (c > 127) { break; } chars[charIdx++] = (char) (replaceSlashWithDot && c == '/' ? '.' : c); } while (byteIdx < numBytes) { final int c = arr[startOffset + byteIdx] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: { byteIdx++; chars[charIdx++] = (char) (replaceSlashWithDot && c == '/' ? '.' : c); break; } case 12: case 13: { byteIdx += 2; if (byteIdx > numBytes) { throw new IllegalArgumentException("Bad modified UTF8"); } final int c2 = arr[startOffset + byteIdx - 1]; if ((c2 & 0xc0) != 0x80) { throw new IllegalArgumentException("Bad modified UTF8"); } final int c3 = ((c & 0x1f) << 6) | (c2 & 0x3f); chars[charIdx++] = (char) (replaceSlashWithDot && c3 == '/' ? '.' : c3); break; } case 14: { byteIdx += 3; if (byteIdx > numBytes) { throw new IllegalArgumentException("Bad modified UTF8"); } final int c2 = arr[startOffset + byteIdx - 2]; final int c3 = arr[startOffset + byteIdx - 1]; if ((c2 & 0xc0) != 0x80 || (c3 & 0xc0) != 0x80) { throw new IllegalArgumentException("Bad modified UTF8"); } final int c4 = ((c & 0x0f) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f); chars[charIdx++] = (char) (replaceSlashWithDot && c4 == '/' ? '.' : c4); break; } default: throw new IllegalArgumentException("Bad modified UTF8"); } } if (charIdx == numBytes && !stripLSemicolon) { return new String(chars); } else { if (stripLSemicolon) { if (charIdx < 2 || chars[0] != 'L' || chars[charIdx - 1] != ';') { throw new IllegalArgumentException("Expected string to start with 'L' and end with ';', got \"" + new String(chars) + "\""); } return new String(chars, 1, charIdx - 2); } else { return new String(chars, 0, charIdx); } }
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(InMemoryMetricReader.create()) .setResource(Resource.getDefault()) .build(); OpenTelemetry openTelemetry = OpenTelemetrySdk.builder() .setMeterProvider(sdkMeterProvider) .build(); Meter meter = openTelemetry .meterBuilder("instrumentation-library-name") .setInstrumentationVersion("1.0.0") .build(); this.longCounter = meter .counterBuilder("test1") .setDescription("test") .build(); this.doubleCounter = meter .counterBuilder("test2") .ofDoubles() .setDescription("test") .build(); this.attributes = Attributes.of( AttributeKey.stringKey("path"), "/", AttributeKey.stringKey("status"), "200"); } } @Benchmark @Threads(4) public CounterDataPoint prometheusAdd(RandomNumbers randomNumbers, PrometheusCounter counter) { for (int i=0; i<randomNumbers.randomNumbers.length; i++) { counter.dataPoint.inc(randomNumbers.randomNumbers[i]); } return counter.dataPoint; } @Benchmark @Threads(4) public CounterDataPoint prometheusInc(PrometheusCounter counter) { for (int i=0; i<10*1024; i++) { counter.dataPoint.inc(); } return counter.dataPoint; } @Benchmark @Threads(4) public DoubleCounter openTelemetryAdd(RandomNumbers randomNumbers, OpenTelemetryCounter counter) { for (int i=0; i<randomNumbers.randomNumbers.length; i++) { counter.doubleCounter.add(randomNumbers.randomNumbers[i], counter.attributes); } return counter.doubleCounter; } @Benchmark @Threads(4) public LongCounter openTelemetryInc(OpenTelemetryCounter counter) {<FILL_FUNCTION_BODY>
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()) .setResource(Resource.getDefault()) .registerView(InstrumentSelector.builder() .setName("test") .build(), View.builder() .setAggregation(Aggregation.base2ExponentialBucketHistogram(10_000, 5)) .build() ) .build(); OpenTelemetry openTelemetry = OpenTelemetrySdk.builder() .setMeterProvider(sdkMeterProvider) .build(); Meter meter = openTelemetry .meterBuilder("instrumentation-library-name") .setInstrumentationVersion("1.0.0") .build(); this.histogram = meter .histogramBuilder("test") .setDescription("test") .build(); } } @Benchmark @Threads(4) public Histogram prometheusClassic(RandomNumbers randomNumbers, PrometheusClassicHistogram histogram) { for (int i = 0; i < randomNumbers.randomNumbers.length; i++) { histogram.noLabels.observe(randomNumbers.randomNumbers[i]); } return histogram.noLabels; } @Benchmark @Threads(4) public Histogram prometheusNative(RandomNumbers randomNumbers, PrometheusNativeHistogram histogram) { for (int i = 0; i < randomNumbers.randomNumbers.length; i++) { histogram.noLabels.observe(randomNumbers.randomNumbers[i]); } return histogram.noLabels; } @Benchmark @Threads(4) public io.prometheus.client.Histogram simpleclient(RandomNumbers randomNumbers, SimpleclientHistogram histogram) { for (int i = 0; i < randomNumbers.randomNumbers.length; i++) { histogram.noLabels.observe(randomNumbers.randomNumbers[i]); } return histogram.noLabels; } @Benchmark @Threads(4) public io.opentelemetry.api.metrics.DoubleHistogram openTelemetryClassic(RandomNumbers randomNumbers, OpenTelemetryClassicHistogram histogram) { for (int i = 0; i < randomNumbers.randomNumbers.length; i++) { histogram.histogram.record(randomNumbers.randomNumbers[i]); } return histogram.histogram; } @Benchmark @Threads(4) public io.opentelemetry.api.metrics.DoubleHistogram openTelemetryExponential(RandomNumbers randomNumbers, OpenTelemetryExponentialHistogram histogram) {<FILL_FUNCTION_BODY>
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(Unit.SECONDS) .labelNames("http_status") .register(); histogram.initLabelValues("200"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {<FILL_FUNCTION_BODY>} }
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) { throw new RuntimeException(e); } finally { histogram.labelValues("200").observe(nanosToSeconds(System.nanoTime() - start)); }
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"); Tomcat.addServlet(ctx, "metrics", new PrometheusMetricsServlet()); ctx.addServletMappingDecoded("/metrics", "metrics"); tomcat.getConnector(); tomcat.start(); tomcat.getServer().await();
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") .unit(Unit.SECONDS) .labelNames("http_status") .register(); histogram.initLabelValues("200"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {<FILL_FUNCTION_BODY>} private String executeGreetingServiceRequest() throws URISyntaxException, IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(new URI("http://localhost:8081/")) .build(); HttpClient httpClient = HttpClient.newHttpClient(); HttpResponse<String> response = httpClient.send(request, ofString()); return response.body(); } }
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(greeting); } catch (Exception e) { throw new ServletException(e); } finally { histogram.labelValues("200").observe(nanosToSeconds(System.nanoTime() - start)); }
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"); Tomcat.addServlet(ctx, "metrics", new PrometheusMetricsServlet()); ctx.addServletMappingDecoded("/metrics", "metrics"); tomcat.getConnector(); tomcat.start(); tomcat.getServer().await();
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 Prometheus query // time() - process_start_time_seconds // rather than creating a custom uptime metric. Counter counter = Counter.builder() .name("uptime_seconds_total") .help("total number of seconds since this application was started") .unit(Unit.SECONDS) .register(); HTTPServer server = HTTPServer.builder() .port(9400) .buildAndStart(); System.out.println("HTTPServer listening on port http://localhost:" + server.getPort() + "/metrics"); while (true) { Thread.sleep(1000); counter.inc(); }
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.getPort() + "/metrics");
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); } protected MetricSnapshots collectMetricSnapshots(PrometheusScrapeRequest scrapeRequest) {<FILL_FUNCTION_BODY>} public List<String> getPrometheusNames() { List<String> names = new ArrayList<String>(); names.add("x_calls_total"); names.add("x_load"); return names; } }
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 = scrapeRequest.getParameterValues("target"); String targetName; String[] procs = scrapeRequest.getParameterValues("proc"); if (targetNames == null || targetNames.length == 0) { targetName = "defaultTarget"; procs = null; //ignore procs param } else { targetName = targetNames[0]; } Builder counterDataPointBuilder = CounterSnapshot.CounterDataPointSnapshot.builder(); io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot.Builder gaugeDataPointBuilder = GaugeSnapshot.GaugeDataPointSnapshot.builder(); Labels lbls = Labels.of("target", targetName); if (procs == null || procs.length == 0) { counterDataPointBuilder.labels(lbls.merge(Labels.of("proc", "defaultProc"))); gaugeDataPointBuilder.labels(lbls.merge(Labels.of("proc", "defaultProc"))); counterDataPointBuilder.value(70); gaugeDataPointBuilder.value(Math.random()); counterBuilder.dataPoint(counterDataPointBuilder.build()); gaugeBuilder.dataPoint(gaugeDataPointBuilder.build()); } else { for (int i = 0; i < procs.length; i++) { counterDataPointBuilder.labels(lbls.merge(Labels.of("proc", procs[i]))); gaugeDataPointBuilder.labels(lbls.merge(Labels.of("proc", procs[i]))); counterDataPointBuilder.value(Math.random()); gaugeDataPointBuilder.value(Math.random()); counterBuilder.dataPoint(counterDataPointBuilder.build()); gaugeBuilder.dataPoint(gaugeDataPointBuilder.build()); } } Collection<MetricSnapshot> snaps = new ArrayList<MetricSnapshot>(); snaps.add(counterBuilder.build()); snaps.add(gaugeBuilder.build()); MetricSnapshots msnaps = new MetricSnapshots(snaps); return msnaps;
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_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 Prometheus query // time() - process_start_time_seconds // rather than creating a custom uptime metric. Counter counter = Counter.builder() .name("uptime_seconds_total") .help("total number of seconds since this application was started") .unit(Unit.SECONDS) .register(); OpenTelemetryExporter.builder() .intervalSeconds(5) // ridiculously short interval for demo purposes .buildAndStart(); while (true) { Thread.sleep(1000); counter.inc(); }
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() .name("requests_total") .help("total number of requests") .labelNames("http_status") .register(); private final Histogram histogram = Histogram.builder() .name("request_duration_seconds") .help("request duration in seconds") .unit(Unit.SECONDS) .labelNames("http_status") .register(); public HelloWorldServlet() { counter.initLabelValues("200"); histogram.initLabelValues("200"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {<FILL_FUNCTION_BODY>} }
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) { throw new RuntimeException(e); } finally { counter.labelValues("200").inc(); histogram.labelValues("200").observe(nanosToSeconds(System.nanoTime() - start)); }
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()); Tomcat.addServlet(ctx, "hello", new HelloWorldServlet()); ctx.addServletMappingDecoded("/*", "hello"); Tomcat.addServlet(ctx, "metrics", new PrometheusMetricsServlet()); ctx.addServletMappingDecoded("/metrics", "metrics"); tomcat.getConnector(); tomcat.start(); tomcat.getServer().await();
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(); HTTPServer server = HTTPServer.builder() .port(9400) .buildAndStart(); System.out.println("HTTPServer listening on port http://localhost:" + server.getPort() + "/metrics"); Random random = new Random(0); while (true) { double duration = Math.abs(random.nextGaussian() / 10.0 + 0.2); String status = random.nextInt(100) < 20 ? "500" : "200"; histogram.labelValues("/", status).observe(duration); Thread.sleep(1000); }
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() .name("request_size_bytes") .help("request size in bytes") .unit(Unit.BYTES) .register(); HTTPServer server = HTTPServer.builder() .port(9400) .buildAndStart(); System.out.println("HTTPServer listening on port http://localhost:" + server.getPort() + "/metrics"); Random random = new Random(0); while (true) { double duration = Math.abs(random.nextGaussian() / 10.0 + 0.2); double size = random.nextInt(1000) + 256; requestDuration.observe(duration); requestSize.observe(size); Thread.sleep(1000); }
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 the counter is registered before or after bridging with PrometheusRegistry. Counter simpleclientCounter = Counter.build() .name("events_total") .help("total number of events") .register(); simpleclientCounter.inc(); // Expose metrics from the new PrometheusRegistry. This should contain the events_total metric. HTTPServer server = HTTPServer.builder() .port(9400) .buildAndStart(); System.out.println("HTTPServer listening on port http://localhost:" + server.getPort() + "/metrics"); Thread.currentThread().join();
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 final Integer minRetentionPeriodSeconds; private final Integer maxRetentionPeriodSeconds; private final Integer sampleIntervalMilliseconds; private ExemplarsProperties( Integer minRetentionPeriodSeconds, Integer maxRetentionPeriodSeconds, Integer sampleIntervalMilliseconds) { this.minRetentionPeriodSeconds = minRetentionPeriodSeconds; this.maxRetentionPeriodSeconds = maxRetentionPeriodSeconds; this.sampleIntervalMilliseconds = sampleIntervalMilliseconds; } /** * Minimum time how long Exemplars are kept before they may be replaced by new Exemplars. * <p> * Default see {@code ExemplarSamplerConfig.DEFAULT_MIN_RETENTION_PERIOD_SECONDS} */ public Integer getMinRetentionPeriodSeconds() { return minRetentionPeriodSeconds; } /** * Maximum time how long Exemplars are kept before they are evicted. * <p> * Default see {@code ExemplarSamplerConfig.DEFAULT_MAX_RETENTION_PERIOD_SECONDS} */ public Integer getMaxRetentionPeriodSeconds() { return maxRetentionPeriodSeconds; } /** * Time between attempts to sample new Exemplars. This is a performance improvement for high-frequency * applications, because with the sample interval we make sure that the exemplar sampler is not called * for every single request. * <p> * Default see {@code ExemplarSamplerConfig.DEFAULT_SAMPLE_INTERVAL_MILLISECONDS} */ public Integer getSampleIntervalMilliseconds() { return sampleIntervalMilliseconds; } /** * Note that this will remove entries from {@code properties}. * This is because we want to know if there are unused properties remaining after all properties have been loaded. */ static ExemplarsProperties load(String prefix, Map<Object, Object> properties) throws PrometheusPropertiesException {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(); } public static class Builder { private Integer minRetentionPeriodSeconds; private Integer maxRetentionPeriodSeconds; private Integer sampleIntervalMilliseconds; private Builder() { } public Builder minRetentionPeriodSeconds(int minRetentionPeriodSeconds) { this.minRetentionPeriodSeconds = minRetentionPeriodSeconds; return this; } public Builder maxRetentionPeriodSeconds(int maxRetentionPeriodSeconds) { this.maxRetentionPeriodSeconds = maxRetentionPeriodSeconds; return this; } public Builder sampleIntervalMilliseconds(int sampleIntervalMilliseconds) { this.sampleIntervalMilliseconds = sampleIntervalMilliseconds; return this; } public ExemplarsProperties build() { return new ExemplarsProperties(minRetentionPeriodSeconds, maxRetentionPeriodSeconds, sampleIntervalMilliseconds); } } }
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 + "." + SAMPLE_INTERVAL_MILLISECONDS, properties); Util.assertValue(minRetentionPeriodSeconds, t -> t > 0, "Expecting value > 0.", prefix, MIN_RETENTION_PERIOD_SECONDS); Util.assertValue(minRetentionPeriodSeconds, t -> t > 0, "Expecting value > 0.", prefix, MAX_RETENTION_PERIOD_SECONDS); Util.assertValue(sampleIntervalMilliseconds, t -> t > 0, "Expecting value > 0.", prefix, SAMPLE_INTERVAL_MILLISECONDS); if (minRetentionPeriodSeconds != null && maxRetentionPeriodSeconds != null) { if (minRetentionPeriodSeconds > maxRetentionPeriodSeconds) { throw new PrometheusPropertiesException(prefix + "." + MIN_RETENTION_PERIOD_SECONDS + " must not be greater than " + prefix + "." + MAX_RETENTION_PERIOD_SECONDS + "."); } } return new ExemplarsProperties( minRetentionPeriodSeconds, maxRetentionPeriodSeconds, sampleIntervalMilliseconds );
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 static final String METRIC_NAME_MUST_NOT_START_WITH = "metricNameMustNotStartWith"; private final List<String> allowedNames; private final List<String> excludedNames; private final List<String> allowedPrefixes; private final List<String> excludedPrefixes; private ExporterFilterProperties(List<String> allowedNames, List<String> excludedNames, List<String> allowedPrefixes, List<String> excludedPrefixes) { this(allowedNames, excludedNames, allowedPrefixes, excludedPrefixes, ""); } private ExporterFilterProperties(List<String> allowedNames, List<String> excludedNames, List<String> allowedPrefixes, List<String> excludedPrefixes, String prefix) { this.allowedNames = allowedNames == null ? null : Collections.unmodifiableList(new ArrayList<>(allowedNames)); this.excludedNames = excludedNames == null ? null : Collections.unmodifiableList(new ArrayList<>(excludedNames)); this.allowedPrefixes = allowedPrefixes == null ? null : Collections.unmodifiableList(new ArrayList<>(allowedPrefixes)); this.excludedPrefixes = excludedPrefixes == null ? null : Collections.unmodifiableList(new ArrayList<>(excludedPrefixes)); validate(prefix); } public List<String> getAllowedMetricNames() { return allowedNames; } public List<String> getExcludedMetricNames() { return excludedNames; } public List<String> getAllowedMetricNamePrefixes() { return allowedPrefixes; } public List<String> getExcludedMetricNamePrefixes() { return excludedPrefixes; } private void validate(String prefix) throws PrometheusPropertiesException { } /** * Note that this will remove entries from {@code properties}. * This is because we want to know if there are unused properties remaining after all properties have been loaded. */ static ExporterFilterProperties load(String prefix, Map<Object, Object> properties) throws PrometheusPropertiesException {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(); } public static class Builder { private List<String> allowedNames; private List<String> excludedNames; private List<String> allowedPrefixes; private List<String> excludedPrefixes; private Builder() { } /** * Only allowed metric names will be exposed. */ public Builder allowedNames(String... allowedNames) { this.allowedNames = Arrays.asList(allowedNames); return this; } /** * Excluded metric names will not be exposed. */ public Builder excludedNames(String... excludedNames) { this.excludedNames = Arrays.asList(excludedNames); return this; } /** * Only metrics with a name starting with an allowed prefix will be exposed. */ public Builder allowedPrefixes(String... allowedPrefixes) { this.allowedPrefixes = Arrays.asList(allowedPrefixes); return this; } /** * Metrics with a name starting with an excluded prefix will not be exposed. */ public Builder excludedPrefixes(String... excludedPrefixes) { this.excludedPrefixes = Arrays.asList(excludedPrefixes); return this; } public ExporterFilterProperties build() { return new ExporterFilterProperties(allowedNames, excludedNames, allowedPrefixes, excludedPrefixes); } } }
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_MUST_START_WITH, properties); List<String> excludedPrefixes = Util.loadStringList(prefix + "." + METRIC_NAME_MUST_NOT_START_WITH, properties); return new ExporterFilterProperties(allowedNames, excludedNames, allowedPrefixes, excludedPrefixes, prefix);
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 from {@code properties}. * This is because we want to know if there are unused properties remaining after all properties have been loaded. */ static ExporterHttpServerProperties load(String prefix, Map<Object, Object> properties) throws PrometheusPropertiesException {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(); } public static class Builder { private Integer port; private Builder() {} public Builder port(int port) { this.port = port; return this; } public ExporterHttpServerProperties build() { return new ExporterHttpServerProperties(port); } } }
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 private static String HEADERS = "headers"; // otel.exporter.otlp.headers private static String INTERVAL_SECONDS = "intervalSeconds"; // otel.metric.export.interval private static String TIMEOUT_SECONDS = "timeoutSeconds"; // otel.exporter.otlp.timeout private static String SERVICE_NAME = "serviceName"; // otel.service.name private static String SERVICE_NAMESPACE = "serviceNamespace"; private static String SERVICE_INSTANCE_ID = "serviceInstanceId"; private static String SERVICE_VERSION = "serviceVersion"; private static String RESOURCE_ATTRIBUTES = "resourceAttributes"; // otel.resource.attributes private final String protocol; private final String endpoint; private final Map<String, String> headers; private final Integer intervalSeconds; private final Integer timeoutSeconds; private final String serviceName; private final String serviceNamespace; private final String serviceInstanceId; private final String serviceVersion; private final Map<String, String> resourceAttributes; private ExporterOpenTelemetryProperties(String protocol, String endpoint, Map<String, String> headers, Integer intervalSeconds, Integer timeoutSeconds, String serviceName, String serviceNamespace, String serviceInstanceId, String serviceVersion, Map<String, String> resourceAttributes) { this.protocol = protocol; this.endpoint = endpoint; this.headers = headers; this.intervalSeconds = intervalSeconds; this.timeoutSeconds = timeoutSeconds; this.serviceName = serviceName; this.serviceNamespace = serviceNamespace; this.serviceInstanceId = serviceInstanceId; this.serviceVersion = serviceVersion; this.resourceAttributes = resourceAttributes; } public String getProtocol() { return protocol; } public String getEndpoint() { return endpoint; } public Map<String, String> getHeaders() { return headers; } public Integer getIntervalSeconds() { return intervalSeconds; } public Integer getTimeoutSeconds() { return timeoutSeconds; } public String getServiceName() { return serviceName; } public String getServiceNamespace() { return serviceNamespace; } public String getServiceInstanceId() { return serviceInstanceId; } public String getServiceVersion() { return serviceVersion; } public Map<String, String> getResourceAttributes() { return resourceAttributes; } /** * Note that this will remove entries from {@code properties}. * This is because we want to know if there are unused properties remaining after all properties have been loaded. */ static ExporterOpenTelemetryProperties load(String prefix, Map<Object, Object> properties) throws PrometheusPropertiesException {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(); } public static class Builder { private String protocol; private String endpoint; private Map<String, String> headers = new HashMap<>(); private Integer intervalSeconds; private Integer timeoutSeconds; private String serviceName; private String serviceNamespace; private String serviceInstanceId; private String serviceVersion; private Map<String, String> resourceAttributes = new HashMap<>(); private Builder() {} public Builder protocol(String protocol) { if (!protocol.equals("grpc") && !protocol.equals("http/protobuf")) { throw new IllegalArgumentException(protocol + ": Unsupported protocol. Expecting grpc or http/protobuf"); } this.protocol = protocol; return this; } public Builder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Add a request header. Call multiple times to add multiple headers. */ public Builder header(String name, String value) { this.headers.put(name, value); return this; } public Builder intervalSeconds(int intervalSeconds) { if (intervalSeconds <= 0) { throw new IllegalArgumentException(intervalSeconds + ": Expecting intervalSeconds > 0"); } this.intervalSeconds = intervalSeconds; return this; } public Builder timeoutSeconds(int timeoutSeconds) { if (timeoutSeconds <= 0) { throw new IllegalArgumentException(timeoutSeconds + ": Expecting timeoutSeconds > 0"); } this.timeoutSeconds = timeoutSeconds; return this; } public Builder serviceName(String serviceName) { this.serviceName = serviceName; return this; } public Builder serviceNamespace(String serviceNamespace) { this.serviceNamespace = serviceNamespace; return this; } public Builder serviceInstanceId(String serviceInstanceId) { this.serviceInstanceId = serviceInstanceId; return this; } public Builder serviceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; return this; } public Builder resourceAttribute(String name, String value) { this.resourceAttributes.put(name, value); return this; } public ExporterOpenTelemetryProperties build() { return new ExporterOpenTelemetryProperties(protocol, endpoint, headers, intervalSeconds, timeoutSeconds, serviceName, serviceNamespace, serviceInstanceId, serviceVersion, resourceAttributes); } } }
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 + "." + INTERVAL_SECONDS, properties); Integer timeoutSeconds = Util.loadInteger(prefix + "." + TIMEOUT_SECONDS, properties); String serviceName = Util.loadString(prefix + "." + SERVICE_NAME, properties); String serviceNamespace = Util.loadString(prefix + "." + SERVICE_NAMESPACE, properties); String serviceInstanceId = Util.loadString(prefix + "." + SERVICE_INSTANCE_ID, properties); String serviceVersion = Util.loadString(prefix + "." + SERVICE_VERSION, properties); Map<String, String> resourceAttributes = Util.loadMap(prefix + "." + RESOURCE_ATTRIBUTES, properties); Util.assertValue(intervalSeconds, t -> t > 0, "Expecting value > 0", prefix, INTERVAL_SECONDS); Util.assertValue(timeoutSeconds, t -> t > 0, "Expecting value > 0", prefix, TIMEOUT_SECONDS); if (protocol != null && !protocol.equals("grpc") && !protocol.equals("http/protobuf")) { throw new PrometheusPropertiesException(protocol + ": Unsupported OpenTelemetry exporter protocol. Expecting grpc or http/protobuf"); } return new ExporterOpenTelemetryProperties(protocol, endpoint, headers, intervalSeconds, timeoutSeconds, serviceName, serviceNamespace, serviceInstanceId, serviceVersion, resourceAttributes);
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; private ExporterProperties(Boolean includeCreatedTimestamps, Boolean exemplarsOnAllMetricTypes) { this.includeCreatedTimestamps = includeCreatedTimestamps; this.exemplarsOnAllMetricTypes = exemplarsOnAllMetricTypes; } /** * Include the {@code _created} timestamps in text format? Default is {@code false}. */ public boolean getIncludeCreatedTimestamps() { return includeCreatedTimestamps != null && includeCreatedTimestamps; } /** * Allow Exemplars on all metric types in OpenMetrics format? * Default is {@code false}, which means Exemplars will only be added for Counters and Histogram buckets. */ public boolean getExemplarsOnAllMetricTypes() { return exemplarsOnAllMetricTypes != null && exemplarsOnAllMetricTypes; } /** * Note that this will remove entries from {@code properties}. * This is because we want to know if there are unused properties remaining after all properties have been loaded. */ static ExporterProperties load(String prefix, Map<Object, Object> properties) throws PrometheusPropertiesException {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(); } public static class Builder { private Boolean includeCreatedTimestamps; private Boolean exemplarsOnAllMetricTypes; private Builder() { } /** * See {@link #getIncludeCreatedTimestamps()} */ public Builder includeCreatedTimestamps(boolean includeCreatedTimestamps) { this.includeCreatedTimestamps = includeCreatedTimestamps; return this; } /** * See {@link #getExemplarsOnAllMetricTypes()}. */ public Builder exemplarsOnAllMetricTypes(boolean exemplarsOnAllMetricTypes) { this.exemplarsOnAllMetricTypes = exemplarsOnAllMetricTypes; return this; } public ExporterProperties build() { return new ExporterProperties(includeCreatedTimestamps, 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, exemplarsOnAllMetricTypes);
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 PrometheusPropertiesException { Map<Object, Object> properties = loadProperties(externalProperties); Map<String, MetricsProperties> metricsConfigs = loadMetricsConfigs(properties); MetricsProperties defaultMetricsProperties = MetricsProperties.load("io.prometheus.metrics", properties); ExemplarsProperties exemplarConfig = ExemplarsProperties.load("io.prometheus.exemplars", properties); ExporterProperties exporterProperties = ExporterProperties.load("io.prometheus.exporter", properties); ExporterFilterProperties exporterFilterProperties = ExporterFilterProperties.load("io.prometheus.exporter.filter", properties); ExporterHttpServerProperties exporterHttpServerProperties = ExporterHttpServerProperties.load("io.prometheus.exporter.httpServer", properties); ExporterOpenTelemetryProperties exporterOpenTelemetryProperties = ExporterOpenTelemetryProperties.load("io.prometheus.exporter.opentelemetry", properties); validateAllPropertiesProcessed(properties); return new PrometheusProperties(defaultMetricsProperties, metricsConfigs, exemplarConfig, exporterProperties, exporterFilterProperties, exporterHttpServerProperties, exporterOpenTelemetryProperties); } // This will remove entries from properties when they are processed. private static Map<String, MetricsProperties> loadMetricsConfigs(Map<Object, Object> properties) { Map<String, MetricsProperties> result = new HashMap<>(); // Note that the metric name in the properties file must be as exposed in the Prometheus exposition formats, // i.e. all dots replaced with underscores. Pattern pattern = Pattern.compile("io\\.prometheus\\.metrics\\.([^.]+)\\."); // Create a copy of the keySet() for iterating. We cannot iterate directly over keySet() // because entries are removed when MetricsConfig.load(...) is called. Set<String> propertyNames = new HashSet<>(); for (Object key : properties.keySet()) { propertyNames.add(key.toString()); } for (String propertyName : propertyNames) { Matcher matcher = pattern.matcher(propertyName); if (matcher.find()) { String metricName = matcher.group(1).replace(".", "_"); if (!result.containsKey(metricName)) { result.put(metricName, MetricsProperties.load("io.prometheus.metrics." + metricName, properties)); } } } return result; } // If there are properties left starting with io.prometheus it's likely a typo, // because we didn't use that property. // Throw a config error to let the user know that this property doesn't exist. private static void validateAllPropertiesProcessed(Map<Object, Object> properties) { for (Object key : properties.keySet()) { if (key.toString().startsWith("io.prometheus")) { throw new PrometheusPropertiesException(key + ": Unknown property"); } } } private static Map<Object, Object> loadProperties(Map<Object, Object> externalProperties) { Map<Object, Object> properties = new HashMap<>(); properties.putAll(loadPropertiesFromClasspath()); properties.putAll(loadPropertiesFromFile()); // overriding the entries from the classpath file properties.putAll(System.getProperties()); // overriding the entries from the properties file properties.putAll(externalProperties); // overriding all the entries above // TODO: Add environment variables like EXEMPLARS_ENABLED. return properties; } private static Properties loadPropertiesFromClasspath() {<FILL_FUNCTION_BODY>} private static Properties loadPropertiesFromFile() throws PrometheusPropertiesException { Properties properties = new Properties(); String path = System.getProperty("prometheus.config"); if (System.getenv("PROMETHEUS_CONFIG") != null) { path = System.getenv("PROMETHEUS_CONFIG"); } if (path != null) { try (InputStream stream = Files.newInputStream(Paths.get(path))) { properties.load(stream); } catch (IOException e) { throw new PrometheusPropertiesException("Failed to read Prometheus properties from " + path + ": " + e.getMessage(), e); } } return properties; } }
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> properties) throws PrometheusPropertiesException { String property = getProperty(name, properties); if (property != null) { if (!"true".equalsIgnoreCase(property) && !"false".equalsIgnoreCase(property)) { throw new PrometheusPropertiesException(name + "=" + property + ": Expecting 'true' or 'false'"); } return Boolean.parseBoolean(property); } return null; } static List<Double> toList(double... values) { if (values == null) { return null; } List<Double> result = new ArrayList<>(values.length); for (double value : values) { result.add(value); } return result; } static String loadString(String name, Map<Object, Object> properties) throws PrometheusPropertiesException { return getProperty(name, properties); } static List<String> loadStringList(String name, Map<Object, Object> properties) throws PrometheusPropertiesException {<FILL_FUNCTION_BODY>} static List<Double> loadDoubleList(String name, Map<Object, Object> properties) throws PrometheusPropertiesException { String property = getProperty(name, properties); if (property != null) { String[] numbers = property.split("\\s*,\\s*"); Double[] result = new Double[numbers.length]; for (int i = 0; i < numbers.length; i++) { try { if ("+Inf".equals(numbers[i].trim())) { result[i] = Double.POSITIVE_INFINITY; } else { result[i] = Double.parseDouble(numbers[i]); } } catch (NumberFormatException e) { throw new PrometheusPropertiesException(name + "=" + property + ": Expecting comma separated list of double values"); } } return Arrays.asList(result); } return null; } // Map is represented as "key1=value1,key2=value2" static Map<String, String> loadMap(String name, Map<Object, Object> properties) throws PrometheusPropertiesException { Map<String, String> result = new HashMap<>(); String property = getProperty(name, properties); if (property != null) { String[] pairs = property.split(","); for (String pair : pairs) { if (pair.contains("=")) { String[] keyValue = pair.split("=", 1); if (keyValue.length == 2) { String key = keyValue[0].trim(); String value = keyValue[1].trim(); if (key.length() > 0 && value.length() > 0) { result.putIfAbsent(key, value); } } } } } return result; } static Integer loadInteger(String name, Map<Object, Object> properties) throws PrometheusPropertiesException { String property = getProperty(name, properties); if (property != null) { try { return Integer.parseInt(property); } catch (NumberFormatException e) { throw new PrometheusPropertiesException(name + "=" + property + ": Expecting integer value"); } } return null; } static Double loadDouble(String name, Map<Object, Object> properties) throws PrometheusPropertiesException { String property = getProperty(name, properties); if (property != null) { try { return Double.parseDouble(property); } catch (NumberFormatException e) { throw new PrometheusPropertiesException(name + "=" + property + ": Expecting double value"); } } return null; } static Long loadLong(String name, Map<Object, Object> properties) throws PrometheusPropertiesException { String property = getProperty(name, properties); if (property != null) { try { return Long.parseLong(property); } catch (NumberFormatException e) { throw new PrometheusPropertiesException(name + "=" + property + ": Expecting long value"); } } return null; } static <T extends Number> void assertValue(T number, Predicate<T> predicate, String message, String prefix, String name) throws PrometheusPropertiesException { if (number != null && !predicate.test(number)) { String fullMessage = prefix == null ? name + ": " + message : prefix + "." + name + ": " + message; throw new PrometheusPropertiesException(fullMessage); } } }
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 observeFunction) { this.observeFunction = observeFunction; } /** * Records the observed duration in seconds since this {@code Timer} instance was created. * @return the observed duration in seconds. */ public double observeDuration() {<FILL_FUNCTION_BODY>} /** * Same as {@link #observeDuration()}. */ @Override public void close() { observeDuration(); } }
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_RETENTION_PERIOD_SECONDS = 70; /** * See {@link ExemplarsProperties#getSampleIntervalMilliseconds()} */ private static final int DEFAULT_SAMPLE_INTERVAL_MILLISECONDS = 90; private final long minRetentionPeriodMillis; private final long maxRetentionPeriodMillis; private final long sampleIntervalMillis; private final double[] histogramClassicUpperBounds; // null unless it's a classic histogram private final int numberOfExemplars; // if histogramClassicUpperBounds != null, then numberOfExemplars == histogramClassicUpperBounds.length /** * Constructor for all metric types except classic histograms. * * @param properties See {@link PrometheusProperties#getExemplarProperties()}. * @param numberOfExemplars Counters have 1 Exemplar, native histograms and summaries have 4 Exemplars by default. * For classic histogram use {@link #ExemplarSamplerConfig(ExemplarsProperties, double[])}. */ public ExemplarSamplerConfig(ExemplarsProperties properties, int numberOfExemplars) { this(properties, numberOfExemplars, null); } /** * Constructor for classic histogram metrics. * * @param properties See {@link PrometheusProperties#getExemplarProperties()}. * @param histogramClassicUpperBounds the ExemplarSampler will provide one Exemplar per histogram bucket. * Must be sorted, and must include the +Inf bucket. */ public ExemplarSamplerConfig(ExemplarsProperties properties, double[] histogramClassicUpperBounds) { this(properties, histogramClassicUpperBounds.length, histogramClassicUpperBounds); } private ExemplarSamplerConfig(ExemplarsProperties properties, int numberOfExemplars, double[] histogramClassicUpperBounds) { this( TimeUnit.SECONDS.toMillis(getOrDefault(properties.getMinRetentionPeriodSeconds(), DEFAULT_MIN_RETENTION_PERIOD_SECONDS)), TimeUnit.SECONDS.toMillis(getOrDefault(properties.getMaxRetentionPeriodSeconds(), DEFAULT_MAX_RETENTION_PERIOD_SECONDS)), getOrDefault(properties.getSampleIntervalMilliseconds(), DEFAULT_SAMPLE_INTERVAL_MILLISECONDS), numberOfExemplars, histogramClassicUpperBounds); } ExemplarSamplerConfig(long minRetentionPeriodMillis, long maxRetentionPeriodMillis, long sampleIntervalMillis, int numberOfExemplars, double[] histogramClassicUpperBounds) { this.minRetentionPeriodMillis = minRetentionPeriodMillis; this.maxRetentionPeriodMillis = maxRetentionPeriodMillis; this.sampleIntervalMillis = sampleIntervalMillis; this.numberOfExemplars = numberOfExemplars; this.histogramClassicUpperBounds = histogramClassicUpperBounds; validate(); } private void validate() {<FILL_FUNCTION_BODY>} private static <T> T getOrDefault(T result, T defaultValue) { return result != null ? result : defaultValue; } /** * May be {@code null}. */ public double[] getHistogramClassicUpperBounds() { return histogramClassicUpperBounds; } /** * See {@link ExemplarsProperties#getMinRetentionPeriodSeconds()} */ public long getMinRetentionPeriodMillis() { return minRetentionPeriodMillis; } /** * See {@link ExemplarsProperties#getMaxRetentionPeriodSeconds()} */ public long getMaxRetentionPeriodMillis() { return maxRetentionPeriodMillis; } /** * See {@link ExemplarsProperties#getSampleIntervalMilliseconds()} */ public long getSampleIntervalMillis() { return sampleIntervalMillis; } /** * Defaults: Counters have one Exemplar, native histograms and summaries have 4 Exemplars, classic histograms have one Exemplar per bucket. */ public int getNumberOfExemplars() { return numberOfExemplars; } }
if (minRetentionPeriodMillis <= 0) { throw new IllegalArgumentException(minRetentionPeriodMillis + ": minRetentionPeriod must be > 0."); } if (maxRetentionPeriodMillis <= 0) { throw new IllegalArgumentException(maxRetentionPeriodMillis + ": maxRetentionPeriod must be > 0."); } if (histogramClassicUpperBounds != null) { if (histogramClassicUpperBounds.length == 0 || histogramClassicUpperBounds[histogramClassicUpperBounds.length - 1] != Double.POSITIVE_INFINITY) { throw new IllegalArgumentException("histogramClassicUpperBounds must contain the +Inf bucket."); } if (histogramClassicUpperBounds.length != numberOfExemplars) { throw new IllegalArgumentException("histogramClassicUpperBounds.length must be equal to numberOfExemplars."); } double bound = histogramClassicUpperBounds[0]; for (int i = 1; i < histogramClassicUpperBounds.length; i++) { if (bound >= histogramClassicUpperBounds[i]) { throw new IllegalArgumentException("histogramClassicUpperBounds must be sorted and must not contain duplicates."); } } } if (numberOfExemplars <= 0) { throw new IllegalArgumentException(numberOfExemplars + ": numberOfExemplars 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 final Object runLock = new Object(); boolean append(double value) { long count = observationCount.incrementAndGet(); if ((count & signBit) == 0) { return false; // sign bit not set -> buffer not active. } else { doAppend(value); return true; } } private void doAppend(double amount) {<FILL_FUNCTION_BODY>} /** * Must be called by the runnable in the run() method. */ void reset() { reset = true; } <T extends DataPointSnapshot> T run(Function<Long, Boolean> complete, Supplier<T> runnable, Consumer<Double> observeFunction) { double[] buffer; int bufferSize; T result; synchronized (runLock) { Long count = observationCount.getAndAdd(signBit); while (!complete.apply(count)) { Thread.yield(); } result = runnable.get(); int expectedBufferSize; if (reset) { expectedBufferSize = (int) ((observationCount.getAndSet(0) & ~signBit) - count); reset = false; } else { expectedBufferSize = (int) (observationCount.addAndGet(signBit) - count); } while (bufferPos != expectedBufferSize) { Thread.yield(); } buffer = observationBuffer; bufferSize = bufferPos; observationBuffer = new double[0]; bufferPos = 0; } for (int i = 0; i < bufferSize; i++) { observeFunction.accept(buffer[i]); } return result; } }
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 MetricWithFixedMetadata.Builder<B, M> { protected Builder(List<String> illegalLabelNames, PrometheusProperties properties) { super(illegalLabelNames, properties); } } }
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; } else { if (labelValues == null) { throw new IllegalArgumentException(this.getClass().getSimpleName() + " was created with label names, but the callback was called without label values."); } if (labelValues.length != labelNames.length) { throw new IllegalArgumentException(this.getClass().getSimpleName() + " was created with " + labelNames.length + " label names, but the callback was called with " + labelValues.length + " label values."); } return constLabels.merge(Labels.of(labelNames, labelValues)); }
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, // we will be using the LongAdder and get the best performance. private final LongAdder longValue = new LongAdder(); private final long createdTimeMillis = System.currentTimeMillis(); private final ExemplarSampler exemplarSampler; // null if isExemplarsEnabled() is false private DataPoint(ExemplarSampler exemplarSampler) { this.exemplarSampler = exemplarSampler; } /** * {@inheritDoc} */ public double get() { return longValue.sum() + doubleValue.sum(); } /** * {@inheritDoc} */ public long getLongValue() { return longValue.sum() + (long) doubleValue.sum(); } /** * {@inheritDoc} */ @Override public void inc(long amount) { validateAndAdd(amount); if (isExemplarsEnabled()) { exemplarSampler.observe(amount); } } /** * {@inheritDoc} */ @Override public void inc(double amount) { validateAndAdd(amount); if (isExemplarsEnabled()) { exemplarSampler.observe(amount); } } /** * {@inheritDoc} */ @Override public void incWithExemplar(long amount, Labels labels) { validateAndAdd(amount); if (isExemplarsEnabled()) { exemplarSampler.observeWithExemplar(amount, labels); } } /** * {@inheritDoc} */ @Override public void incWithExemplar(double amount, Labels labels) { validateAndAdd(amount); if (isExemplarsEnabled()) { exemplarSampler.observeWithExemplar(amount, labels); } } private void validateAndAdd(long amount) { if (amount < 0) { throw new IllegalArgumentException("Negative increment " + amount + " is illegal for Counter metrics."); } longValue.add(amount); } private void validateAndAdd(double amount) { if (amount < 0) { throw new IllegalArgumentException("Negative increment " + amount + " is illegal for Counter metrics."); } doubleValue.add(amount); } private CounterSnapshot.CounterDataPointSnapshot collect(Labels labels) {<FILL_FUNCTION_BODY>} }
// 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 (exemplarSampler != null) { for (Exemplar exemplar : exemplarSampler.collect()) { if (latestExemplar == null || exemplar.getTimestampMillis() > latestExemplar.getTimestampMillis()) { latestExemplar = exemplar; } } } return new CounterSnapshot.CounterDataPointSnapshot(get(), labels, latestExemplar, createdTimeMillis);
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[]) <variables>private final ConcurrentHashMap<List<java.lang.String>,io.prometheus.metrics.core.metrics.Counter.DataPoint> data,private volatile io.prometheus.metrics.core.metrics.Counter.DataPoint noLabels
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 = builder.callback; if (callback == null) { throw new IllegalArgumentException("callback cannot be null"); } } @Override public CounterSnapshot collect() {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties properties) { return new Builder(properties); } public static class Builder extends CallbackMetric.Builder<CounterWithCallback.Builder, CounterWithCallback> { private Consumer<Callback> callback; public Builder callback(Consumer<Callback> callback) { this.callback = callback; return self(); } private Builder(PrometheusProperties properties) { super(Collections.emptyList(), properties); } /** * The {@code _total} suffix will automatically be appended if it's missing. * <pre>{@code * CounterWithCallback c1 = CounterWithCallback.builder() * .name("events_total") * .build(); * CounterWithCallback c2 = CounterWithCallback.builder() * .name("events") * .build(); * }</pre> * In the example above both {@code c1} and {@code c2} would be named {@code "events_total"} in Prometheus. * <p> * Throws an {@link IllegalArgumentException} if * {@link io.prometheus.metrics.model.snapshots.PrometheusNaming#isValidMetricName(String) MetricMetadata.isValidMetricName(name)} * is {@code false}. */ @Override public Builder name(String name) { return super.name(Counter.stripTotalSuffix(name)); } @Override public CounterWithCallback build() { return new CounterWithCallback(this); } @Override protected Builder self() { return this; } } }
List<CounterSnapshot.CounterDataPointSnapshot> dataPoints = new ArrayList<>(); callback.accept((value, labelValues) -> { dataPoints.add(new CounterSnapshot.CounterDataPointSnapshot(value, makeLabels(labelValues), null, 0L)); }); return new CounterSnapshot(getMetadata(), dataPoints);
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); MetricsProperties[] properties = getMetricProperties(builder, prometheusProperties); exemplarsEnabled = getConfigProperty(properties, MetricsProperties::getExemplarsEnabled); if (exemplarsEnabled) { exemplarSamplerConfig = new ExemplarSamplerConfig(prometheusProperties.getExemplarProperties(), 1); } else { exemplarSamplerConfig = null; } } /** * {@inheritDoc} */ @Override public void inc(double amount) { getNoLabels().inc(amount); } /** * {@inheritDoc} */ @Override public double get() { return getNoLabels().get(); } /** * {@inheritDoc} */ @Override public void incWithExemplar(double amount, Labels labels) { getNoLabels().incWithExemplar(amount, labels); } /** * {@inheritDoc} */ @Override public void set(double value) { getNoLabels().set(value); } /** * {@inheritDoc} */ @Override public void setWithExemplar(double value, Labels labels) { getNoLabels().setWithExemplar(value, labels); } /** * {@inheritDoc} */ @Override public GaugeSnapshot collect() { return (GaugeSnapshot) super.collect(); } @Override protected GaugeSnapshot collect(List<Labels> labels, List<DataPoint> metricData) {<FILL_FUNCTION_BODY>} @Override protected DataPoint newDataPoint() { if (isExemplarsEnabled()) { return new DataPoint(new ExemplarSampler(exemplarSamplerConfig)); } else { return new DataPoint(null); } } @Override protected boolean isExemplarsEnabled() { return exemplarsEnabled; } class DataPoint implements GaugeDataPoint { private final ExemplarSampler exemplarSampler; // null if isExemplarsEnabled() is false private DataPoint(ExemplarSampler exemplarSampler) { this.exemplarSampler = exemplarSampler; } private final AtomicLong value = new AtomicLong(Double.doubleToRawLongBits(0)); /** * {@inheritDoc} */ @Override public void inc(double amount) { long next = value.updateAndGet(l -> Double.doubleToRawLongBits(Double.longBitsToDouble(l) + amount)); if (isExemplarsEnabled()) { exemplarSampler.observe(Double.longBitsToDouble(next)); } } /** * {@inheritDoc} */ @Override public void incWithExemplar(double amount, Labels labels) { long next = value.updateAndGet(l -> Double.doubleToRawLongBits(Double.longBitsToDouble(l) + amount)); if (isExemplarsEnabled()) { exemplarSampler.observeWithExemplar(Double.longBitsToDouble(next), labels); } } /** * {@inheritDoc} */ @Override public void set(double value) { this.value.set(Double.doubleToRawLongBits(value)); if (isExemplarsEnabled()) { exemplarSampler.observe(value); } } /** * {@inheritDoc} */ @Override public double get() { return Double.longBitsToDouble(value.get()); } /** * {@inheritDoc} */ @Override public void setWithExemplar(double value, Labels labels) { this.value.set(Double.doubleToRawLongBits(value)); if (isExemplarsEnabled()) { exemplarSampler.observeWithExemplar(value, labels); } } private GaugeSnapshot.GaugeDataPointSnapshot collect(Labels labels) { // Read the exemplar first. Otherwise, there is a race condition where you might // see an Exemplar for a value that's not represented in getValue() yet. // If there are multiple Exemplars (by default it's just one), use the oldest // so that we don't violate min age. Exemplar oldest = null; if (isExemplarsEnabled()) { for (Exemplar exemplar : exemplarSampler.collect()) { if (oldest == null || exemplar.getTimestampMillis() < oldest.getTimestampMillis()) { oldest = exemplar; } } } return new GaugeSnapshot.GaugeDataPointSnapshot(get(), labels, oldest); } } public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder extends StatefulMetric.Builder<Builder, Gauge> { private Builder(PrometheusProperties config) { super(Collections.emptyList(), config); } @Override public Gauge build() { return new Gauge(this, properties); } @Override protected Builder self() { return this; } } }
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[]) <variables>private final ConcurrentHashMap<List<java.lang.String>,io.prometheus.metrics.core.metrics.Gauge.DataPoint> data,private volatile io.prometheus.metrics.core.metrics.Gauge.DataPoint noLabels
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 = builder.callback; if (callback == null) { throw new IllegalArgumentException("callback cannot be null"); } } @Override public GaugeSnapshot collect() {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties properties) { return new Builder(properties); } public static class Builder extends CallbackMetric.Builder<GaugeWithCallback.Builder, GaugeWithCallback> { private Consumer<Callback> callback; public Builder callback(Consumer<Callback> callback) { this.callback = callback; return self(); } private Builder(PrometheusProperties properties) { super(Collections.emptyList(), properties); } @Override public GaugeWithCallback build() { return new GaugeWithCallback(this); } @Override protected Builder self() { return this; } } }
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 * Info info1 = Info.builder() * .name("runtime_info") * .build(); * Info info2 = Info.builder() * .name("runtime") * .build(); * }</pre> * In the example above both {@code info1} and {@code info2} will be named {@code "runtime_info"} in Prometheus. * <p> * Throws an {@link IllegalArgumentException} if * {@link io.prometheus.metrics.model.snapshots.PrometheusNaming#isValidMetricName(String) MetricMetadata.isValidMetricName(name)} * is {@code false}. */ @Override public Builder name(String name) { return super.name(stripInfoSuffix(name)); } /** * Throws an {@link UnsupportedOperationException} because Info metrics cannot have a unit. */ @Override public Builder unit(Unit unit) { if (unit != null) { throw new UnsupportedOperationException("Info metrics cannot have a unit."); } return this; } private static String stripInfoSuffix(String name) {<FILL_FUNCTION_BODY>} @Override public Info build() { return new Info(this); } @Override protected Builder self() { return this; } }
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) { this.illegalLabelNames = new ArrayList<>(illegalLabelNames); this.properties = properties; } // ConstLabels are only used rarely. In particular, do not use them to // attach the same labels to all your metrics. Those use cases are // better covered by target labels set by the scraping Prometheus // server, or by one specific metric (e.g. a build_info or a // machine_role metric). See also // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels public B constLabels(Labels constLabels) {<FILL_FUNCTION_BODY>} public M register() { return register(PrometheusRegistry.defaultRegistry); } public M register(PrometheusRegistry registry) { M metric = build(); registry.register(metric); return metric; } public abstract M build(); protected abstract B self(); }
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.constLabels = constLabels; return self();
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, builder.unit); this.labelNames = Arrays.copyOf(builder.labelNames, builder.labelNames.length); } protected MetricMetadata getMetadata() { return metadata; } private String makeName(String name, Unit unit) {<FILL_FUNCTION_BODY>} @Override public String getPrometheusName() { return metadata.getPrometheusName(); } public static abstract class Builder<B extends Builder<B, M>, M extends MetricWithFixedMetadata> extends Metric.Builder<B, M> { protected String name; private Unit unit; private String help; private String[] labelNames = new String[0]; protected Builder(List<String> illegalLabelNames, PrometheusProperties properties) { super(illegalLabelNames, properties); } public B name(String name) { if (!PrometheusNaming.isValidMetricName(name)) { throw new IllegalArgumentException("'" + name + "': Illegal metric name."); } this.name = name; return self(); } public B unit(Unit unit) { this.unit = unit; return self(); } public B help(String help) { this.help = help; return self(); } public B labelNames(String... labelNames) { for (String labelName : labelNames) { if (!PrometheusNaming.isValidLabelName(labelName)) { throw new IllegalArgumentException(labelName + ": illegal label name"); } if (illegalLabelNames.contains(labelName)) { throw new IllegalArgumentException(labelName + ": illegal label name for this metric type"); } if (constLabels.contains(labelName)) { throw new IllegalArgumentException(labelName + ": duplicate label name"); } } this.labelNames = labelNames; return self(); } public B constLabels(Labels constLabels) { for (String labelName : labelNames) { if (constLabels.contains(labelName)) { // Labels.contains() treats dots like underscores throw new IllegalArgumentException(labelName + ": duplicate label name"); } } return super.constLabels(constLabels); } @Override public abstract M build(); @Override protected abstract B self(); } }
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 currentTimeMillis = System::currentTimeMillis; // to be replaced in unit tests /** * Example: If the {@code maxAgeSeconds} is 60 and {@code ageBuckets} is 3, then 3 instances of {@code T} * are maintained and the sliding window moves to the next instance of T every 20 seconds. * * @param clazz type of T * @param constructor for creating a new instance of T as the old one gets evicted * @param observeFunction for observing a value (e.g. calling {@code t.observe(value)} * @param maxAgeSeconds after this amount of time an instance of T gets evicted. * @param ageBuckets number of age buckets. */ public SlidingWindow(Class<T> clazz, Supplier<T> constructor, ObjDoubleConsumer<T> observeFunction, long maxAgeSeconds, int ageBuckets) { this.constructor = constructor; this.observeFunction = observeFunction; this.ringBuffer = (T[]) Array.newInstance(clazz, ageBuckets); for (int i = 0; i < ringBuffer.length; i++) { this.ringBuffer[i] = constructor.get(); } this.currentBucket = 0; this.lastRotateTimestampMillis = currentTimeMillis.getAsLong(); this.durationBetweenRotatesMillis = TimeUnit.SECONDS.toMillis(maxAgeSeconds) / ageBuckets; } /** * Get the currently active instance of {@code T}. */ public synchronized T current() { return rotate(); } /** * Observe a value. */ public synchronized void observe(double value) { rotate(); for (T t : ringBuffer) { observeFunction.accept(t, value); } } private T rotate() {<FILL_FUNCTION_BODY>} }
long timeSinceLastRotateMillis = currentTimeMillis.getAsLong() - lastRotateTimestampMillis; while (timeSinceLastRotateMillis > durationBetweenRotatesMillis) { ringBuffer[currentBucket] = constructor.get(); if (++currentBucket >= ringBuffer.length) { currentBucket = 0; } timeSinceLastRotateMillis -= durationBetweenRotatesMillis; lastRotateTimestampMillis += durationBetweenRotatesMillis; } return ringBuffer[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[] properties = getMetricProperties(builder, prometheusProperties); exemplarsEnabled = getConfigProperty(properties, MetricsProperties::getExemplarsEnabled); this.names = builder.names; // builder.names is already a validated copy for (String name : names) { if (this.getMetadata().getPrometheusName().equals(prometheusName(name))) { throw new IllegalArgumentException("Label name " + name + " is illegal (can't use the metric name as label name in state set metrics)"); } } } /** * {@inheritDoc} */ @Override public StateSetSnapshot collect() { return (StateSetSnapshot) super.collect(); } /** * {@inheritDoc} */ @Override public void setTrue(String state) { getNoLabels().setTrue(state); } /** * {@inheritDoc} */ @Override public void setFalse(String state) { getNoLabels().setFalse(state); } @Override protected StateSetSnapshot collect(List<Labels> labels, List<DataPoint> metricDataList) {<FILL_FUNCTION_BODY>} @Override protected DataPoint newDataPoint() { return new DataPoint(); } @Override protected boolean isExemplarsEnabled() { return exemplarsEnabled; } class DataPoint implements StateSetDataPoint { private final boolean[] values = new boolean[names.length]; private DataPoint() { } /** * {@inheritDoc} */ @Override public void setTrue(String state) { set(state, true); } /** * {@inheritDoc} */ @Override public void setFalse(String state) { set(state, false); } private void set(String name, boolean value) { for (int i = 0; i < names.length; i++) { if (names[i].equals(name)) { values[i] = value; return; } } throw new IllegalArgumentException(name + ": unknown state"); } } public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder extends StatefulMetric.Builder<Builder, StateSet> { private String[] names; private Builder(PrometheusProperties config) { super(Collections.emptyList(), config); } /** * Declare the states that should be represented by this StateSet. */ public Builder states(Class<? extends Enum<?>> enumClass) { return states(Stream.of(enumClass.getEnumConstants()).map(Enum::toString).toArray(String[]::new)); } /** * Declare the states that should be represented by this StateSet. */ public Builder states(String... stateNames) { if (stateNames.length == 0) { throw new IllegalArgumentException("states cannot be empty"); } this.names = Stream.of(stateNames) .distinct() .sorted() .toArray(String[]::new); return this; } @Override public StateSet build() { if (names == null) { throw new IllegalStateException("State names are required when building a StateSet."); } return new StateSet(this, properties); } @Override protected Builder self() { return this; } } }
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(getMetadata(), data);
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[]) <variables>private final ConcurrentHashMap<List<java.lang.String>,io.prometheus.metrics.core.metrics.StateSet.DataPoint> data,private volatile io.prometheus.metrics.core.metrics.StateSet.DataPoint noLabels
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 volatile T noLabels; protected StatefulMetric(Builder<?, ?> builder) { super(builder); } /** * labels and metricData have the same size. labels.get(i) are the labels for metricData.get(i). */ protected abstract MetricSnapshot collect(List<Labels> labels, List<T> metricData); public MetricSnapshot collect() { if (labelNames.length == 0 && data.size() == 0) { // This is a metric without labels that has not been used yet. Initialize the data on the fly. labelValues(); } List<Labels> labels = new ArrayList<>(data.size()); List<T> metricData = new ArrayList<>(data.size()); for (Map.Entry<List<String>, T> entry : data.entrySet()) { String[] labelValues = entry.getKey().toArray(new String[labelNames.length]); labels.add(constLabels.merge(labelNames, labelValues)); metricData.add(entry.getValue()); } return collect(labels, metricData); } /** * Initialize label values. * <p> * Example: Imagine you have a counter for payments as follows * <pre> * payment_transactions_total{payment_type="credit card"} 7.0 * payment_transactions_total{payment_type="paypal"} 3.0 * </pre> * Now, the data points for the {@code payment_type} label values get initialized when they are * first used, i.e. the first time you call * <pre>{@code * counter.labelValues("paypal").inc(); * }</pre> * the data point with label {@code payment_type="paypal"} will go from non-existent to having value {@code 1.0}. * <p> * In some cases this is confusing, and you want to have data points initialized on application start * with an initial value of {@code 0.0}: * <pre> * payment_transactions_total{payment_type="credit card"} 0.0 * payment_transactions_total{payment_type="paypal"} 0.0 * </pre> * {@code initLabelValues(...)} can be used to initialize label value, so that the data points * show up in the exposition format with an initial value of zero. */ public void initLabelValues(String... labelValues) { labelValues(labelValues); } public D labelValues(String... labelValues) { if (labelValues.length != labelNames.length) { if (labelValues.length == 0) { throw new IllegalArgumentException(getClass().getSimpleName() + " " + getMetadata().getName() + " was created with label names, so you must call labelValues(...) when using it."); } else { throw new IllegalArgumentException("Expected " + labelNames.length + " label values, but got " + labelValues.length + "."); } } return data.computeIfAbsent(Arrays.asList(labelValues), l -> newDataPoint()); } /** * Remove the data point with the given label values. * See <a href="https://prometheus.io/docs/instrumenting/writing_clientlibs/#labels">https://prometheus.io/docs/instrumenting/writing_clientlibs/#labels</a>. */ public void remove(String... labelValues) { data.remove(Arrays.asList(labelValues)); } /** * Reset the metric (remove all data points). */ public void clear() { data.clear(); } protected abstract T newDataPoint(); protected T getNoLabels() { if (noLabels == null) { // Note that this will throw an IllegalArgumentException if labelNames is not empty. noLabels = (T) labelValues(); } return noLabels; } protected MetricsProperties[] getMetricProperties(Builder builder, PrometheusProperties prometheusProperties) {<FILL_FUNCTION_BODY>} protected <T> T getConfigProperty(MetricsProperties[] properties, Function<MetricsProperties, T> getter) { T result; for (MetricsProperties props : properties) { result = getter.apply(props); if (result != null) { return result; } } throw new IllegalStateException("Missing default config. This is a bug in the Prometheus metrics core library."); } protected abstract boolean isExemplarsEnabled(); static abstract class Builder<B extends Builder<B, M>, M extends StatefulMetric<?, ?>> extends MetricWithFixedMetadata.Builder<B, M> { protected Boolean exemplarsEnabled; protected Builder(List<String> illegalLabelNames, PrometheusProperties config) { super(illegalLabelNames, config); } /** * Allow Exemplars for this metric. */ public B withExemplars() { this.exemplarsEnabled = TRUE; return self(); } /** * Turn off Exemplars for this metric. */ public B withoutExemplars() { this.exemplarsEnabled = FALSE; return self(); } /** * Override if there are more properties than just exemplars enabled. */ protected MetricsProperties toProperties() { return MetricsProperties.builder() .exemplarsEnabled(exemplarsEnabled) .build(); } /** * Override if there are more properties than just exemplars enabled. */ public MetricsProperties getDefaultProperties() { return MetricsProperties.builder() .exemplarsEnabled(true) .build(); } } }
String metricName = getMetadata().getName(); if (prometheusProperties.getMetricProperties(metricName) != null) { return new MetricsProperties[]{ prometheusProperties.getMetricProperties(metricName), // highest precedence builder.toProperties(), // second-highest precedence prometheusProperties.getDefaultMetricProperties(), // third-highest precedence builder.getDefaultProperties() // fallback }; } else { return new MetricsProperties[]{ builder.toProperties(), // highest precedence prometheusProperties.getDefaultMetricProperties(), // second-highest precedence builder.getDefaultProperties() // fallback }; }
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)} */ public static final int DEFAULT_NUMBER_OF_AGE_BUCKETS = 5; private final List<CKMSQuantiles.Quantile> quantiles = new ArrayList<>(); private Long maxAgeSeconds; private Integer ageBuckets; private Builder(PrometheusProperties properties) { super(Collections.singletonList("quantile"), properties); } private static double defaultError(double quantile) { if (quantile <= 0.01 || quantile >= 0.99) { return 0.001; } else if (quantile <= 0.02 || quantile >= 0.98) { return 0.005; } else { return 0.01; } } /** * Add a quantile. See {@link #quantile(double, double)}. * <p> * Default errors are: * <ul> * <li>error = 0.001 if quantile &lt;= 0.01 or quantile &gt;= 0.99</li> * <li>error = 0.005 if quantile &lt;= 0.02 or quantile &gt;= 0.98</li> * <li>error = 0.01 else. * </ul> */ public Builder quantile(double quantile) { return quantile(quantile, defaultError(quantile)); } /** * Add a quantile. Call multiple times to add multiple quantiles. * <p> * Example: The following will track the 0.95 quantile: * <pre>{@code * .quantile(0.95, 0.001) * }</pre> * The second argument is the acceptable error margin, i.e. with the code above the quantile * will not be exactly the 0.95 quantile but something between 0.949 and 0.951. * <p> * There are two special cases: * <ul> * <li>{@code .quantile(0.0, 0.0)} gives you the minimum observed value</li> * <li>{@code .quantile(1.0, 0.0)} gives you the maximum observed value</li> * </ul> */ public Builder quantile(double quantile, double error) { if (quantile < 0.0 || quantile > 1.0) { throw new IllegalArgumentException("Quantile " + quantile + " invalid: Expected number between 0.0 and 1.0."); } if (error < 0.0 || error > 1.0) { throw new IllegalArgumentException("Error " + error + " invalid: Expected number between 0.0 and 1.0."); } quantiles.add(new CKMSQuantiles.Quantile(quantile, error)); return this; } /** * The quantiles are relative to a moving time window. * {@code maxAgeSeconds} is the size of that time window. * Default is {@link #DEFAULT_MAX_AGE_SECONDS}. */ public Builder maxAgeSeconds(long maxAgeSeconds) {<FILL_FUNCTION_BODY>} /** * The quantiles are relative to a moving time window. * The {@code numberOfAgeBuckets} defines how smoothly the time window moves forward. * For example, if the time window is 5 minutes and has 5 age buckets, * then it is moving forward every minute by one minute. * Default is {@link #DEFAULT_NUMBER_OF_AGE_BUCKETS}. */ public Builder numberOfAgeBuckets(int ageBuckets) { if (ageBuckets <= 0) { throw new IllegalArgumentException("ageBuckets cannot be " + ageBuckets); } this.ageBuckets = ageBuckets; return this; } @Override protected MetricsProperties toProperties() { double[] quantiles = null; double[] quantileErrors = null; if (!this.quantiles.isEmpty()) { quantiles = new double[this.quantiles.size()]; quantileErrors = new double[this.quantiles.size()]; for (int i = 0; i < this.quantiles.size(); i++) { quantiles[i] = this.quantiles.get(i).quantile; quantileErrors[i] = this.quantiles.get(i).epsilon; } } return MetricsProperties.builder() .exemplarsEnabled(exemplarsEnabled) .summaryQuantiles(quantiles) .summaryQuantileErrors(quantileErrors) .summaryNumberOfAgeBuckets(ageBuckets) .summaryMaxAgeSeconds(maxAgeSeconds) .build(); } /** * Default properties for summary metrics. */ @Override public MetricsProperties getDefaultProperties() { return MetricsProperties.builder() .exemplarsEnabled(true) .summaryQuantiles() .summaryNumberOfAgeBuckets(DEFAULT_NUMBER_OF_AGE_BUCKETS) .summaryMaxAgeSeconds(DEFAULT_MAX_AGE_SECONDS) .build(); } @Override public Summary build() { return new Summary(this, properties); } @Override protected Builder self() { return this; } }
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[]) <variables>private final ConcurrentHashMap<List<java.lang.String>,io.prometheus.metrics.core.metrics.Summary.DataPoint> data,private volatile io.prometheus.metrics.core.metrics.Summary.DataPoint noLabels
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(builder); this.callback = builder.callback; if (callback == null) { throw new IllegalArgumentException("callback cannot be null"); } } @Override public SummarySnapshot collect() {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties properties) { return new Builder(properties); } public static class Builder extends CallbackMetric.Builder<SummaryWithCallback.Builder, SummaryWithCallback> { private Consumer<Callback> callback; public Builder callback(Consumer<Callback> callback) { this.callback = callback; return self(); } private Builder(PrometheusProperties properties) { super(Collections.singletonList("quantile"), properties); } @Override public SummaryWithCallback build() { return new SummaryWithCallback(this); } @Override protected Builder self() { return this; } } }
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)); }); return new SummarySnapshot(getMetadata(), dataPoints);
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.newSingleThreadScheduledExecutor(new DaemonThreadFactory()); public static ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return executor.schedule(command, delay, unit); } /** * For unit test. Wait until the executor Thread is running. */ public static void awaitInitialization() throws InterruptedException {<FILL_FUNCTION_BODY>
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(PrometheusProperties.get(), PrometheusRegistry.defaultRegistry); } public PrometheusScrapeHandler(PrometheusRegistry registry) { this(PrometheusProperties.get(), registry); } public PrometheusScrapeHandler(PrometheusProperties config) { this(config, PrometheusRegistry.defaultRegistry); } public PrometheusScrapeHandler(PrometheusProperties config, PrometheusRegistry registry) { this.expositionFormats = ExpositionFormats.init(config.getExporterProperties()); this.registry = registry; this.nameFilter = makeNameFilter(config.getExporterFilterProperties()); } public void handleRequest(PrometheusHttpExchange exchange) throws IOException { try { PrometheusHttpRequest request = exchange.getRequest(); PrometheusHttpResponse response = exchange.getResponse(); MetricSnapshots snapshots = scrape(request); if (writeDebugResponse(snapshots, exchange)) { return; } ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream(lastResponseSize.get() + 1024); String acceptHeader = request.getHeader("Accept"); ExpositionFormatWriter writer = expositionFormats.findWriter(acceptHeader); writer.write(responseBuffer, snapshots); lastResponseSize.set(responseBuffer.size()); response.setHeader("Content-Type", writer.getContentType()); if (shouldUseCompression(request)) { response.setHeader("Content-Encoding", "gzip"); try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(response.sendHeadersAndGetBody(200, 0))) { responseBuffer.writeTo(gzipOutputStream); } } else { int contentLength = responseBuffer.size(); if (contentLength > 0) { response.setHeader("Content-Length", String.valueOf(contentLength)); } if (request.getMethod().equals("HEAD")) { // The HTTPServer implementation will throw an Exception if we close the output stream // without sending a response body, so let's not close the output stream in case of a HEAD response. response.sendHeadersAndGetBody(200, -1); } else { try (OutputStream outputStream = response.sendHeadersAndGetBody(200, contentLength)) { responseBuffer.writeTo(outputStream); } } } } catch (IOException e) { exchange.handleException(e); } catch (RuntimeException e) { exchange.handleException(e); } finally { exchange.close(); } } private Predicate<String> makeNameFilter(ExporterFilterProperties props) { if (props.getAllowedMetricNames() == null && props.getExcludedMetricNames() == null && props.getAllowedMetricNamePrefixes() == null && props.getExcludedMetricNamePrefixes() == null) { return null; } else { return MetricNameFilter.builder() .nameMustBeEqualTo(props.getAllowedMetricNames()) .nameMustNotBeEqualTo(props.getExcludedMetricNames()) .nameMustStartWith(props.getAllowedMetricNamePrefixes()) .nameMustNotStartWith(props.getExcludedMetricNamePrefixes()) .build(); } } private MetricSnapshots scrape(PrometheusHttpRequest request) { Predicate<String> filter = makeNameFilter(request.getParameterValues("name[]")); if (filter != null) { return registry.scrape(filter, request); } else { return registry.scrape(request); } } private Predicate<String> makeNameFilter(String[] includedNames) { Predicate<String> result = null; if (includedNames != null && includedNames.length > 0) { result = MetricNameFilter.builder().nameMustBeEqualTo(includedNames).build(); } if (result != null && nameFilter != null) { result = result.and(nameFilter); } else if (nameFilter != null) { result = nameFilter; } return result; } private boolean writeDebugResponse(MetricSnapshots snapshots, PrometheusHttpExchange exchange) throws IOException { String debugParam = exchange.getRequest().getParameter("debug"); PrometheusHttpResponse response = exchange.getResponse(); if (debugParam == null) { return false; } else { response.setHeader("Content-Type", "text/plain; charset=utf-8"); boolean supportedFormat = Arrays.asList("openmetrics", "text", "prometheus-protobuf").contains(debugParam); int responseStatus = supportedFormat ? 200 : 500; OutputStream body = response.sendHeadersAndGetBody(responseStatus, 0); switch (debugParam) { case "openmetrics": expositionFormats.getOpenMetricsTextFormatWriter().write(body, snapshots); break; case "text": expositionFormats.getPrometheusTextFormatWriter().write(body, snapshots); break; case "prometheus-protobuf": String debugString = expositionFormats.getPrometheusProtobufWriter().toDebugString(snapshots); body.write(debugString.getBytes(StandardCharsets.UTF_8)); break; default: body.write(("debug=" + debugParam + ": Unsupported query parameter. Valid values are 'openmetrics', 'text', and 'prometheus-protobuf'.").getBytes(StandardCharsets.UTF_8)); break; } return true; } } private boolean shouldUseCompression(PrometheusHttpRequest request) {<FILL_FUNCTION_BODY>} }
Enumeration<String> encodingHeaders = request.getHeaders("Accept-Encoding"); if (encodingHeaders == null) { return false; } while (encodingHeaders.hasMoreElements()) { String encodingHeader = encodingHeaders.nextElement(); String[] encodings = encodingHeader.split(","); for (String encoding : encodings) { if (encoding.trim().equalsIgnoreCase("gzip")) { return true; } } } return false;
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" + "<h1>Prometheus Java Client</h1>\n" + "<h2>Metrics Path</h2>\n" + "The metrics path is <a href=\"/metrics\">/metrics</a>.\n" + "<h2>Name Filter</h2>\n" + "If you want to scrape only specific metrics, use the <tt>name[]</tt> parameter like this:\n" + "<ul>\n" + "<li><a href=\"/metrics?name[]=my_metric\">/metrics?name[]=my_metric</a></li>\n" + "</ul>\n" + "You can also use multiple <tt>name[]</tt> parameters to query multiple metrics:\n" + "<ul>\n" + "<li><a href=\"/metrics?name[]=my_metric_a&name=my_metrics_b\">/metrics?name[]=my_metric_a&amp;name=[]=my_metric_b</a></li>\n" + "</ul>\n" + "The <tt>name[]</tt> parameter can be used by the Prometheus server for scraping. Add the following snippet to your scrape job configuration in <tt>prometheus.yaml</tt>:\n" + "<pre>\n" + "params:\n" + " name[]:\n" + " - my_metric_a\n" + " - my_metric_b\n" + "</pre>\n" + "<h2>Debug Parameter</h2>\n" + "The Prometheus Java metrics library supports multiple exposition formats.\n" + "The Prometheus server sends the <tt>Accept</tt> header to indicate which format it accepts.\n" + "By default, the Prometheus server accepts OpenMetrics text format, unless the Prometheus server is started with feature flag <tt>--enable-feature=native-histograms</tt>,\n" + "in which case the default is Prometheus protobuf.\n" + "The Prometheus Java metrics library supports a <tt>debug</tt> query parameter for viewing the different formats in a Web browser:\n" + "<ul>\n" + "<li><a href=\"/metrics?debug=openmetrics\">/metrics?debug=openmetrics</a>: View OpenMetrics text format.</li>\n" + "<li><a href=\"/metrics?debug=text\">/metrics?debug=text</a>: View Prometheus text format (this is the default when accessing the <a href=\"/metrics\">/metrics</a> endpoint with a Web browser).</li>\n" + "<li><a href=\"/metrics?debug=prometheus-protobuf\">/metrics?debug=prometheus-protobuf</a>: View a text representation of the Prometheus protobuf format.</li>\n" + "</ul>\n" + "Note that the <tt>debug</tt> parameter is only for viewing different formats in a Web browser, it should not be used by the Prometheus server for scraping. The Prometheus server uses the <tt>Accept</tt> header for indicating which format it accepts.\n" + "</body>\n" + "</html>\n"; this.responseBytes = responseString.getBytes(StandardCharsets.UTF_8); this.contentType = "text/html; charset=utf-8"; } @Override public void handle(HttpExchange exchange) throws IOException {<FILL_FUNCTION_BODY>} }
try { exchange.getResponseHeaders().set("Content-Type", contentType); exchange.getResponseHeaders().set("Content-Length", Integer.toString(responseBytes.length)); exchange.sendResponseHeaders(200, responseBytes.length); exchange.getResponseBody().write(responseBytes); } finally { exchange.close(); }
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 = "text/plain; charset=utf-8"; } @Override public void handle(HttpExchange exchange) throws IOException {<FILL_FUNCTION_BODY>} }
try { exchange.getResponseHeaders().set("Content-Type", contentType); exchange.getResponseHeaders().set("Content-Length", Integer.toString(responseBytes.length)); exchange.sendResponseHeaders(200, responseBytes.length); exchange.getResponseBody().write(responseBytes); } finally { exchange.close(); }
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 IOException { if (responseSent) { throw new IOException("Cannot send multiple HTTP responses for a single HTTP exchange."); } responseSent = true; httpExchange.sendResponseHeaders(statusCode, contentLength); return httpExchange.getResponseBody(); } } @Override public HttpRequest getRequest() { return request; } @Override public HttpResponse getResponse() { return response; } @Override public void handleException(IOException e) throws IOException { sendErrorResponseWithStackTrace(e); } @Override public void handleException(RuntimeException e) { sendErrorResponseWithStackTrace(e); } private void sendErrorResponseWithStackTrace(Exception requestHandlerException) {<FILL_FUNCTION_BODY>
if (!responseSent) { responseSent = true; try { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.write("An Exception occurred while scraping metrics: "); requestHandlerException.printStackTrace(new PrintWriter(printWriter)); byte[] stackTrace = stringWriter.toString().getBytes(StandardCharsets.UTF_8); httpExchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); httpExchange.sendResponseHeaders(500, stackTrace.length); httpExchange.getResponseBody().write(stackTrace); } catch (Exception errorWriterException) { // We want to avoid logging so that we don't mess with application logs when the HTTPServer is used in a Java agent. // However, if we can't even send an error response to the client there's nothing we can do but logging a message. Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "The Prometheus metrics HTTPServer caught an Exception during scrape and failed to send an error response to the client.", errorWriterException); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Original Exception that caused the Prometheus scrape error:", requestHandlerException); } } else { // If the exception occurs after response headers have been sent, it's too late to respond with HTTP 500. Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "The Prometheus metrics HTTPServer caught an Exception while trying to send the metrics response.", requestHandlerException); }
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; private final boolean daemon; NamedDaemonThreadFactory(ThreadFactory delegate, boolean daemon) { this.delegate = delegate; this.daemon = daemon; } @Override public Thread newThread(Runnable r) {<FILL_FUNCTION_BODY>} static ThreadFactory defaultThreadFactory(boolean daemon) { return new NamedDaemonThreadFactory(Executors.defaultThreadFactory(), daemon); } }
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 = "instrumentationScope.version"; public static InstrumentationScopeInfo loadInstrumentationScopeInfo() {<FILL_FUNCTION_BODY>} }
try { Properties properties = new Properties(); properties.load(PrometheusInstrumentationScope.class.getClassLoader().getResourceAsStream(instrumentationScopePropertiesFile)); String instrumentationScopeName = properties.getProperty(instrumentationScopeNameKey); if (instrumentationScopeName == null) { throw new IllegalStateException("Prometheus metrics library initialization error: " + instrumentationScopeNameKey + " not found in " + instrumentationScopePropertiesFile + " in classpath."); } String instrumentationScopeVersion = properties.getProperty(instrumentationScopeVersionKey); if (instrumentationScopeVersion == null) { throw new IllegalStateException("Prometheus metrics library initialization error: " + instrumentationScopeVersionKey + " not found in " + instrumentationScopePropertiesFile + " in classpath."); } return InstrumentationScopeInfo.builder(instrumentationScopeName) .setVersion(instrumentationScopeVersion) .build(); } catch (Exception e) { throw new IllegalStateException("Prometheus metrics library initialization error: Failed to read " + instrumentationScopePropertiesFile + " from classpath.", e); }
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 instrumentationScopeInfo, Resource resource) { this.registry = registry; this.instrumentationScopeInfo = instrumentationScopeInfo; this.resource = resource; } @Override public Collection<MetricData> collectAllMetrics() {<FILL_FUNCTION_BODY>} private Resource resourceFromTargetInfo(MetricSnapshots snapshots) { ResourceBuilder result = Resource.builder(); for (MetricSnapshot snapshot : snapshots) { if (snapshot.getMetadata().getName().equals("target") && snapshot instanceof InfoSnapshot) { InfoSnapshot targetInfo = (InfoSnapshot) snapshot; if (targetInfo.getDataPoints().size() > 0) { InfoSnapshot.InfoDataPointSnapshot data = targetInfo.getDataPoints().get(0); Labels labels = data.getLabels(); for (int i = 0; i < labels.size(); i++) { result.put(labels.getName(i), labels.getValue(i)); } } } } return result.build(); } private InstrumentationScopeInfo instrumentationScopeFromOTelScopeInfo(MetricSnapshots snapshots) { for (MetricSnapshot snapshot : snapshots) { if (snapshot.getMetadata().getPrometheusName().equals("otel_scope") && snapshot instanceof InfoSnapshot) { InfoSnapshot scopeInfo = (InfoSnapshot) snapshot; if (scopeInfo.getDataPoints().size() > 0) { Labels labels = scopeInfo.getDataPoints().get(0).getLabels(); String name = null; String version = null; AttributesBuilder attributesBuilder = Attributes.builder(); for (int i = 0; i < labels.size(); i++) { if (labels.getPrometheusName(i).equals("otel_scope_name")) { name = labels.getValue(i); } else if (labels.getPrometheusName(i).equals("otel_scope_version")) { version = labels.getValue(i); } else { attributesBuilder.put(labels.getName(i), labels.getValue(i)); } } if (name != null) { return InstrumentationScopeInfo.builder(name) .setVersion(version) .setAttributes(attributesBuilder.build()) .build(); } } } } return null; } private void addUnlessNull(List<MetricData> result, MetricData data) { if (data != null) { result.add(data); } } }
// 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)); InstrumentationScopeInfo scopeFromInfo = instrumentationScopeFromOTelScopeInfo(snapshots); List<MetricData> result = new ArrayList<>(snapshots.size()); MetricDataFactory factory = new MetricDataFactory(resourceWithTargetInfo, scopeFromInfo != null ? scopeFromInfo : instrumentationScopeInfo, System.currentTimeMillis()); for (MetricSnapshot snapshot : snapshots) { if (snapshot instanceof CounterSnapshot) { addUnlessNull(result, factory.create((CounterSnapshot) snapshot)); } else if (snapshot instanceof GaugeSnapshot) { addUnlessNull(result, factory.create((GaugeSnapshot) snapshot)); } else if (snapshot instanceof HistogramSnapshot) { if (!((HistogramSnapshot) snapshot).isGaugeHistogram()) { addUnlessNull(result, factory.create((HistogramSnapshot) snapshot)); } } else if (snapshot instanceof SummarySnapshot) { addUnlessNull(result, factory.create((SummarySnapshot) snapshot)); } else if (snapshot instanceof InfoSnapshot) { String name = snapshot.getMetadata().getPrometheusName(); if (!name.equals("target") && !name.equals("otel_scope")) { addUnlessNull(result, factory.create((InfoSnapshot) snapshot)); } } else if (snapshot instanceof StateSetSnapshot) { addUnlessNull(result, factory.create((StateSetSnapshot) snapshot)); } else if (snapshot instanceof UnknownSnapshot) { addUnlessNull(result, factory.create((UnknownSnapshot) snapshot)); } } return result;
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, String serviceNamespace, String serviceInstanceId, String serviceVersion, Map<String, String> configuredResourceAttributes) {<FILL_FUNCTION_BODY>} private static void putIfAbsent(Map<String, String> result, String key, String value) { if (value != null) { result.putIfAbsent(key, value); } } }
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", serviceInstanceId); putIfAbsent(result, "service.version", serviceVersion); for (Map.Entry<String, String> attribute : configuredResourceAttributes.entrySet()) { putIfAbsent(result, attribute.getKey(), attribute.getValue()); } ResourceAttributesFromJarFileName.addIfAbsent(result); ResourceAttributesDefaults.addIfAbsent(result); return result;
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 null; } // Take the path until the first space. If the path doesn't exist extend it up to the next // space. Repeat until a path that exists is found or input runs out. int next = 0; while (true) { int nextSpace = programArguments.indexOf(' ', next); if (nextSpace == -1) { return pathIfExists(programArguments); } Path path = pathIfExists(programArguments.substring(0, nextSpace)); next = nextSpace + 1; if (path != null) { return path; } } } private static Path pathIfExists(String programArguments) { Path candidate; try { candidate = Paths.get(programArguments); } catch (InvalidPathException e) { return null; } return Files.isRegularFile(candidate) ? candidate : null; } private static String getServiceName(Path jarPath) { String jarName = jarPath.getFileName().toString(); int dotIndex = jarName.lastIndexOf("."); return dotIndex == -1 ? jarName : jarName.substring(0, dotIndex); } }
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) and adds them to {@code result}. * <p> * The way this works is as follows: If the OTel Java agent is attached, it modifies the * {@code GlobalOpenTelemetry.get()} method to return an agent-specific object. * From that agent-specific object we can get the resource attributes via reflection. * <p> * So we load the {@code GlobalOpenTelemetry} class (in a separate class loader from the JAR files * that are bundled with this module), call {@code .get()}, and inspect the returned object. * <p> * After that we discard the class loader so that all OTel specific classes are unloaded. * No runtime dependency on any OTel version remains. */ public static void addIfAbsent(Map<String, String> result, String instrumentationScopeName) { try { Path tmpDir = createTempDirectory(instrumentationScopeName + "-"); try { URL[] otelJars = copyOtelJarsToTempDir(tmpDir, instrumentationScopeName); try (URLClassLoader classLoader = new URLClassLoader(otelJars)) { Class<?> globalOpenTelemetryClass = classLoader.loadClass("io.opentelemetry.api.GlobalOpenTelemetry"); Object globalOpenTelemetry = globalOpenTelemetryClass.getMethod("get").invoke(null); if (globalOpenTelemetry.getClass().getSimpleName().contains("ApplicationOpenTelemetry")) { // GlobalOpenTelemetry is injected by the OTel Java aqent Object applicationMeterProvider = callMethod("getMeterProvider", globalOpenTelemetry); Object agentMeterProvider = getField("agentMeterProvider", applicationMeterProvider); Object sdkMeterProvider = getField("delegate", agentMeterProvider); Object sharedState = getField("sharedState", sdkMeterProvider); Object resource = callMethod("getResource", sharedState); Object attributes = callMethod("getAttributes", resource); Map<?, ?> attributeMap = (Map<?, ?>) callMethod("asMap", attributes); for (Map.Entry<?, ?> entry : attributeMap.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { result.putIfAbsent(entry.getKey().toString(), entry.getValue().toString()); } } } } } finally { deleteTempDir(tmpDir.toFile()); } } catch (Exception ignored) { } } private static Object getField(String name, Object obj) throws Exception { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); return field.get(obj); } private static Object callMethod(String name, Object obj) throws Exception { Method method = obj.getClass().getMethod(name); method.setAccessible(true); return method.invoke(obj); } private static URL[] copyOtelJarsToTempDir(Path tmpDir, String instrumentationScopeName) throws Exception {<FILL_FUNCTION_BODY>} private static void deleteTempDir(File tmpDir) { // We don't have subdirectories, so this simple implementation should work. for (File file : tmpDir.listFiles()) { file.delete(); } tmpDir.delete(); } }
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("Error initializing " + instrumentationScopeName + ": lib/" + OTEL_JARS[i] + " not found in classpath."); } File outputFile = tmpDir.resolve(OTEL_JARS[i]).toFile(); Files.copy(inputStream, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); inputStream.close(); result[i] = outputFile.toURI().toURL(); } return result;
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; } void addCount(long count) { bucketCounts.add(count); } @Override public int getScale() { return scale; } @Override public int getOffset() { return offset; } @Override public List<Long> getBucketCounts() { return bucketCounts; } @Override public long getTotalCount() {<FILL_FUNCTION_BODY>} }
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.resource = resource; this.instrumentationScopeInfo = instrumentationScopeInfo; this.currentTimeMillis = currentTimeMillis; } public MetricData create(CounterSnapshot snapshot) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusCounter(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } public MetricData create(GaugeSnapshot snapshot) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusGauge(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } public MetricData create(HistogramSnapshot snapshot) {<FILL_FUNCTION_BODY>} public MetricData create(SummarySnapshot snapshot) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusSummary(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } public MetricData create(InfoSnapshot snapshot) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusInfo(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } public MetricData create(StateSetSnapshot snapshot) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusStateSet(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } public MetricData create(UnknownSnapshot snapshot) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusUnknown(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } }
if (!snapshot.getDataPoints().isEmpty()) { HistogramSnapshot.HistogramDataPointSnapshot firstDataPoint = snapshot.getDataPoints().get(0); if (firstDataPoint.hasNativeHistogramData()) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusNativeHistogram(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } else if (firstDataPoint.hasClassicHistogramData()) { return new PrometheusMetricData<>(snapshot.getMetadata(), new PrometheusClassicHistogram(snapshot, currentTimeMillis), instrumentationScopeInfo, resource); } } return null;
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.getDataPoints().stream() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Override public AggregationTemporality getAggregationTemporality() { return AggregationTemporality.CUMULATIVE; } @Override public Collection<HistogramPointData> getPoints() { return points; } private HistogramPointData toOtelDataPoint(HistogramSnapshot.HistogramDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} private long calculateCount(ClassicHistogramBuckets buckets) { int result = 0; for (int i=0; i<buckets.size(); i++ ) { result += buckets.getCount(i); } return result; } private List<Double> makeBoundaries(ClassicHistogramBuckets buckets) { List<Double> result = new ArrayList<>(buckets.size()); for (int i=0; i<buckets.size(); i++) { result.add(buckets.getUpperBound(i)); } return result; } private List<Long> makeCounts(ClassicHistogramBuckets buckets) { List<Long> result = new ArrayList<>(buckets.size()); for (int i=0; i<buckets.size(); i++) { result.add(buckets.getCount(i)); } return result; } }
if (!dataPoint.hasClassicHistogramData()) { return null; } else { return new HistogramPointDataImpl( dataPoint.hasSum() ? dataPoint.getSum() : Double.NaN, dataPoint.hasCount() ? dataPoint.getCount() : calculateCount(dataPoint.getClassicBuckets()), Double.NaN, Double.NaN, makeBoundaries(dataPoint.getClassicBuckets()), makeCounts(dataPoint.getClassicBuckets()), getStartEpochNanos(dataPoint), getEpochNanos(dataPoint, currentTimeMillis), labelsToAttributes(dataPoint.getLabels()), convertExemplars(dataPoint.getExemplars()) ); }
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().stream() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .collect(Collectors.toList()); } @Override public boolean isMonotonic() { return true; } @Override public AggregationTemporality getAggregationTemporality() { return AggregationTemporality.CUMULATIVE; } @Override public Collection<DoublePointData> getPoints() { return points; } private DoublePointData toOtelDataPoint(CounterSnapshot.CounterDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} }
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 (labels.isEmpty()) { return Attributes.empty(); } else { AttributesBuilder builder = Attributes.builder(); for (int i=0; i<labels.size(); i++) { builder.put(labels.getName(i), labels.getValue(i)); } return builder.build(); } } protected List<DoubleExemplarData> convertExemplar(Exemplar exemplar) { if (exemplar == null) { return Collections.emptyList(); } return convertExemplars(Exemplars.of(exemplar)); } protected List<DoubleExemplarData> convertExemplars(Exemplars exemplars) { return StreamSupport.stream(exemplars.spliterator(), false) .map(this::toDoubleExemplarData) .collect(Collectors.toList()); } protected DoubleExemplarData toDoubleExemplarData(Exemplar exemplar) {<FILL_FUNCTION_BODY>} protected long getStartEpochNanos(DataPointSnapshot dataPoint) { return dataPoint.hasCreatedTimestamp() ? TimeUnit.MILLISECONDS.toNanos(dataPoint.getCreatedTimestampMillis()) : 0L; } protected long getEpochNanos(DataPointSnapshot dataPoint, long currentTimeMillis) { return dataPoint.hasScrapeTimestamp() ? TimeUnit.MILLISECONDS.toNanos(dataPoint.getScrapeTimestampMillis()) : TimeUnit.MILLISECONDS.toNanos(currentTimeMillis); } }
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_ID)) { traceId = label.getValue(); } else if (label.getName().equals(Exemplar.SPAN_ID)) { spanId = label.getValue(); } else { filteredAttributesBuilder.put(label.getName(), label.getValue()); } } Attributes filteredAttributes = filteredAttributesBuilder.build(); SpanContext spanContext = (traceId != null && spanId != null) ? SpanContext.create(traceId, spanId, TraceFlags.getSampled(), TraceState.getDefault()) : SpanContext.getInvalid(); return ImmutableDoubleExemplarData.create( filteredAttributes, TimeUnit.MILLISECONDS.toNanos(exemplar.getTimestampMillis()), spanContext, exemplar.getValue());
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().stream() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .collect(Collectors.toList()); } @Override public Collection<DoublePointData> getPoints() { return points; } private DoublePointData toOtelDataPoint(GaugeSnapshot.GaugeDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} }
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() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .collect(Collectors.toList()); } @Override public boolean isMonotonic() { return false; } @Override public AggregationTemporality getAggregationTemporality() { return AggregationTemporality.CUMULATIVE; } @Override public Collection<DoublePointData> getPoints() { return points; } private DoublePointData toOtelDataPoint(InfoSnapshot.InfoDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} }
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; PrometheusMetricData(MetricMetadata metricMetadata, T data, InstrumentationScopeInfo instrumentationScopeInfo, Resource resource) { this.instrumentationScopeInfo = instrumentationScopeInfo; this.resource = resource; this.name = getNameWithoutUnit(metricMetadata); this.description = metricMetadata.getHelp(); this.unit = convertUnit(metricMetadata.getUnit()); this.data = data; } // In OpenTelemetry the unit should not be part of the metric name. private String getNameWithoutUnit(MetricMetadata metricMetadata) { String name = metricMetadata.getName(); if (metricMetadata.getUnit() != null) { String unit = metricMetadata.getUnit().toString(); if (name.endsWith(unit)) { name = name.substring(0, name.length() - unit.length()); } while (name.endsWith("_")) { name = name.substring(0, name.length()-1); } } return name; } // See https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/6cf4dec6cb42d87d8840e9f67d4acf66d4eb8fda/pkg/translator/prometheus/normalize_name.go#L19 private String convertUnit(Unit unit) {<FILL_FUNCTION_BODY>} @Override public Resource getResource() { return resource; } @Override public InstrumentationScopeInfo getInstrumentationScopeInfo() { return instrumentationScopeInfo; } @Override public String getName() { return name; } @Override public String getDescription() { return description; } @Override public String getUnit() { return unit; } @Override public MetricDataType getType() { return data.getType(); } @Override public T getData() { return data; } @Override public SumData<DoublePointData> getDoubleSumData() { if (data instanceof PrometheusCounter) { return (PrometheusCounter) data; } if (data instanceof PrometheusStateSet) { return (PrometheusStateSet) data; } if (data instanceof PrometheusInfo) { return (PrometheusInfo) data; } return MetricData.super.getDoubleSumData(); } }
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"; case "microseconds": return "us"; case "nanoseconds": return "ns"; // Bytes case "bytes": return "By"; case "kibibytes": return "KiBy"; case "mebibytes": return "MiBy"; case "gibibytes": return "GiBy"; case "tibibytes": return "TiBy"; case "kilobytes": return "KBy"; case "megabytes": return "MBy"; case "gigabytes": return "GBy"; case "terabytes": return "TBy"; // SI case "meters": return "m"; case "volts": return "V"; case "amperes": return "A"; case "joules": return "J"; case "watts": return "W"; case "grams": return "g"; // Misc case "celsius": return "Cel"; case "hertz": return "Hz"; case "percent": return "%"; // default default: return unit.toString(); }
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_HISTOGRAM); this.points = snapshot.getDataPoints().stream() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Override public AggregationTemporality getAggregationTemporality() { return AggregationTemporality.CUMULATIVE; } @Override public Collection<ExponentialHistogramPointData> getPoints() { return points; } private ExponentialHistogramPointData toOtelDataPoint(HistogramSnapshot.HistogramDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} private ExponentialHistogramBuckets convertBuckets(int scale, NativeHistogramBuckets buckets) { if (buckets.size() == 0) { return new ExponentialHistogramBucketsImpl(scale, 0); } int offset = buckets.getBucketIndex(0); ExponentialHistogramBucketsImpl result = new ExponentialHistogramBucketsImpl(scale, offset-1); int currentBucket = 0; for (int i=offset; i<=buckets.getBucketIndex(buckets.size()-1); i++) { if (buckets.getBucketIndex(currentBucket) == i) { result.addCount(buckets.getCount(currentBucket)); currentBucket++; } else { result.addCount(0); } } return result; } private long calculateCount(HistogramSnapshot.HistogramDataPointSnapshot dataPoint) { long result = 0L; for (int i=0; i<dataPoint.getNativeBucketsForPositiveValues().size(); i++) { result += dataPoint.getNativeBucketsForPositiveValues().getCount(i); } for (int i=0; i<dataPoint.getNativeBucketsForNegativeValues().size(); i++) { result += dataPoint.getNativeBucketsForNegativeValues().getCount(i); } result += dataPoint.getNativeZeroCount(); return result; } }
if (!dataPoint.hasNativeHistogramData()) { return null; } return new ExponentialHistogramPointDataImpl( dataPoint.getNativeSchema(), dataPoint.hasSum() ? dataPoint.getSum() : Double.NaN, dataPoint.hasCount() ? dataPoint.getCount() : calculateCount(dataPoint), dataPoint.getNativeZeroCount(), Double.NaN, Double.NaN, convertBuckets(dataPoint.getNativeSchema(), dataPoint.getNativeBucketsForPositiveValues()), convertBuckets(dataPoint.getNativeSchema(), dataPoint.getNativeBucketsForNegativeValues()), getStartEpochNanos(dataPoint), getEpochNanos(dataPoint, currentTimeMillis), labelsToAttributes(dataPoint.getLabels()), convertExemplars(dataPoint.getExemplars()) );
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<>(); for (StateSetSnapshot.StateSetDataPointSnapshot dataPoint : snapshot.getDataPoints()) { for (int i=0; i<dataPoint.size(); i++) { this.points.add(toOtelDataPoint(snapshot, dataPoint, i, currentTimeMillis)); } } } @Override public boolean isMonotonic() { return false; } @Override public AggregationTemporality getAggregationTemporality() { return AggregationTemporality.CUMULATIVE; } @Override public Collection<DoublePointData> getPoints() { return points; } private DoublePointData toOtelDataPoint(StateSetSnapshot snapshot, StateSetSnapshot.StateSetDataPointSnapshot dataPoint, int i, long currentTimeMillis) {<FILL_FUNCTION_BODY>} }
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.getName(i)))), Collections.emptyList() );
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() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .collect(Collectors.toList()); } @Override public Collection<SummaryPointData> getPoints() { return points; } private SummaryPointData toOtelDataPoint(SummarySnapshot.SummaryDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} }
SummaryPointDataImpl result = new SummaryPointDataImpl( dataPoint.hasSum() ? dataPoint.getSum() : Double.NaN, dataPoint.hasCount() ? dataPoint.getCount() : 0, getStartEpochNanos(dataPoint), getEpochNanos(dataPoint, currentTimeMillis), labelsToAttributes(dataPoint.getLabels()), convertExemplars(dataPoint.getExemplars()) ); for (Quantile quantile : dataPoint.getQuantiles()) { result.addValue(quantile.getQuantile(), quantile.getValue()); } return result;
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.getDataPoints().stream() .map(dataPoint -> toOtelDataPoint(dataPoint, currentTimeMillis)) .collect(Collectors.toList()); } @Override public Collection<DoublePointData> getPoints() { return points; } private DoublePointData toOtelDataPoint(UnknownSnapshot.UnknownDataPointSnapshot dataPoint, long currentTimeMillis) {<FILL_FUNCTION_BODY>} }
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(); } @Override public Enumeration<String> getHeaders(String name) { return request.getHeaders(name); } @Override public String getMethod() { return request.getMethod(); } @Override public String getRequestPath() {<FILL_FUNCTION_BODY>} }
StringBuilder uri = new StringBuilder(); String contextPath = request.getContextPath(); if (contextPath.startsWith("/")) { uri.append(contextPath); } String servletPath = request.getServletPath(); if (servletPath.startsWith("/")) { uri.append(servletPath); } String pathInfo = request.getPathInfo(); if (pathInfo != null) { uri.append(pathInfo); } return uri.toString();
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(HttpServletResponse response) { this.response = response; } @Override public void setHeader(String name, String value) { response.setHeader(name, value); } @Override public OutputStream sendHeadersAndGetBody(int statusCode, int contentLength) throws IOException {<FILL_FUNCTION_BODY>} }
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 prometheusProtobufWriter, PrometheusTextFormatWriter prometheusTextFormatWriter, OpenMetricsTextFormatWriter openMetricsTextFormatWriter) { this.prometheusProtobufWriter = prometheusProtobufWriter; this.prometheusTextFormatWriter = prometheusTextFormatWriter; this.openMetricsTextFormatWriter = openMetricsTextFormatWriter; } public static ExpositionFormats init() { return init(PrometheusProperties.get().getExporterProperties()); } public static ExpositionFormats init(ExporterProperties properties) {<FILL_FUNCTION_BODY>} public ExpositionFormatWriter findWriter(String acceptHeader) { if (prometheusProtobufWriter.accepts(acceptHeader)) { return prometheusProtobufWriter; } if (openMetricsTextFormatWriter.accepts(acceptHeader)) { return openMetricsTextFormatWriter; } return prometheusTextFormatWriter; } public PrometheusProtobufWriter getPrometheusProtobufWriter() { return prometheusProtobufWriter; } public PrometheusTextFormatWriter getPrometheusTextFormatWriter() { return prometheusTextFormatWriter; } public OpenMetricsTextFormatWriter getOpenMetricsTextFormatWriter() { return openMetricsTextFormatWriter; } }
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("+Inf"); } else if (d == Double.NEGATIVE_INFINITY) { writer.write("-Inf"); } else { writer.write(Double.toString(d)); // FloatingDecimal.getBinaryToASCIIConverter(d).appendTo(writer); } } static void writeTimestamp(OutputStreamWriter writer, long timestampMs) throws IOException { writer.write(Long.toString(timestampMs / 1000L)); writer.write("."); long ms = timestampMs % 1000; if (ms < 100) { writer.write("0"); } if (ms < 10) { writer.write("0"); } writer.write(Long.toString(ms)); } static void writeEscapedLabelValue(Writer writer, String s) throws IOException { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\\': writer.append("\\\\"); break; case '\"': writer.append("\\\""); break; case '\n': writer.append("\\n"); break; default: writer.append(c); } } } static void writeLabels(OutputStreamWriter writer, Labels labels, String additionalLabelName, double additionalLabelValue) throws IOException {<FILL_FUNCTION_BODY>} }
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)); writer.write("\""); } if (additionalLabelName != null) { if (!labels.isEmpty()) { writer.write(","); } writer.write(additionalLabelName); writer.write("=\""); writeDouble(writer, additionalLabelValue); writer.write("\""); } writer.write('}');
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) { this.registry = registry; return this; } public Builder metricFilter(MetricFilter metricFilter) { this.metricFilter = metricFilter; return this; } public Builder customLabelMapper(CustomLabelMapper labelMapper) { this.labelMapper = labelMapper; return this; } DropwizardExports build() {<FILL_FUNCTION_BODY>} public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) { DropwizardExports dropwizardExports = build(); registry.register(dropwizardExports); } }
if (registry == null) { throw new IllegalArgumentException("MetricRegistry must be set"); } if (labelMapper == null) { return new DropwizardExports(registry, metricFilter); } else { return new DropwizardExports(registry, metricFilter, labelMapper); }
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 configs!"); } this.compiledMapperConfigs = new ArrayList<CompiledMapperConfig>(mapperConfigs.size()); for (MapperConfig config : mapperConfigs) { this.compiledMapperConfigs.add(new CompiledMapperConfig(config)); } } public String getName(final String dropwizardName){ if (dropwizardName == null) { throw new IllegalArgumentException("Dropwizard metric name cannot be null"); } CompiledMapperConfig matchingConfig = null; for (CompiledMapperConfig config : this.compiledMapperConfigs) { if (config.pattern.matches(dropwizardName)) { matchingConfig = config; break; } } if (matchingConfig != null) { final Map<String, String> params = matchingConfig.pattern.extractParameters(dropwizardName); final NameAndLabels nameAndLabels = getNameAndLabels(matchingConfig.mapperConfig, params); return nameAndLabels.name; } return dropwizardName; } public Labels getLabels(final String dropwizardName, final List<String> additionalLabelNames, final List<String> additionalLabelValues){ if (dropwizardName == null) { throw new IllegalArgumentException("Dropwizard metric name cannot be null"); } CompiledMapperConfig matchingConfig = null; for (CompiledMapperConfig config : this.compiledMapperConfigs) { if (config.pattern.matches(dropwizardName)) { matchingConfig = config; break; } } if (matchingConfig != null) { final Map<String, String> params = matchingConfig.pattern.extractParameters(dropwizardName); final NameAndLabels nameAndLabels = getNameAndLabels(matchingConfig.mapperConfig, params); nameAndLabels.labelNames.addAll(additionalLabelNames); nameAndLabels.labelValues.addAll(additionalLabelValues); return Labels.of(nameAndLabels.labelNames, nameAndLabels.labelValues); } return Labels.of(additionalLabelNames, additionalLabelValues); } protected NameAndLabels getNameAndLabels(final MapperConfig config, final Map<String, String> parameters) {<FILL_FUNCTION_BODY>} private String formatTemplate(final String template, final Map<String, String> params) { String result = template; for (Map.Entry<String, String> entry : params.entrySet()) { result = result.replace(entry.getKey(), entry.getValue()); } return result; } static class CompiledMapperConfig { final MapperConfig mapperConfig; final GraphiteNamePattern pattern; CompiledMapperConfig(final MapperConfig mapperConfig) { this.mapperConfig = mapperConfig; this.pattern = new GraphiteNamePattern(mapperConfig.getMatch()); } } static class NameAndLabels { final String name; final List<String> labelNames; final List<String> labelValues; NameAndLabels(final String name, final List<String> labelNames, final List<String> labelValues) { this.name = name; this.labelNames = labelNames; this.labelValues = labelValues; } } }
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.getLabels().entrySet()) { labels.add(entry.getKey()); labelValues.add(formatTemplate(entry.getValue(), parameters)); } return new NameAndLabels(metricName, labels, labelValues);
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 to be used. */ GraphiteNamePattern(final String pattern) throws IllegalArgumentException { if (!VALIDATION_PATTERN.matcher(pattern).matches()) { throw new IllegalArgumentException(String.format("Provided pattern [%s] does not matches [%s]", pattern, METRIC_GLOB_REGEX)); } initializePattern(pattern); } /** * Matches the metric name against the pattern. * * @param metricName The metric name to be tested. * @return {@code true} if the name is matched, {@code false} otherwise. */ boolean matches(final String metricName) { return metricName != null && pattern.matcher(metricName).matches(); } /** * Extracts parameters from the given metric name based on the pattern. * The resulting map has keys named as '${n}' where n is the 0 based position in the pattern. * E.g.: * pattern: org.test.controller.*.status.* * extractParameters("org.test.controller.gather.status.400") -> * {${0} -> "gather", ${1} -> "400"} * * @param metricName The metric name to extract parameters from. * @return A parameter map where keys are named '${n}' where n is 0 based parameter position in the pattern. */ Map<String, String> extractParameters(final String metricName) {<FILL_FUNCTION_BODY>} /** * Turns the GLOB pattern into a REGEX. * * @param pattern The pattern to use */ private void initializePattern(final String pattern) { final String[] split = pattern.split(Pattern.quote("*"), -1); final StringBuilder escapedPattern = new StringBuilder(Pattern.quote(split[0])); for (int i = 1; i < split.length; i++) { String quoted = Pattern.quote(split[i]); escapedPattern.append("([^.]*)").append(quoted); } final String regex = "^" + escapedPattern.toString() + "$"; this.patternStr = regex; this.pattern = Pattern.compile(regex); } String getPatternString() { return this.patternStr; } }
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)); } } return params;
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 + "\\.)+(\\*|" + METRIC_PART_REGEX + ")$"; // Labels validation. private static final String LABEL_REGEX = "^[a-zA-Z_][a-zA-Z0-9_]+$"; private static final Pattern MATCH_EXPRESSION_PATTERN = Pattern.compile(METRIC_GLOB_REGEX); private static final Pattern LABEL_PATTERN = Pattern.compile(LABEL_REGEX); /** * Regex used to match incoming metric name. * Uses a simplified glob syntax where only '*' are allowed. * E.g: * org.company.controller.*.status.* * Will be used to match * org.company.controller.controller1.status.200 * and * org.company.controller.controller2.status.400 */ private String match; /** * New metric name. Can contain placeholders to be replaced with actual values from the incoming metric name. * Placeholders are in the ${n} format where n is the zero based index of the group to extract from the original metric name. * E.g.: * match: test.dispatcher.*.*.* * name: dispatcher_events_total_${1} * <p> * A metric "test.dispatcher.old.test.yay" will be converted in a new metric with name "dispatcher_events_total_test" */ private String name; /** * Labels to be extracted from the metric name. * They should contain placeholders to be replaced with actual values from the incoming metric name. * Placeholders are in the ${n} format where n is the zero based index of the group to extract from the original metric name. * E.g.: * match: test.dispatcher.*.* * name: dispatcher_events_total_${0} * labels: * label1: ${1}_t * <p> * A metric "test.dispatcher.sp1.yay" will be converted in a new metric with name "dispatcher_events_total_sp1" with label {label1: yay_t} * <p> * Label names have to match the regex ^[a-zA-Z_][a-zA-Z0-9_]+$ */ private Map<String, String> labels = new HashMap<String, String>(); public MapperConfig() { // empty constructor } // for tests MapperConfig(final String match) { validateMatch(match); this.match = match; } public MapperConfig(final String match, final String name, final Map<String, String> labels) { this.name = name; validateMatch(match); this.match = match; validateLabels(labels); this.labels = labels; } @Override public String toString() { return String.format("MapperConfig{match=%s, name=%s, labels=%s}", match, name, labels); } public String getMatch() { return match; } public void setMatch(final String match) { validateMatch(match); this.match = match; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Map<String, String> getLabels() { return labels; } public void setLabels(final Map<String, String> labels) { validateLabels(labels); this.labels = labels; } private void validateMatch(final String match) { if (!MATCH_EXPRESSION_PATTERN.matcher(match).matches()) { throw new IllegalArgumentException(String.format("Match expression [%s] does not match required pattern %s", match, MATCH_EXPRESSION_PATTERN)); } } private void validateLabels(final Map<String, String> labels) { if (labels != null) { for (final String key : labels.keySet()) { if (!LABEL_PATTERN.matcher(key).matches()) { throw new IllegalArgumentException(String.format("Label [%s] does not match required pattern %s", match, LABEL_PATTERN)); } } } } @Override public boolean equals(final Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = match != null ? match.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (labels != null ? labels.hashCode() : 0); return result; } }
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) return false; return labels != null ? labels.equals(that.labels) : that.labels == 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"; private final PrometheusProperties config; private final List<BufferPoolMXBean> bufferPoolBeans; private JvmBufferPoolMetrics(List<BufferPoolMXBean> bufferPoolBeans, PrometheusProperties config) { this.config = config; this.bufferPoolBeans = bufferPoolBeans; } private void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder { private final PrometheusProperties config; private List<BufferPoolMXBean> bufferPoolBeans; private Builder(PrometheusProperties config) { this.config = config; } /** * Package private. For testing only. */ Builder bufferPoolBeans(List<BufferPoolMXBean> bufferPoolBeans) { this.bufferPoolBeans = bufferPoolBeans; return this; } public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) { List<BufferPoolMXBean> bufferPoolBeans = this.bufferPoolBeans; if (bufferPoolBeans == null) { bufferPoolBeans = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class); } new JvmBufferPoolMetrics(bufferPoolBeans, config).register(registry); } } }
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 : bufferPoolBeans) { callback.call(pool.getMemoryUsed(), pool.getName()); } }) .register(registry); GaugeWithCallback.builder(config) .name(JVM_BUFFER_POOL_CAPACITY_BYTES) .help("Bytes capacity of a given JVM buffer pool.") .unit(Unit.BYTES) .labelNames("pool") .callback(callback -> { for (BufferPoolMXBean pool : bufferPoolBeans) { callback.call(pool.getTotalCapacity(), pool.getName()); } }) .register(registry); GaugeWithCallback.builder(config) .name(JVM_BUFFER_POOL_USED_BUFFERS) .help("Used buffers of a given JVM buffer pool.") .labelNames("pool") .callback(callback -> { for (BufferPoolMXBean pool : bufferPoolBeans) { callback.call(pool.getCount(), pool.getName()); } }) .register(registry);
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 final PrometheusProperties config; private final ClassLoadingMXBean classLoadingBean; private JvmClassLoadingMetrics(ClassLoadingMXBean classLoadingBean, PrometheusProperties config) { this.classLoadingBean = classLoadingBean; this.config = config; } private void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder { private final PrometheusProperties config; private ClassLoadingMXBean classLoadingBean; private Builder(PrometheusProperties config) { this.config = config; } /** * Package private. For testing only. */ Builder classLoadingBean(ClassLoadingMXBean classLoadingBean) { this.classLoadingBean = classLoadingBean; return this; } public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) { ClassLoadingMXBean classLoadingBean = this.classLoadingBean != null ? this.classLoadingBean : ManagementFactory.getClassLoadingMXBean(); new JvmClassLoadingMetrics(classLoadingBean, config).register(registry); } } }
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); CounterWithCallback.builder(config) .name(JVM_CLASSES_LOADED_TOTAL) .help("The total number of classes that have been loaded since the JVM has started execution") .callback(callback -> callback.call(classLoadingBean.getTotalLoadedClassCount())) .register(registry); CounterWithCallback.builder(config) .name(JVM_CLASSES_UNLOADED_TOTAL) .help("The total number of classes that have been unloaded since the JVM has started execution") .callback(callback -> callback.call(classLoadingBean.getUnloadedClassCount())) .register(registry);
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, PrometheusProperties config) { this.compilationBean = compilationBean; this.config = config; } private void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>} public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder { private final PrometheusProperties config; private CompilationMXBean compilationBean; private Builder(PrometheusProperties config) { this.config = config; } /** * Package private. For testing only. */ Builder compilationBean(CompilationMXBean compilationBean) { this.compilationBean = compilationBean; return this; } public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) { CompilationMXBean compilationBean = this.compilationBean != null ? this.compilationBean : ManagementFactory.getCompilationMXBean(); new JvmCompilationMetrics(compilationBean, config).register(registry); } } }
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") .unit(Unit.SECONDS) .callback(callback -> callback.call(millisToSeconds(compilationBean.getTotalCompilationTime()))) .register(registry);
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. */ Builder garbageCollectorBeans(List<GarbageCollectorMXBean> garbageCollectorBeans) { this.garbageCollectorBeans = garbageCollectorBeans; return this; } public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>} }
List<GarbageCollectorMXBean> garbageCollectorBeans = this.garbageCollectorBeans; if (garbageCollectorBeans == null) { garbageCollectorBeans = ManagementFactory.getGarbageCollectorMXBeans(); } new JvmGarbageCollectorMetrics(garbageCollectorBeans, config).register(registry);
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<GarbageCollectorMXBean> garbageCollectorBeans, PrometheusProperties config) { this.garbageCollectorBeans = garbageCollectorBeans; this.config = config; } private void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>} static class AllocationCountingNotificationListener implements NotificationListener { private final Map<String, Long> lastMemoryUsage = new HashMap<String, Long>(); private final Counter counter; AllocationCountingNotificationListener(Counter counter) { this.counter = counter; } @Override public synchronized void handleNotification(Notification notification, Object handback) { GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData()); GcInfo gcInfo = info.getGcInfo(); Map<String, MemoryUsage> memoryUsageBeforeGc = gcInfo.getMemoryUsageBeforeGc(); Map<String, MemoryUsage> memoryUsageAfterGc = gcInfo.getMemoryUsageAfterGc(); for (Map.Entry<String, MemoryUsage> entry : memoryUsageBeforeGc.entrySet()) { String memoryPool = entry.getKey(); long before = entry.getValue().getUsed(); long after = memoryUsageAfterGc.get(memoryPool).getUsed(); handleMemoryPool(memoryPool, before, after); } } // Visible for testing void handleMemoryPool(String memoryPool, long before, long after) { /* * Calculate increase in the memory pool by comparing memory used * after last GC, before this GC, and after this GC. * See ascii illustration below. * Make sure to count only increases and ignore decreases. * (Typically a pool will only increase between GCs or during GCs, not both. * E.g. eden pools between GCs. Survivor and old generation pools during GCs.) * * |<-- diff1 -->|<-- diff2 -->| * Timeline: |-- last GC --| |---- GC -----| * ___^__ ___^____ ___^___ * Mem. usage vars: / last \ / before \ / after \ */ // Get last memory usage after GC and remember memory used after for next time long last = getAndSet(lastMemoryUsage, memoryPool, after); // Difference since last GC long diff1 = before - last; // Difference during this GC long diff2 = after - before; // Make sure to only count increases if (diff1 < 0) { diff1 = 0; } if (diff2 < 0) { diff2 = 0; } long increase = diff1 + diff2; if (increase > 0) { counter.labelValues(memoryPool).inc(increase); } } private static long getAndSet(Map<String, Long> map, String key, long value) { Long last = map.put(key, value); return last == null ? 0 : last; } } public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder { private final PrometheusProperties config; private List<GarbageCollectorMXBean> garbageCollectorBeans; private Builder(PrometheusProperties config) { this.config = config; } /** * Package private. For testing only. */ Builder withGarbageCollectorBeans(List<GarbageCollectorMXBean> garbageCollectorBeans) { this.garbageCollectorBeans = garbageCollectorBeans; return this; } public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) { List<GarbageCollectorMXBean> garbageCollectorBeans = this.garbageCollectorBeans; if (garbageCollectorBeans == null) { garbageCollectorBeans = ManagementFactory.getGarbageCollectorMXBeans(); } new JvmMemoryPoolAllocationMetrics(garbageCollectorBeans, config).register(registry); } } }
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); AllocationCountingNotificationListener listener = new AllocationCountingNotificationListener(allocatedCounter); for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorBeans) { if (garbageCollectorMXBean instanceof NotificationEmitter) { ((NotificationEmitter) garbageCollectorMXBean).addNotificationListener(listener, null, null); } }
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: * Only the first call will register the metrics, all subsequent calls will be ignored. */ public void register() { if (!registeredWithTheDefaultRegistry.getAndSet(true)) { register(PrometheusRegistry.defaultRegistry); } } /** * Register all JVM metrics with the {@code registry}. * <p> * You must make sure to call this only once per {@code registry}, otherwise it will * throw an Exception because you are trying to register duplicate metrics. */ public void register(PrometheusRegistry registry) {<FILL_FUNCTION_BODY>} }
JvmThreadsMetrics.builder(config).register(registry); JvmBufferPoolMetrics.builder(config).register(registry); JvmClassLoadingMetrics.builder(config).register(registry); JvmCompilationMetrics.builder(config).register(registry); JvmGarbageCollectorMetrics.builder(config).register(registry); JvmMemoryPoolAllocationMetrics.builder(config).register(registry); JvmMemoryMetrics.builder(config).register(registry); JvmNativeMemoryMetrics.builder(config).register(registry); JvmRuntimeInfoMetric.builder(config).register(registry); ProcessMetrics.builder(config).register(registry);
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-Za-z]+).*reserved=(\\d+), committed=(\\d+)"); /** * Package private. For testing only. */ static final AtomicBoolean isEnabled = new AtomicBoolean(true); private final PrometheusProperties config; private final PlatformMBeanServerAdapter adapter; private JvmNativeMemoryMetrics(PrometheusProperties config, PlatformMBeanServerAdapter adapter) { this.config = config; this.adapter = adapter; } private void register(PrometheusRegistry registry) { // first call will check if enabled and set the flag vmNativeMemorySummaryInBytesOrEmpty(); if (isEnabled.get()) { GaugeWithCallback.builder(config) .name(JVM_NATIVE_MEMORY_RESERVED_BYTES) .help("Reserved bytes of a given JVM. Reserved memory represents the total amount of memory the JVM can potentially use.") .unit(Unit.BYTES) .labelNames("pool") .callback(makeCallback(true)) .register(registry); GaugeWithCallback.builder(config) .name(JVM_NATIVE_MEMORY_COMMITTED_BYTES) .help("Committed bytes of a given JVM. Committed memory represents the amount of memory the JVM is using right now.") .unit(Unit.BYTES) .labelNames("pool") .callback(makeCallback(false)) .register(registry); } } private Consumer<GaugeWithCallback.Callback> makeCallback(Boolean reserved) {<FILL_FUNCTION_BODY>} private String vmNativeMemorySummaryInBytesOrEmpty() { if (!isEnabled.get()) { return ""; } try { // requires -XX:NativeMemoryTracking=summary String summary = adapter.vmNativeMemorySummaryInBytes(); if (summary.isEmpty() || summary.trim().contains("Native memory tracking is not enabled")) { isEnabled.set(false); return ""; } else { return summary; } } catch (Exception ex) { // ignore errors isEnabled.set(false); return ""; } } interface PlatformMBeanServerAdapter { String vmNativeMemorySummaryInBytes(); } static class DefaultPlatformMBeanServerAdapter implements PlatformMBeanServerAdapter { @Override public String vmNativeMemorySummaryInBytes() { try { return (String) ManagementFactory.getPlatformMBeanServer().invoke( new ObjectName("com.sun.management:type=DiagnosticCommand"), "vmNativeMemory", new Object[]{new String[]{"summary", "scale=B"}}, new String[]{"[Ljava.lang.String;"}); } catch (ReflectionException | MalformedObjectNameException | InstanceNotFoundException | MBeanException e) { throw new IllegalStateException("Native memory tracking is not enabled", e); } } } public static Builder builder() { return new Builder(PrometheusProperties.get()); } public static Builder builder(PrometheusProperties config) { return new Builder(config); } public static class Builder { private final PrometheusProperties config; private final PlatformMBeanServerAdapter adapter; private Builder(PrometheusProperties config) { this(config, new DefaultPlatformMBeanServerAdapter()); } /** * Package private. For testing only. */ Builder(PrometheusProperties config, PlatformMBeanServerAdapter adapter) { this.config = config; this.adapter = adapter; } public void register() { register(PrometheusRegistry.defaultRegistry); } public void register(PrometheusRegistry registry) { new JvmNativeMemoryMetrics(config, adapter).register(registry); } } }
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 = Long.parseLong(matcher.group(2)); } else { value = Long.parseLong(matcher.group(3)); } callback.call(value, category); } } };
1,096
141
1,237
<no_super_class>