src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
MessicVersion implements Comparable<MessicVersion> { @Override public boolean equals( Object obj ) { if ( obj instanceof MessicVersion ) { return ( this.compareTo( (MessicVersion) obj ) == 0 ? true : false ); } else { return false; } } MessicVersion( String version ); @Override String toString(); @Override boolean equa...
@Test public void testConstruction() { MessicVersion mv = new MessicVersion( "1.0.3" ); Assert.assertTrue( mv.version == 1 ); Assert.assertTrue( mv.revision == 0 ); Assert.assertTrue( mv.patch == 3 ); Assert.assertTrue( mv.semantic.equals( "" ) ); Assert.assertTrue( mv.semanticPatch == 0 ); mv = new MessicVersion( "5.3...
Util { public static String replaceIllegalFilenameCharactersNew( String filename, char replacementCharacter ) { String result = filename.replaceAll( ILLEGAL_FILENAME_OPENENCAPSULATE_CHARS_NEW, "[" ); result = result.replaceAll( ILLEGAL_FILENAME_CLOSEENCAPSULATE_CHARS_NEW, "]" ); result = result.replaceAll( ILLEGAL_FILE...
@Test public void testReplaceIllegalFilenameCharacters() { String fileName = "04-From?::/let's see.mp3"; String result = Util.replaceIllegalFilenameCharactersNew( fileName, '_' ); Assert.assertTrue( result.equals( "04-From_-let's see.mp3" ) ); fileName = "04-Fr^om /et's see\\.m*3"; result = Util.replaceIllegalFilenameC...
Util { public static File getRollFileNumber( File file ) { File fresult = file; if ( !file.isDirectory() && file.exists() ) { file.getName(); String name = FilenameUtils.getBaseName( file.getName() ); String ext = FilenameUtils.getExtension( file.getName() ); String parent = file.getParent(); int indexOf_ = name.lastIn...
@Test public void testGetRollFileNumber() throws IOException { File f = new File( "./testFile0" ); File fresult = Util.getRollFileNumber( f ); Assert.assertTrue( fresult.getName().equals( "testFile0" ) ); f = tfolder.newFile( "testFile1.txt" ); fresult = Util.getRollFileNumber( f ); Assert.assertTrue( fresult.getName()...
MessicDataSource extends BasicDataSource { @Override public synchronized void setUrl( String url ) { String musicFolder = System.getProperty( "messic.musicfolder" ); if ( musicFolder == null || musicFolder.length() <= 0 ) { musicFolder = System.getProperty( "user.home" ) + File.separatorChar + "messic-data"; } File f =...
@Test public void testSetUrl() { MessicDataSource mds = new MessicDataSource(); String urlTest = "jdbc:h2:MESSIC_PATH/db;DB_CLOSE_DELAY=-1"; mds.setUrl( urlTest ); Assert.assertTrue( !mds.getUrl().equals( urlTest ) ); }
Activator implements BundleActivator { public void start( BundleContext bundleContext ) { try { String sversion = LibShout.get().getVersion(); if ( !sversion.equals( "2.3.1" ) ) { logger.warn( "icecast2 version " + sversion ); } logger.info( "Radio - Icecast2 Started" ); Hashtable<String, String> props = new Hashtable<...
@Test public void testStart() { }
RingStream implements Iterable<E>, Iterator<E> { public Stream<E> streamLimited(int count) { return streamUnlimited().limit(count); } @SafeVarargs RingStream(E... elements); @Override boolean hasNext(); @Override Iterator<E> iterator(); @Override E next(); int size(); Stream<E> streamAll(); Stream<E> streamLimited(int...
@Test public void testLimitedStream() { RingStream<String> s = new RingStream<>("foo", "bar", "baz"); assertTrue(s.streamLimited(2).noneMatch("baz"::equals)); assertTrue(s.streamLimited(2).noneMatch("bar"::equals)); assertTrue(s.streamLimited(2).noneMatch("foo"::equals)); }
MsgDeliveryTagMapping { public void basicAck(long deliveryTag, boolean multiple) throws IOException { Map<Long, MsgResponse> acks = multiple ? deliveryTags.headMap(deliveryTag, true).descendingMap() : deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(acks, MsgResult.ACK, multiple, false); acks.clear();...
@Test void basicAck() { when(envelope.getDeliveryTag()).thenReturn(40L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(40L, e.getDeliveryTag()); assertDoesNotThrow(() -> map.basicAck(e.getDeliveryTag(), false)); assertDoesNotThrow(() -> verify(channel).basicAck(40L, false)); }
MsgDeliveryTagMapping { void basicNack(long deliveryTag, boolean multiple, boolean requeue) throws IOException { Map<Long, MsgResponse> nacks = multiple ? deliveryTags.headMap(deliveryTag, true).descendingMap() : deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(nacks, MsgResult.NACK, multiple, requeue...
@Test void basicNack() { when(envelope.getDeliveryTag()).thenReturn(41L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(41L, e.getDeliveryTag()); assertDoesNotThrow(() -> map.basicNack(e.getDeliveryTag(), false, false)); assertDoesNotThrow(() -> verify(channel).basicNack(41L, false,...
MsgDeliveryTagMapping { void basicReject(long deliveryTag, boolean requeue) throws IOException { Map<Long, MsgResponse> rejections = deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(rejections, MsgResult.REJECT, false, requeue); rejections.clear(); } MsgDeliveryTagMapping(); void basicAck(long deliver...
@Test void basicReject() { when(envelope.getDeliveryTag()).thenReturn(43L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(43L, e.getDeliveryTag()); assertDoesNotThrow(() -> map.basicReject(e.getDeliveryTag(), false)); assertDoesNotThrow(() -> verify(channel).basicReject(43L, false))...
MsgDeliveryTagMapping { Consumer createConsumerDecorator(Consumer delegate, Channel channel) { return new MappingConsumer(this, delegate, channel); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag, boolean multiple); }
@Test void createConsumerDecorator() { Consumer c = map.createConsumerDecorator(callback, channel); }
MsgDeliveryTagMapping { Envelope envelopeWithPseudoDeliveryTag(Channel channel, Envelope envelope) { long tag = mapDelivery(channel, envelope.getDeliveryTag()); return new Envelope( tag, envelope.isRedeliver(), envelope.getExchange(), envelope.getRoutingKey()); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag,...
@Test void mapEnvelope() { when(envelope.getDeliveryTag()).thenReturn(42L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(42L, e.getDeliveryTag()); }
Utility { static byte[] encode(BigInteger n) { byte[] encodedN; if (n.signum() == 0) { encodedN = new byte[0]; } else { byte[] nAsByteArray = n.toByteArray(); int firstNonZeroIndex = 0; while ((nAsByteArray[firstNonZeroIndex] == 0) && (firstNonZeroIndex < nAsByteArray.length)) { firstNonZeroIndex++; } encodedN = new by...
@Test public void testEncode() { assertArrayEquals(TestUtility.cba(0xCA, 0xFE, 0xBA, 0xBE), Utility.encode(BigInteger.valueOf(0xCAFEBABE))); assertArrayEquals(TestUtility.cba(0xCA, 0xFE, 0xBA), Utility.encode(BigInteger.valueOf(0x00CAFEBA))); assertArrayEquals(TestUtility.cba(0xCA, 0xFE), Utility.encode(BigInteger.valu...
FE1 { public BigInteger decrypt(final BigInteger modulus, final BigInteger ciphertext, final byte[] key, final byte[] tweak) throws FPEException { if (modulus == null) { throw new IllegalArgumentException("modulus must not be null."); } if (ciphertext == null) { throw new IllegalArgumentException("ciphertext must not b...
@Test(expected = IllegalArgumentException.class) public void testDecryptTooBigInputBy1() throws FPEException { new FE1().decrypt(BigInteger.valueOf(10000), BigInteger.valueOf(10000), TEST_KEY, TEST_IV); } @Test(expected = IllegalArgumentException.class) public void testDecryptTooBigInputBy2() throws FPEException { new ...
FE1 { public BigInteger encrypt(final BigInteger modulus, final BigInteger plaintext, final byte[] key, final byte[] tweak) throws FPEException { if (modulus == null) { throw new IllegalArgumentException("modulus must not be null."); } if (plaintext == null) { throw new IllegalArgumentException("plaintext must not be n...
@Test(expected = IllegalArgumentException.class) public void testEncryptNullModulus() throws FPEException { new FE1().encrypt(null, BigInteger.valueOf(10001), TEST_KEY, TEST_IV); } @Test(expected = IllegalArgumentException.class) public void testEncryptNullValue() throws FPEException { new FE1().encrypt(BigInteger.valu...
NumberTheory { static int countLowZeroBits(BigInteger n) { int lowZero = 0; if (n.signum() > 0) { byte[] bytes = n.toByteArray(); for (int i = bytes.length - 1; i >= 0; i--) { byte x = bytes[i]; if (x != 0) { lowZero += countTrailingZeros(x); break; } else { lowZero += 8; } } } return lowZero; } private NumberTheory()...
@Test public void testCountLowZeroBits() { assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b0))); assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(-1))); assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(-1000))); assertEquals(8, NumberTheory.countLowZeroBits(BigInteger....
NumberTheory { static int countTrailingZeros(byte n) { for (int i = 0; i != 8; ++i) { if (((n >> i) & 0x01) > 0) { return i; } } return 8; } private NumberTheory(); }
@Test public void testCountTrailingZeros() { assertEquals(8, NumberTheory.countTrailingZeros((byte) 0b0)); assertEquals(0, NumberTheory.countTrailingZeros((byte) 0b1)); assertEquals(1, NumberTheory.countTrailingZeros((byte) 0b11111110)); assertEquals(6, NumberTheory.countTrailingZeros((byte) 0b11000000)); assertEquals(...
NumberTheory { static BigInteger[] factor(BigInteger number) throws FPEException { BigInteger n = number; BigInteger a = BigInteger.valueOf(1); BigInteger b = BigInteger.valueOf(1); int nLowZero = countLowZeroBits(n); a = a.shiftLeft(nLowZero / 2); b = b.shiftLeft(nLowZero - (nLowZero / 2)); n = n.shiftRight(nLowZero);...
@Test public void testFactor() throws FPEException { assertArrayEquals(this.cfp(3, 3), NumberTheory.factor(BigInteger.valueOf(9))); assertArrayEquals(this.cfp(6, 2), NumberTheory.factor(BigInteger.valueOf(12))); assertArrayEquals(this.cfp(6, 2), NumberTheory.factor(BigInteger.valueOf(12))); assertArrayEquals(this.cfp(1...
Utility { public static byte[] reverse(byte[] source) { int len = source.length; byte[] destination = new byte[len]; for (int i = 0; i < len; i++) { destination[len - i - 1] = source[i]; } return destination; } private Utility(); static byte[] reverse(byte[] source); static byte[] toLEBytes(int i); }
@Test public void testReverse() { assertArrayEquals(new byte[0], Utility.reverse(new byte[0])); assertArrayEquals(TestUtility.cba(0xCA, 0xFE, 0xBA, 0xBE), Utility.reverse(TestUtility.cba(0xBE, 0xBA, 0xFE, 0xCA))); assertArrayEquals(TestUtility.cba(0xCA), Utility.reverse(TestUtility.cba(0xCA))); }
RoutersService { public void put(final RouterMeta routerMeta) { final JsonEventToLogger event = new JsonEventToLogger(this.getClass()); String logCorrelation = routerMeta.correlation; event.put("correlation", logCorrelation); try { String key = MessageFormat.format(FORMAT_KEY_ROUTERS, routerMeta.envId, routerMeta.group...
@Test @Rollback(false) public void shouldClearChangesWithNewestVersion() { RouterMeta routerMeta = new RouterMeta(); routerMeta.groupId = "group-local"; routerMeta.localIP = "127.0.0.1"; routerMeta.version = "2"; routerMeta.envId = "1"; routerMeta.zoneId = null; String versionOldest = "1"; Environment env; Target targe...
HealthMeterRegistry extends SimpleMeterRegistry { public static Builder builder(HealthConfig config) { return new Builder(config); } protected HealthMeterRegistry(HealthConfig config, Collection<ServiceLevelObjective> serviceLevelObjectives, Collection<MeterFilter> serviceLevelObjecti...
@Test void onlyMetricsThatAreServiceLevelIndicatorsAreRegistered() { HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) .clock(new MockClock()) .serviceLevelObjectives( ServiceLevelObjective .build("counter.throughput") .count(search -> search.name("my.counter")) .isGreaterThan(1) ) .build...
PrometheusMeterRegistry extends MeterRegistry { public String scrape() { Writer writer = new StringWriter(); try { scrape(writer); } catch (IOException e) { throw new RuntimeException(e); } return writer.toString(); } PrometheusMeterRegistry(PrometheusConfig config); PrometheusMeterRegistry(PrometheusConfig config, Co...
@Issue("#61") @Test void timersRecordMax() { Timer timer = registry.timer("my.timer"); timer.record(10, TimeUnit.MILLISECONDS); timer.record(1, TimeUnit.SECONDS); assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(1); assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000); assertThat(registry.scrape()).contains("m...
PrometheusNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { String conventionName = NamingConvention.snakeCase.name(name, type, baseUnit); switch (type) { case COUNTER: case DISTRIBUTION_SUMMARY: case GAUGE: if (baseUnit != null && !co...
@Test void formatName() { assertThat(convention.name("123abc/{:id}水", Meter.Type.GAUGE)).startsWith("m_123abc__:id__"); } @Test void unitsAreAppendedToTimers() { assertThat(convention.name("timer", Meter.Type.TIMER)).isEqualTo("timer_seconds"); assertThat(convention.name("timer", Meter.Type.LONG_TASK_TIMER)).isEqualTo(...
PrometheusNamingConvention implements NamingConvention { @Override public String tagKey(String key) { String conventionKey = NamingConvention.snakeCase.tagKey(key); String sanitized = tagKeyChars.matcher(conventionKey).replaceAll("_"); if (!Character.isLetter(sanitized.charAt(0))) { sanitized = "m_" + sanitized; } retu...
@Test void formatTagKey() { assertThat(convention.tagKey("123abc/{:id}水")).startsWith("m_123abc___id__"); }
NewRelicMeterRegistry extends StepMeterRegistry { @Override public Config config() { return thisConfig; } NewRelicMeterRegistry(NewRelicConfig config, Clock clock); NewRelicMeterRegistry(NewRelicConfig config, @Nullable NewRelicClientProvider clientProvider, Clock clock); NewRelicMeterRegistry(NewRelicConfig config,...
@Test void succeedsConfigInsightsAgentClientProviderAndCustomNamingConvention() { NamingConvention customNamingConvention = mock(NewRelicNamingConvention.class); NewRelicMeterRegistry registry = new NewRelicMeterRegistry(insightsAgentConfig, null, customNamingConvention, clock, new NamedThreadFactory("new-relic-test"))...
KairosMeterRegistry extends StepMeterRegistry { Stream<String> writeGauge(Gauge gauge) { double value = gauge.value(); if (Double.isFinite(value)) { return Stream.of(writeMetric(gauge.getId(), config().clock().wallTime(), value)); } return Stream.empty(); } @SuppressWarnings("deprecation") KairosMeterRegistry(KairosCo...
@Test void writeGauge() { meterRegistry.gauge("my.gauge", 1d); Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge)).hasSize(1); } @Test void writeGaugeShouldDropNanValue() { meterRegistry.gauge("my.gauge", Double.NaN); Gauge gauge = meterRegistry.find("my.gauge").gauge(); as...
KairosMeterRegistry extends StepMeterRegistry { Stream<String> writeTimeGauge(TimeGauge timeGauge) { double value = timeGauge.value(getBaseTimeUnit()); if (Double.isFinite(value)) { return Stream.of(writeMetric(timeGauge.getId(), config().clock().wallTime(), value)); } return Stream.empty(); } @SuppressWarnings("deprec...
@Test void writeTimeGauge() { AtomicReference<Double> obj = new AtomicReference<>(1d); meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge(); assertThat(meterRegistry.writeTimeGauge(timeGauge)).hasS...
NewRelicMeterRegistry extends StepMeterRegistry { public static Builder builder(NewRelicConfig config) { return new Builder(config); } NewRelicMeterRegistry(NewRelicConfig config, Clock clock); NewRelicMeterRegistry(NewRelicConfig config, @Nullable NewRelicClientProvider clientProvider, Clock clock); NewRelicMeterRe...
@SuppressWarnings("deprecation") @Test void canCustomizeHttpSenderViaBuilder_deprecated() { HttpSender httpSender = mock(HttpSender.class); NewRelicClientProvider clientProvider = NewRelicMeterRegistry.builder(insightsApiConfig).httpClient(httpSender).build().clientProvider; assertThat(clientProvider).isInstanceOf(NewR...
KairosMeterRegistry extends StepMeterRegistry { Stream<String> writeFunctionCounter(FunctionCounter counter) { double count = counter.count(); if (Double.isFinite(count)) { return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), count)); } return Stream.empty(); } @SuppressWarnings("deprecation") Ka...
@Test void writeFunctionCounter() { FunctionCounter counter = FunctionCounter.builder("myCounter", 1d, Number::doubleValue).register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).hasSize(1); }
KairosNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return format(delegate.name(name, type, baseUnit)); } KairosNamingConvention(); KairosNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type t...
@Test void defaultToSnakeCase() { assertThat(convention.name("gauge.size", Meter.Type.GAUGE)).isEqualTo("gauge_size"); }
SysdigStatsdLineBuilder extends FlavorStatsdLineBuilder { @Override String line(String amount, @Nullable Statistic stat, String type) { updateIfNamingConventionChanged(); return name + tagsByStatistic(stat) + ":" + amount + "|" + type; } SysdigStatsdLineBuilder(Meter.Id id, MeterRegistry.Config config); }
@Test void changingNamingConvention() { Counter c = registry.counter("my.counter", "my.tag", "value"); SysdigStatsdLineBuilder lb = new SysdigStatsdLineBuilder(c.getId(), registry.config()); registry.config().namingConvention(NamingConvention.dot); assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo("my.counter#st...
BufferingFlux { public static Flux<String> create(final Flux<String> source, final String delimiter, final int maxByteArraySize, final long maxMillisecondsBetweenEmits) { return Flux.defer(() -> { final int delimiterSize = delimiter.getBytes().length; final AtomicInteger byteSize = new AtomicInteger(0); final AtomicLon...
@Test void bufferSingleStrings() { Flux<String> source = Flux.just( "twelve bytes", "fourteen bytes", "twelve bytes", "fourteen bytes" ).delayElements(Duration.ofMillis(50)); Flux<String> buffered = BufferingFlux.create(source, "\n", 14, 200); StepVerifier.create(buffered) .expectNext("twelve bytes\n") .expectNext("fou...
EtsyStatsdLineBuilder extends FlavorStatsdLineBuilder { @Override String line(String amount, @Nullable Statistic stat, String type) { updateIfNamingConventionChanged(); return nameByStatistic(stat) + ":" + amount + "|" + type; } EtsyStatsdLineBuilder(Meter.Id id, MeterRegistry.Config config, HierarchicalNameMapper name...
@Test void changingNamingConvention() { Counter c = registry.counter("my.counter", "my.tag", "value"); EtsyStatsdLineBuilder lb = new EtsyStatsdLineBuilder(c.getId(), registry.config(), HierarchicalNameMapper.DEFAULT); registry.config().namingConvention(NamingConvention.dot); assertThat(lb.line("1", Statistic.COUNT, "c...
DatadogStatsdLineBuilder extends FlavorStatsdLineBuilder { @Override String line(String amount, @Nullable Statistic stat, String type) { updateIfNamingConventionChanged(); return name + amount + "|" + type + tagsByStatistic(stat); } DatadogStatsdLineBuilder(Meter.Id id, MeterRegistry.Config config); }
@Test void changingNamingConvention() { Counter c = registry.counter("my.counter", "my.tag", "value"); DatadogStatsdLineBuilder lb = new DatadogStatsdLineBuilder(c.getId(), registry.config()); registry.config().namingConvention(NamingConvention.dot); assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo("my.counter:...
TelegrafStatsdLineBuilder extends FlavorStatsdLineBuilder { @Override String line(String amount, @Nullable Statistic stat, String type) { updateIfNamingConventionChanged(); return name + tagsByStatistic(stat) + ":" + amount + "|" + type; } TelegrafStatsdLineBuilder(Meter.Id id, MeterRegistry.Config config); }
@Test void changingNamingConvention() { Counter c = registry.counter("my.counter", "my.tag", "value"); TelegrafStatsdLineBuilder lb = new TelegrafStatsdLineBuilder(c.getId(), registry.config()); registry.config().namingConvention(NamingConvention.dot); assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo("my.counte...
StatsdMeterRegistry extends MeterRegistry { public static Builder builder(StatsdConfig config) { return new Builder(config); } StatsdMeterRegistry(StatsdConfig config, Clock clock); StatsdMeterRegistry(StatsdConfig config, HierarchicalNameMapper nameMapper, Clock clock); private StatsdMeterRegistry(StatsdConfig confi...
@Test void customNamingConvention() { final Processor<String, String> lines = lineProcessor(); registry = StatsdMeterRegistry.builder(configWithFlavor(StatsdFlavor.ETSY)) .nameMapper((id, convention) -> id.getName().toUpperCase()) .clock(clock) .lineSink(toSink(lines)) .build(); StepVerifier.create(lines) .then(() -> r...
NewRelicNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return StringEscapeUtils.escapeJson(toValidNewRelicString(delegate.name(name, type, baseUnit))); } NewRelicNamingConvention(); NewRelicNamingConvention(NamingConvention delegat...
@Test void name() { String validString = newRelicNamingConvention.name(VALID_NAME, Type.COUNTER); assertThat(validString).isEqualTo(VALID_NAME); } @Test void nameShouldStripInvalidCharacters() { String validString = newRelicNamingConvention.name(INVALID_NAME, Type.COUNTER); assertThat(validString).isEqualTo("invalid_na...
StatsdMeterRegistry extends MeterRegistry { public void stop() { if (started.compareAndSet(true, false)) { if (statsdConnection.get() != null) { statsdConnection.get().dispose(); } if (meterPoller.get() != null) { meterPoller.get().dispose(); } } } StatsdMeterRegistry(StatsdConfig config, Clock clock); StatsdMeterRegi...
@Test void interactWithStoppedRegistry() { registry = new StatsdMeterRegistry(configWithFlavor(StatsdFlavor.ETSY), clock); registry.stop(); registry.counter("my.counter").increment(); }
StatsdGauge extends AbstractMeter implements Gauge, StatsdPollable { @Override public void poll() { double val = value(); if (Double.isFinite(val) && (alwaysPublish || lastValue.getAndSet(val) != val)) { sink.next(lineBuilder.gauge(val)); } } StatsdGauge(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, @Nul...
@Test void shouldAlwaysPublishValue() { AtomicInteger lines = new AtomicInteger(0); MeterRegistry registry = StatsdMeterRegistry.builder(StatsdConfig.DEFAULT) .lineSink(l -> lines.incrementAndGet()) .build(); StatsdGauge<?> alwaysPublishingGauge = (StatsdGauge<?>) Gauge .builder("test", value, AtomicInteger::get).regis...
InfluxNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return escape(delegate.name(name, type, baseUnit).replace("=", "_")); } InfluxNamingConvention(); InfluxNamingConvention(NamingConvention delegate); @Override String name(String ...
@Issue("#693") @Test void name() { assertThat(convention.name("foo.bar=, baz", Meter.Type.GAUGE)).isEqualTo("foo_bar_\\,\\ baz"); }
InfluxNamingConvention implements NamingConvention { @Override public String tagKey(String key) { if (key.equals("time")) { throw new IllegalArgumentException("'time' is an invalid tag key in InfluxDB"); } return escape(delegate.tagKey(key)); } InfluxNamingConvention(); InfluxNamingConvention(NamingConvention delegate...
@Test void tagKey() { assertThat(convention.tagKey("foo.bar=, baz")).isEqualTo("foo_bar\\=\\,\\ baz"); } @Test void timeCannotBeATagKey() { assertThat(catchThrowable(() -> convention.tagKey("time"))).isInstanceOf(IllegalArgumentException.class); }
InfluxNamingConvention implements NamingConvention { @Override public String tagValue(String value) { return escape(this.delegate.tagValue(value).replace('\n', ' ')); } InfluxNamingConvention(); InfluxNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type type, @Nullable String base...
@Test void tagValue() { assertThat(convention.tagValue("foo=, bar")).isEqualTo("foo\\=\\,\\ bar"); } @Test void timeCanBeATagValue() { assertThat(convention.tagValue("time")).isEqualTo("time"); } @Issue("#645") @Test void namingConventionIsNotAppliedToTagValues() { assertThat(convention.tagValue("org.example.service=")...
CreateDatabaseQueryBuilder { String build() { StringBuilder queryStringBuilder = new StringBuilder(String.format(QUERY_MANDATORY_TEMPLATE, databaseName)); if (hasAnyRetentionPolicy()) { String retentionPolicyClause = Stream.of(retentionPolicyClauses).filter(Objects::nonNull) .reduce(RETENTION_POLICY_INTRODUCTION, Strin...
@Test void noRetentionPolicy() { String query = createDatabaseQueryBuilder.build(); assertEquals("CREATE DATABASE \"dummy_database_0\"", query); }
InfluxMeterRegistry extends StepMeterRegistry { Stream<String> writeGauge(Meter.Id id, Double value) { if (Double.isFinite(value)) { return Stream.of(influxLineProtocol(id, "gauge", Stream.of(new Field("value", value)))); } return Stream.empty(); } @SuppressWarnings("deprecation") InfluxMeterRegistry(InfluxConfig conf...
@Test void writeGauge() { meterRegistry.gauge("my.gauge", 1d); Gauge gauge = meterRegistry.find("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge.getId(), 1d)).hasSize(1); } @Test void writeGaugeShouldDropNanValue() { meterRegistry.gauge("my.gauge", Double.NaN); Gauge gauge = meterRegistry.find("my.gauge")...
NewRelicNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return StringEscapeUtils.escapeJson(toValidNewRelicString(delegate.tagKey(key))); } NewRelicNamingConvention(); NewRelicNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type type, @N...
@Test void tagKey() { String validString = newRelicNamingConvention.tagKey(VALID_NAME); assertThat(validString).isEqualTo(VALID_NAME); } @Test void tagKeyShouldStripInvalidCharacters() { String validString = newRelicNamingConvention.tagKey(INVALID_NAME); assertThat(validString).isEqualTo("invalid_name"); }
InfluxMeterRegistry extends StepMeterRegistry { Stream<String> writeFunctionTimer(FunctionTimer timer) { double sum = timer.totalTime(getBaseTimeUnit()); if (Double.isFinite(sum)) { Stream.Builder<Field> builder = Stream.builder(); builder.add(new Field("sum", sum)); builder.add(new Field("count", timer.count())); doub...
@Test void nanMeanFunctionTimerShouldNotWriteMean() { FunctionTimer functionTimer = new FunctionTimer() { @Override public double count() { return 1; } @Override public double totalTime(TimeUnit unit) { return 1; } @Override public TimeUnit baseTimeUnit() { return TimeUnit.SECONDS; } @Override public Id getId() { retur...
GraphiteMeterRegistry extends DropwizardMeterRegistry { @Override public void close() { if (config.enabled()) { reporter.close(); } super.close(); } GraphiteMeterRegistry(GraphiteConfig config, Clock clock); GraphiteMeterRegistry(GraphiteConfig config, Clock clock, HierarchicalNameMapper nameMapper); GraphiteMeterReg...
@Test void metricPrefixes() throws InterruptedException { final CountDownLatch receiveLatch = new CountDownLatch(1); final GraphiteMeterRegistry registry = new GraphiteMeterRegistry(new GraphiteConfig() { @Override @Nullable public String get(String key) { return null; } @Override public boolean graphiteTagsEnabled() {...
GraphiteHierarchicalNameMapper implements HierarchicalNameMapper { @Override public String toHierarchicalName(Meter.Id id, NamingConvention convention) { StringBuilder hierarchicalName = new StringBuilder(); for (String tagKey : tagsAsPrefix) { String tagValue = id.getTag(tagKey); if (tagValue != null) { hierarchicalNa...
@Issue("#561") @Test void tagsAsPrefix() { assertThat(nameMapper.toHierarchicalName(id, NamingConvention.camelCase)) .isEqualTo("PROD.MYAPP.myName.otherTag.value"); } @Test void toHierarchicalNameShouldSanitizeTagValueFromTagsAsPrefix() { Meter.Id id = new SimpleMeterRegistry().counter("my.name", "app.name", "MY APP", ...
GraphiteHierarchicalNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return sanitizeName(this.delegate.name(normalize(name), type, baseUnit)); } GraphiteHierarchicalNamingConvention(); GraphiteHierarchicalNamingConvention(NamingConve...
@Test void name() { assertThat(convention.name("name([{id}])/1", Meter.Type.TIMER)).isEqualTo("name___id____1"); } @Test void dotNotationIsConvertedToCamelCase() { assertThat(convention.name("gauge.size", Meter.Type.GAUGE)).isEqualTo("gaugeSize"); } @Test void nameShouldPreserveDot() { GraphiteHierarchicalNamingConvent...
GraphiteHierarchicalNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return sanitizeTag(this.delegate.tagKey(normalize(key))); } GraphiteHierarchicalNamingConvention(); GraphiteHierarchicalNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.T...
@Test void tagKeyShouldSanitizeDot() { GraphiteHierarchicalNamingConvention convention = new GraphiteHierarchicalNamingConvention(NamingConvention.identity); assertThat(convention.tagKey("my.tag")).isEqualTo("my_tag"); } @Test void tagKeyShouldSanitizeSpace() { assertThat(convention.tagKey("tag 1")).isEqualTo("tag_1");...
GraphiteHierarchicalNamingConvention implements NamingConvention { @Override public String tagValue(String value) { return sanitizeTag(this.delegate.tagValue(normalize(value))); } GraphiteHierarchicalNamingConvention(); GraphiteHierarchicalNamingConvention(NamingConvention delegate); @Override String name(String name,...
@Test void tagValueShouldSanitizeDot() { assertThat(convention.tagValue("my.value")).isEqualTo("my_value"); }
NewRelicNamingConvention implements NamingConvention { @Override public String tagValue(String value) { return StringEscapeUtils.escapeJson(delegate.tagValue(value)); } NewRelicNamingConvention(); NewRelicNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type type, @Nullable String ...
@Test void tagValue() { String validString = newRelicNamingConvention.tagValue(VALID_NAME); assertThat(validString).isEqualTo(VALID_NAME); } @Test void tagValueShouldNotStripInvalidCharacters() { String validString = newRelicNamingConvention.tagValue(INVALID_NAME); assertThat(validString).isEqualTo(INVALID_NAME); }
GraphiteDimensionalNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return sanitizeName(this.delegate.name(normalize(name), type, baseUnit)); } GraphiteDimensionalNamingConvention(); GraphiteDimensionalNamingConvention(NamingConventi...
@Test void name() { assertThat(convention.name("name([{id}])/1", Meter.Type.TIMER)).isEqualTo("name___id____1"); } @Test void nameShouldPreserveDot() { assertThat(convention.name("my.counter", Meter.Type.COUNTER)).isEqualTo("my.counter"); } @Test void nameShouldSanitizeSpace() { assertThat(convention.name("counter 1", ...
GraphiteDimensionalNamingConvention implements NamingConvention { @Override public String tagKey(String key) { if (key.isEmpty()) { return UNSPECIFIED; } return sanitizeTagKey(this.delegate.tagKey(normalize(key))); } GraphiteDimensionalNamingConvention(); GraphiteDimensionalNamingConvention(NamingConvention delegate);...
@Test void tagKeyShouldPreserveDot() { assertThat(convention.tagKey("my.tag")).isEqualTo("my.tag"); } @Test void tagKeyShouldPreserveSpace() { assertThat(convention.tagKey("tag 1")).isEqualTo("tag 1"); } @Test void tagKeyShouldPreserveQuestionMark() { assertThat(convention.tagKey("tag?1")).isEqualTo("tag?1"); } @Test v...
GraphiteDimensionalNamingConvention implements NamingConvention { @Override public String tagValue(String value) { if (value.isEmpty()) { return UNSPECIFIED; } return sanitizeTagValue(this.delegate.tagValue(normalize(value))); } GraphiteDimensionalNamingConvention(); GraphiteDimensionalNamingConvention(NamingConventio...
@Test void tagValueShouldPreserveDot() { assertThat(convention.tagValue("my.tag")).isEqualTo("my.tag"); } @Test void tagValueShouldPreserveSpace() { assertThat(convention.tagValue("tag 1")).isEqualTo("tag 1"); } @Test void tagValueShouldPreserveQuestionMark() { assertThat(convention.tagValue("tag?1")).isEqualTo("tag?1"...
OpenTSDBMeterRegistry extends PushMeterRegistry { Stream<String> writeGauge(Gauge gauge) { double value = gauge.value(); if (Double.isFinite(value)) { return Stream.of(writeMetric(gauge.getId(), config().clock().wallTime(), value)); } return Stream.empty(); } @SuppressWarnings("deprecation") OpenTSDBMeterRegistry(Open...
@Test void writeGauge() { meterRegistry.gauge("my.gauge", 1d); Gauge gauge = meterRegistry.get("my.gauge").gauge(); assertThat(meterRegistry.writeGauge(gauge)).hasSize(1); } @Test void writeGaugeShouldDropNanValue() { meterRegistry.gauge("my.gauge", Double.NaN); Gauge gauge = meterRegistry.get("my.gauge").gauge(); asse...
CloudWatchMeterRegistry extends StepMeterRegistry { List<MetricDatum> metricData() { Batch batch = new Batch(); return getMeters().stream().flatMap(m -> m.match( batch::gaugeData, batch::counterData, batch::timerData, batch::summaryData, batch::longTaskTimerData, batch::timeGaugeData, batch::functionCounterData, batch:...
@Test void metricData() { registry.gauge("gauge", 1d); List<MetricDatum> metricDatumStream = registry.metricData(); assertThat(metricDatumStream.size()).isEqualTo(1); } @Test void metricDataWhenNaNShouldNotAdd() { registry.gauge("gauge", Double.NaN); AtomicReference<Double> value = new AtomicReference<>(Double.NaN); re...
CloudWatchUtils { static double clampMetricValue(double value) { if (Double.isNaN(value)) { return value; } double magnitude = Math.abs(value); if (magnitude == 0) { return 0; } double clampedMag = Math.min(Math.max(magnitude, MINIMUM_ALLOWED_VALUE), MAXIMUM_ALLOWED_VALUE); return Math.copySign(clampedMag, value); } pr...
@Test void testClamp() { assertThat(CloudWatchUtils.clampMetricValue(Double.NaN)) .as("Check NaN") .isNaN(); assertThat(CloudWatchUtils.clampMetricValue(Double.MIN_VALUE)) .as("Check minimum value") .isEqualTo(EXPECTED_MIN); assertThat(CloudWatchUtils.clampMetricValue(Double.NEGATIVE_INFINITY)) .as("Check negative infi...
CloudWatchNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return StringUtils.truncate(delegate.tagKey(key), MAX_TAG_KEY_LENGTH); } CloudWatchNamingConvention(); CloudWatchNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type type, @Nullab...
@Test void truncateTagKey() { assertThat(namingConvention.tagKey(repeat("x", 256))).hasSize(255); }
CloudWatchNamingConvention implements NamingConvention { @Override public String tagValue(String value) { return StringUtils.truncate(delegate.tagValue(value), MAX_TAG_VALUE_LENGTH); } CloudWatchNamingConvention(); CloudWatchNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type typ...
@Test void truncateTagValue() { assertThat(namingConvention.tagValue(repeat("x", 256))).hasSize(255); }
HumioNamingConvention implements NamingConvention { @Override public String tagKey(String key) { if (key.equals("name")) { key = "name.tag"; } return delegate.tagKey(key); } HumioNamingConvention(); HumioNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type type, @Nullable String b...
@Test void replaceNameTag() { assertThat(namingConvention.tagKey("name")).isEqualTo("name_tag"); }
HumioMeterRegistry extends StepMeterRegistry { public static Builder builder(HumioConfig config) { return new Builder(config); } @SuppressWarnings("deprecation") HumioMeterRegistry(HumioConfig config, Clock clock); private HumioMeterRegistry(HumioConfig config, Clock clock, ThreadFactory threadFactory, HttpSender htt...
@Test void writeFunctionCounter() { FunctionCounter counter = FunctionCounter.builder("myCounter", 1d, Number::doubleValue).register(meterRegistry); clock.add(config.step()); assertThat(createBatch().writeFunctionCounter(counter)).isNotNull(); } @Test void writeFunctionCounterShouldDropPositiveInfiniteValue() { Functio...
DatadogMetricMetadata { String editMetadataBody() { if (descriptionsEnabled && id.getDescription() != null) { String body = "{\"type\":\"" + type + "\""; String baseUnit = sanitizeBaseUnit(id.getBaseUnit(), overrideBaseUnit); if (baseUnit != null) { body += ",\"unit\":\"" + baseUnit + "\""; } body += ",\"description\":...
@Test void escapesStringsInDescription() { DatadogMetricMetadata metricMetadata = new DatadogMetricMetadata( Counter.builder("name") .tag("key", "value") .description("The /\"recent cpu usage\" for the Java Virtual Machine process") .register(new SimpleMeterRegistry()).getId(), Statistic.COUNT, true, null ); assertThat...
DatadogNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { String sanitized = StringEscapeUtils.escapeJson(delegate.name(name, type, baseUnit) .replace('/', '_')); if (!Character.isLetter(sanitized.charAt(0))) { sanitized = "m." + saniti...
@Test void nameStartsWithLetter() { assertThat(convention.name("123", Meter.Type.GAUGE, null)).isEqualTo("m.123"); } @Test void dotNotationIsConvertedToCamelCase() { assertThat(convention.name("gauge.size", Meter.Type.GAUGE, null)).isEqualTo("gauge.size"); }
DatadogNamingConvention implements NamingConvention { @Override public String tagKey(String key) { String sanitized = StringEscapeUtils.escapeJson(delegate.tagKey(key)); if (Character.isDigit(sanitized.charAt(0))) { sanitized = "m." + sanitized; } return sanitized; } DatadogNamingConvention(); DatadogNamingConvention(...
@Test void tagKeyStartsWithLetter() { assertThat(convention.tagKey("123")).isEqualTo("m.123"); } @Test void tagKeyWhenStartsWithNumberShouldRespectDelegateNamingConvention() { String tagKey = "123"; NamingConvention delegate = new NamingConvention() { @Override public String name(String name, Meter.Type type, @Nullable...
WavefrontNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { String sanitizedName = NAME_CLEANUP_PATTERN.matcher(delegate.name(name, type, baseUnit)).replaceAll("_"); if (namePrefix != null) { return namePrefix + "." + sanitizedName; } r...
@Test void name() { assertThat(convention.name("123abc/{:id}水", Meter.Type.GAUGE)).isEqualTo("123abc/__id__"); }
WavefrontNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return KEY_CLEANUP_PATTERN.matcher(delegate.tagKey(key)).replaceAll("_"); } WavefrontNamingConvention(@Nullable String namePrefix); WavefrontNamingConvention(@Nullable String namePrefix, NamingConvention delegate); @Ov...
@Test void tagKey() { assertThat(convention.tagKey("123abc/{:id}水")).isEqualTo("123abc___id__"); }
WavefrontNamingConvention implements NamingConvention { @Override public String tagValue(String value) { String sanitized = delegate.tagValue(value); return StringEscapeUtils.escapeJson(sanitized.endsWith("\\") ? sanitized.substring(0, sanitized.length() - 1) + "_" : sanitized); } WavefrontNamingConvention(@Nullable St...
@Test void tagValue() { assertThat(convention.tagValue("123abc/\"{:id}水\\")).isEqualTo("123abc/\\\"{:id}水_"); assertThat(convention.tagValue("\\")).isEqualTo("_"); }
WavefrontMeterRegistry extends PushMeterRegistry { void publishMetric(Meter.Id id, @Nullable String suffix, long wallTime, double value) { if (!Double.isFinite(value)) { return; } Meter.Id fullId = id; if (suffix != null) { fullId = idWithSuffix(id, suffix); } String name = getConventionName(fullId); String source = co...
@Test void publishMetric() throws IOException { Meter.Id id = registry.counter("name").getId(); long time = System.currentTimeMillis(); registry.publishMetric(id, null, System.currentTimeMillis(), 1d); verify(wavefrontSender, times(1)).sendMetric("name", 1d, time, "host", Collections.emptyMap()); verifyNoMoreInteractio...
OpenTSDBMeterRegistry extends PushMeterRegistry { Stream<String> writeTimeGauge(TimeGauge timeGauge) { double value = timeGauge.value(getBaseTimeUnit()); if (Double.isFinite(value)) { return Stream.of(writeMetric(timeGauge.getId(), config().clock().wallTime(), value)); } return Stream.empty(); } @SuppressWarnings("depr...
@Test void writeTimeGauge() { AtomicReference<Double> obj = new AtomicReference<>(1d); meterRegistry.more().timeGauge("my.time.gauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get); TimeGauge timeGauge = meterRegistry.get("my.time.gauge").timeGauge(); assertThat(meterRegistry.writeTimeGauge(timeGauge)).has...
WavefrontMeterRegistry extends PushMeterRegistry { void publishDistribution(Meter.Id id, List<WavefrontHistogramImpl.Distribution> distributions) { String name = getConventionName(id); String source = config.source(); Map<String, String> tags = getTagsAsMap(id); for (WavefrontHistogramImpl.Distribution distribution : d...
@Test void publishDistribution() throws IOException { Meter.Id id = registry.summary("name").getId(); long time = System.currentTimeMillis(); List<Pair<Double, Integer>> centroids = Arrays.asList(new Pair<>(1d, 1)); List<WavefrontHistogramImpl.Distribution> distributions = Arrays.asList( new WavefrontHistogramImpl.Dist...
WavefrontMeterRegistry extends PushMeterRegistry { public static WavefrontClient.Builder getDefaultSenderBuilder(WavefrontConfig config) { return new WavefrontClient.Builder(getWavefrontReportingUri(config), config.apiToken()).batchSize(config.batchSize()) .flushInterval((int) config.step().toMillis(), TimeUnit.MILLISE...
@Test @Issue("#2173") void defaultStepConfigAffectsWavefrontBuilder() { WavefrontClient.Builder defaultSenderBuilder = WavefrontMeterRegistry.getDefaultSenderBuilder(config); assertThat(defaultSenderBuilder).hasFieldOrPropertyWithValue("flushInterval", 60_000L); assertThat(defaultSenderBuilder).hasFieldOrPropertyWithVa...
WavefrontMeterRegistry extends PushMeterRegistry { public static Builder builder(WavefrontConfig config) { return new Builder(config); } WavefrontMeterRegistry(WavefrontConfig config, Clock clock); @Deprecated WavefrontMeterRegistry(WavefrontConfig config, Clock clock, ThreadFactory threadFactory); WavefrontMeterReg...
@Test void failsWithDefaultSenderWhenUriIsMissing() { WavefrontConfig missingUriConfig = new WavefrontConfig() { @Override public String get(String key) { return null; } @Override public String apiToken() { return "fakeToken"; } }; assertThatExceptionOfType(ValidationException.class) .isThrownBy(() -> WavefrontMeterReg...
WavefrontMeterRegistry extends PushMeterRegistry { static String getWavefrontReportingUri(WavefrontConfig wavefrontConfig) { if (!isDirectToApi(wavefrontConfig)) { return "http" + wavefrontConfig.uri().substring("proxy".length()); } return wavefrontConfig.uri(); } WavefrontMeterRegistry(WavefrontConfig config, Clock cl...
@Test void proxyUriConvertedToHttp() { assertThat(WavefrontMeterRegistry.getWavefrontReportingUri(WavefrontConfig.DEFAULT_PROXY)).startsWith("http: } @Test void directApiUriUnchanged() { assertThat(WavefrontMeterRegistry.getWavefrontReportingUri(WavefrontConfig.DEFAULT_DIRECT)).isEqualTo(WavefrontConfig.DEFAULT_DIRECT....
GangliaMeterRegistry extends StepMeterRegistry { String getMetricName(Meter.Id id, @Nullable String suffix) { return nameMapper.toHierarchicalName(id.withName(suffix != null ? id.getName() + "." + suffix : id.getName()), config().namingConvention()); } GangliaMeterRegistry(GangliaConfig config, Clock clock); @Deprecate...
@Test void getMetricNameWhenSuffixIsNullShouldNotAppendSuffix() { Meter.Id id = registry.counter("name").getId(); assertThat(registry.getMetricName(id, null)).isEqualTo("name"); } @Test void getMetricNameWhenSuffixIsNotNullShouldAppendSuffix() { Meter.Id id = registry.counter("name").getId(); assertThat(registry.getMet...
StackdriverNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return sanitize(nameDelegate.name(name, type, baseUnit), NAME_BLACKLIST, MAX_NAME_LENGTH); } StackdriverNamingConvention(); StackdriverNamingConvention(NamingConvention name...
@Test void name() { assertThat(namingConvention.name("my.counter", Meter.Type.COUNTER)).isEqualTo("my/counter"); }
StackdriverNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return sanitize(tagKeyDelegate.tagKey(key), TAG_KEY_BLACKLIST, MAX_TAG_KEY_LENGTH); } StackdriverNamingConvention(); StackdriverNamingConvention(NamingConvention nameDelegate, NamingConvention tagKeyDelegate); @Overr...
@Test void tagKey() { assertThat(namingConvention.tagKey("my.tag")).isEqualTo("my_tag"); }
StackdriverNamingConvention implements NamingConvention { @Override public String tagValue(String value) { return StringUtils.truncate(value, MAX_TAG_VALUE_LENGTH); } StackdriverNamingConvention(); StackdriverNamingConvention(NamingConvention nameDelegate, NamingConvention tagKeyDelegate); @Override String name(String...
@Test void tagValue() { assertThat(namingConvention.tagValue("my.tag.value")).isEqualTo("my.tag.value"); } @Test void tooLongTagValue() { assertThat(namingConvention.tagValue("thisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongthisistoolongt...
AzureMonitorMeterRegistry extends StepMeterRegistry { public static Builder builder(AzureMonitorConfig config) { return new Builder(config); } AzureMonitorMeterRegistry(AzureMonitorConfig config, Clock clock); private AzureMonitorMeterRegistry(AzureMonitorConfig config, Clock clock, ...
@Test void useTelemetryConfigInstrumentationKeyWhenSet() { TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.createDefault(); telemetryConfiguration.setInstrumentationKey("fake"); AzureMonitorMeterRegistry.builder(new AzureMonitorConfig() { @Override public String get(String key) { return null; } @...
AzureMonitorNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { return NAME_AND_TAG_KEY_PATTERN.matcher(delegate.name(name, type, baseUnit)).replaceAll("_"); } AzureMonitorNamingConvention(); AzureMonitorNamingConvention(NamingConventio...
@Test void testNameContainsDesiredCharacters() { assertThat(namingConvention.name("{custom@Metric.1}", Type.GAUGE)).isEqualTo("_custom_Metric_1_"); }
AzureMonitorNamingConvention implements NamingConvention { @Override public String tagKey(String key) { return NAME_AND_TAG_KEY_PATTERN.matcher(delegate.tagKey(key)).replaceAll("_"); } AzureMonitorNamingConvention(); AzureMonitorNamingConvention(NamingConvention delegate); @Override String name(String name, Meter.Type...
@Test void testTagKeyContainsDesiredCharacters() { assertThat(namingConvention.tagKey("Pc.N@me")).isEqualTo("Pc_N_me"); }
CloudWatchMeterRegistry extends StepMeterRegistry { List<MetricDatum> metricData() { Batch batch = new Batch(); return getMeters().stream().flatMap(m -> m.match( batch::gaugeData, batch::counterData, batch::timerData, batch::summaryData, batch::longTaskTimerData, batch::timeGaugeData, batch::functionCounterData, batch:...
@Test void metricData() { registry.gauge("gauge", 1d); List<MetricDatum> metricDatumStream = registry.metricData(); assertThat(metricDatumStream.size()).isEqualTo(1); } @Test void metricDataWhenNaNShouldNotAdd() { registry.gauge("gauge", Double.NaN); AtomicReference<Double> value = new AtomicReference<>(Double.NaN); re...
StringUtils { public static String truncate(String string, int maxLength) { if (string.length() > maxLength) { return string.substring(0, maxLength); } return string; } private StringUtils(); static boolean isBlank(@Nullable String string); static boolean isNotBlank(@Nullable String string); static boolean isEmpty(@Nu...
@Test void truncateWhenGreaterThanMaxLengthShouldTruncate() { assertThat(StringUtils.truncate("1234567890", 5)).isEqualTo("12345"); } @Test void truncateWhenLessThanMaxLengthShouldReturnItself() { assertThat(StringUtils.truncate("123", 5)).isEqualTo("123"); }
OpenTSDBMeterRegistry extends PushMeterRegistry { Stream<String> writeFunctionCounter(FunctionCounter counter) { double count = counter.count(); if (Double.isFinite(count)) { return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), count)); } return Stream.empty(); } @SuppressWarnings("deprecation") ...
@Test void writeFunctionCounter() { FunctionCounter counter = FunctionCounter.builder("my.counter", 1d, Number::doubleValue).register(meterRegistry); clock.add(config.step()); assertThat(meterRegistry.writeFunctionCounter(counter)).hasSize(1); }
StringUtils { public static boolean isNotEmpty(@Nullable String string) { return !isEmpty(string); } private StringUtils(); static boolean isBlank(@Nullable String string); static boolean isNotBlank(@Nullable String string); static boolean isEmpty(@Nullable String string); static boolean isNotEmpty(@Nullable String st...
@Test void isNotEmptyWhenNullShouldBeFalse() { assertThat(StringUtils.isNotEmpty(null)).isFalse(); } @Test void isNotEmptyWhenEmptyShouldBeFalse() { assertThat(StringUtils.isNotEmpty("")).isFalse(); } @Test void isNotEmptyWhenHasAnyCharacterShouldBeFalse() { assertThat(StringUtils.isNotEmpty(" ")).isTrue(); }
TimeUtils { @Deprecated public static Duration simpleParse(String time) { String timeLower = PARSE_PATTERN.matcher(time.toLowerCase()).replaceAll(""); if (timeLower.endsWith("ns")) { return Duration.ofNanos(Long.parseLong(timeLower.substring(0, timeLower.length() - 2))); } else if (timeLower.endsWith("ms")) { return Du...
@Test void simpleParse() { assertThat(TimeUtils.simpleParse("5ns")).isEqualByComparingTo(Duration.ofNanos(5)); assertThat(TimeUtils.simpleParse("700ms")).isEqualByComparingTo(Duration.ofMillis(700)); assertThat(TimeUtils.simpleParse("1s")).isEqualByComparingTo(Duration.ofSeconds(1)); assertThat(TimeUtils.simpleParse("1...
TimeUtils { public static String format(Duration duration) { return duration.toString() .substring(2) .replaceAll("(\\d[HMS])(?!$)", "$1 ") .toLowerCase(); } private TimeUtils(); static double convert(double t, TimeUnit sourceUnit, TimeUnit destinationUnit); static double nanosToUnit(double nanos, TimeUnit destination...
@Test void formatDuration() { assertThat(TimeUtils.format(Duration.ofSeconds(10))).isEqualTo("10s"); assertThat(TimeUtils.format(Duration.ofSeconds(90))).isEqualTo("1m 30s"); assertThat(TimeUtils.format(Duration.ofMinutes(2))).isEqualTo("2m"); assertThat(TimeUtils.format(Duration.ofNanos(1001234000000L))).isEqualTo("16...
StringEscapeUtils { public static String escapeJson(@Nullable String v) { if (v == null) return ""; int length = v.length(); if (length == 0) return v; int afterReplacement = 0; StringBuilder builder = null; for (int i = 0; i < length; i++) { char c = v.charAt(i); String replacement; if (c < 0x80) { replacement = REPLA...
@Test void escapeJsonWhenNullShouldReturnEmptyString() { assertThat(StringEscapeUtils.escapeJson(null)).isEmpty(); } @Test void escapeJsonWhenEmptyStringShouldReturnEmptyString() { assertThat(StringEscapeUtils.escapeJson("")).isEmpty(); } @Test void escapeJsonWhenDoubleQuotesShouldReturnEscapedString() { assertThat(Str...
OpenTSDBNamingConvention implements NamingConvention { @Override public String name(String name, Meter.Type type, @Nullable String baseUnit) { String conventionName = NamingConvention.snakeCase.name(name, type, baseUnit); switch (type) { case COUNTER: case DISTRIBUTION_SUMMARY: case GAUGE: if (baseUnit != null && !conv...
@Test void defaultToSnakeCase() { assertThat(convention.name("gauge.size", Meter.Type.GAUGE)).isEqualTo("gauge_size"); }
AbstractPartition extends AbstractList<List<T>> { @Override public List<T> get(int index) { int start = index * partitionSize; int end = Math.min(start + partitionSize, delegate.size()); return delegate.subList(start, end); } protected AbstractPartition(List<T> delegate, int partitionSize); @Override List<T> get(int i...
@Test void singlePartitionListActsLikeDelegate_singleElement() { TestPartition singlePartition = new TestPartition(asList("foo"), 1); assertThat(singlePartition).hasSize(1); assertThat(singlePartition.get(0)).containsExactly("foo"); } @Test void singlePartitionListActsLikeDelegate_multipleElements() { TestPartition sin...
AbstractPartition extends AbstractList<List<T>> { static <T> int partitionCount(List<T> delegate, int partitionSize) { int result = delegate.size() / partitionSize; return delegate.size() % partitionSize == 0 ? result : result + 1; } protected AbstractPartition(List<T> delegate, int partitionSize); @Override List<T> g...
@Test void partitionCount_roundsUp() { assertThat(partitionCount(asList("foo", "bar", "baz"), 2)) .isEqualTo(2); }
NamedThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); int seq = sequence.getAndIncrement(); thread.setName(prefix + (seq > 1 ? "-" + seq : "")); if (!thread.isDaemon()) thread.setDaemon(true); return thread; } NamedThreadFactory(String prefix); @Ove...
@Test void nameThreads() { NamedThreadFactory threadFactory = new NamedThreadFactory("name"); Runnable body = () -> { }; assertThat(threadFactory.newThread(body).getName()).isEqualTo("name"); assertThat(threadFactory.newThread(body).getName()).isEqualTo("name-2"); }
IOUtils { public static String toString(@Nullable InputStream inputStream, Charset charset) { if (inputStream == null) return ""; try (StringWriter writer = new StringWriter(); InputStreamReader reader = new InputStreamReader(inputStream, charset); BufferedReader bufferedReader = new BufferedReader(reader)) { char[] ch...
@Test void testToString() { String expected = "This is a sample."; ByteArrayInputStream inputStream = new ByteArrayInputStream(expected.getBytes()); assertThat(IOUtils.toString(inputStream)).isEqualTo(expected); } @Test void testToStringWithCharset() { String expected = "This is a sample."; ByteArrayInputStream inputSt...
DoubleFormat { public static String decimalOrNan(double d) { return DECIMAL_OR_NAN.get().format(d); } private DoubleFormat(); static String decimalOrNan(double d); @Deprecated static String decimalOrWhole(double d); static String decimal(double d); static String wholeOrDecimal(double d); }
@Test void decimalOrNan() { assertThat(DoubleFormat.decimalOrNan(Double.NaN)).isEqualTo("NaN"); assertThat(DoubleFormat.decimalOrNan(123456.1234567)).isEqualTo("123456.123457"); assertThat(DoubleFormat.decimalOrNan(123456)).isEqualTo("123456"); assertThat(DoubleFormat.decimalOrNan(0.123)).isEqualTo("0.123"); }
DoubleFormat { public static String wholeOrDecimal(double d) { return WHOLE_OR_DECIMAL.get().format(d); } private DoubleFormat(); static String decimalOrNan(double d); @Deprecated static String decimalOrWhole(double d); static String decimal(double d); static String wholeOrDecimal(double d); }
@Test void wholeOrDecimal() { assertThat(DoubleFormat.wholeOrDecimal(123456.1234567)).isEqualTo("123456.123457"); assertThat(DoubleFormat.wholeOrDecimal(1)).isEqualTo("1"); }
ElasticMeterRegistry extends StepMeterRegistry { Optional<String> writeTimer(Timer timer) { return Optional.of(writeDocument(timer, builder -> { builder.append(",\"count\":").append(timer.count()); builder.append(",\"sum\":").append(timer.totalTime(getBaseTimeUnit())); builder.append(",\"mean\":").append(timer.mean(get...
@Test void writeTimer() { Timer timer = Timer.builder("myTimer").register(registry); assertThat(registry.writeTimer(timer)).contains("{ \"index\" : {} }\n{\"@timestamp\":\"1970-01-01T00:00:00.001Z\",\"name\":\"myTimer\",\"type\":\"timer\",\"count\":0,\"sum\":0.0,\"mean\":0.0,\"max\":0.0}"); }
DoubleFormat { public static String decimal(double d) { return DECIMAL.get().format(d); } private DoubleFormat(); static String decimalOrNan(double d); @Deprecated static String decimalOrWhole(double d); static String decimal(double d); static String wholeOrDecimal(double d); }
@Test void decimal() { assertThat(DoubleFormat.decimal(123456.1234567)).isEqualTo("123456.123457"); assertThat(DoubleFormat.decimal(123456)).isEqualTo("123456.0"); assertThat(DoubleFormat.decimal(0.123)).isEqualTo("0.123"); }
CumulativeFunctionTimer implements FunctionTimer { public double totalTime(TimeUnit unit) { T obj2 = ref.get(); if (obj2 != null) { lastTime = Math.max(TimeUtils.convert(totalTimeFunction.applyAsDouble(obj2), totalTimeFunctionUnit, baseTimeUnit()), 0); } return TimeUtils.convert(lastTime, baseTimeUnit(), unit); } Cumul...
@Test void totalTimeWhenStateObjectChangedToNullShouldWorkWithChangedTimeUnit() { CumulativeFunctionTimer<Object> functionTimer = new CumulativeFunctionTimer<>( null, new Object(), (o) -> 1L, (o) -> 1d, TimeUnit.SECONDS, TimeUnit.SECONDS); assertThat(functionTimer.totalTime(TimeUnit.SECONDS)).isEqualTo(1d); assertThat(...
MeterRegistry { @Incubating(since = "1.2.0") public void clear() { meterMap.keySet().forEach(this::remove); } protected MeterRegistry(Clock clock); List<Meter> getMeters(); void forEachMeter(Consumer<? super Meter> consumer); Config config(); Search find(String name); RequiredSearch get(String name); Counter counter(S...
@Test void clear() { registry.counter("my.counter"); registry.counter("my.counter2"); assertThat(registry.find("my.counter").counter()).isNotNull(); assertThat(registry.find("my.counter2").counter()).isNotNull(); registry.clear(); assertThat(registry.find("my.counter").counter()).isNull(); assertThat(registry.find("my....
SimpleMeterRegistry extends MeterRegistry { @Override protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit) { switch (config.mode()) { case CUMULATIVE: return new CumulativeFunctionTimer<>(id, obj, countFu...
@Test void newFunctionTimerWhenCountingModeIsCumulativeShouldReturnCumulativeFunctionTimer() { SimpleMeterRegistry registry = createRegistry(CountingMode.CUMULATIVE); Meter.Id id = new Meter.Id("some.timer", Tags.empty(), null, null, Meter.Type.TIMER); FunctionTimer functionTimer = registry.newFunctionTimer(id, null, (...
SimpleMeterRegistry extends MeterRegistry { @Override protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) { switch (config.mode()) { case CUMULATIVE: return new CumulativeFunctionCounter<>(id, obj, countFunction); case STEP: default: return new StepFunctionCounter<>(i...
@Test void newFunctionCounterWhenCountingModeIsCumulativeShouldReturnCumulativeFunctionCounter() { SimpleMeterRegistry registry = createRegistry(CountingMode.CUMULATIVE); Meter.Id id = new Meter.Id("some.timer", Tags.empty(), null, null, Meter.Type.COUNTER); FunctionCounter functionCounter = registry.newFunctionCounter...