Skip to content

Commit

Permalink
Upgrade to Spring Java Format 0.0.36 (micrometer-metrics#3662)
Browse files Browse the repository at this point in the history
  • Loading branch information
izeye authored Feb 22, 2023
1 parent 1e38bd1 commit d00abb9
Show file tree
Hide file tree
Showing 333 changed files with 4,410 additions and 2,863 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,11 @@ public static class PrometheusState {
@Setup(Level.Trial)
public void setup() {
counter = io.prometheus.client.Counter.build().name("counter").help("A counter").create();
counterWithTags = io.prometheus.client.Counter.build().name("counter")
.help("Counter with two tags declared").labelNames("key1", "key2").register();
counterWithTags = io.prometheus.client.Counter.build()
.name("counter")
.help("Counter with two tags declared")
.labelNames("key1", "key2")
.register();
}

}
Expand Down Expand Up @@ -174,7 +177,8 @@ public void prometheusCounterWithTags(PrometheusState state) {

public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(CompareCountersWithOtherLibraries.class.getSimpleName())
.addProfiler(GCProfiler.class).build();
.addProfiler(GCProfiler.class)
.build();
new Runner(opt).run();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ public static class Data {
public void setup() {
final Random r = new Random(1234567891L);
dataIterator = Iterators.cycle(Stream.generate(() -> Math.round(Math.exp(2.0 + r.nextGaussian())))
.limit(1048576).collect(Collectors.toList()));
.limit(1048576)
.collect(Collectors.toList()));
}

}
Expand Down Expand Up @@ -145,11 +146,15 @@ public static class PrometheusState {

@Setup(Level.Trial)
public void setup() {
double[] micrometerBuckets = Doubles.toArray(
PercentileHistogramBuckets.buckets(DistributionStatisticConfig.builder().minimumExpectedValue(0.0)
.maximumExpectedValue(Double.POSITIVE_INFINITY).percentilesHistogram(true).build()));
histogram = io.prometheus.client.Histogram.build("histogram", "A histogram").buckets(micrometerBuckets)
.create();
double[] micrometerBuckets = Doubles
.toArray(PercentileHistogramBuckets.buckets(DistributionStatisticConfig.builder()
.minimumExpectedValue(0.0)
.maximumExpectedValue(Double.POSITIVE_INFINITY)
.percentilesHistogram(true)
.build()));
histogram = io.prometheus.client.Histogram.build("histogram", "A histogram")
.buckets(micrometerBuckets)
.create();
}

@TearDown(Level.Iteration)
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ buildscript {
classpath 'io.github.gradle-nexus:publish-plugin:1.1.0'
classpath 'me.champeau.gradle:japicmp-gradle-plugin:0.4.1'
classpath 'de.undercouch:gradle-download-task:5.2.1'
classpath 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.35'
classpath 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.36'

constraints {
classpath('org.ow2.asm:asm:7.3.1') {
Expand Down
4 changes: 2 additions & 2 deletions buildscript-gradle.lockfile

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ Optional<String> writeMeter(Meter meter) {
}
StringJoiner joiner = new StringJoiner(",");
for (int i = 0; i < statistics.size(); i++) {
joiner.add(
write(meter.getId().withTag(statistics.get(i)), null, Fields.Value.tag(), decimal(values.get(i))));
joiner
.add(write(meter.getId().withTag(statistics.get(i)), null, Fields.Value.tag(), decimal(values.get(i))));
}
return Optional.of(joiner.toString());
}
Expand Down Expand Up @@ -240,9 +240,9 @@ private Optional<String> writeTimer(Timer timer) {
private Optional<String> writeSummary(DistributionSummary summary) {
HistogramSnapshot snapshot = summary.takeSnapshot();
if (snapshot.count() > 0) {
return Optional.of(write(summary.getId(), "distributionSummary", Fields.Count.tag(),
decimal(summary.count()), Fields.Sum.tag(), decimal(summary.totalAmount()), Fields.Max.tag(),
decimal(summary.max())));
return Optional
.of(write(summary.getId(), "distributionSummary", Fields.Count.tag(), decimal(summary.count()),
Fields.Sum.tag(), decimal(summary.totalAmount()), Fields.Max.tag(), decimal(summary.max())));
}
return Optional.empty();
}
Expand All @@ -258,8 +258,10 @@ private Optional<String> writeLongTaskTimer(LongTaskTimer timer) {

private String write(Meter.Id id, @Nullable String type, String... statistics) {
StringBuilder sb = new StringBuilder();
sb.append("{\"name\":\"").append(escapeJson(getConventionName(id))).append("\",\"period\":")
.append(config.step().getSeconds());
sb.append("{\"name\":\"")
.append(escapeJson(getConventionName(id)))
.append("\",\"period\":")
.append(config.step().getSeconds());

if (!Fields.Value.tag().equals(statistics[0])) {
sb.append(",\"attributes\":{\"aggregate\":false}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ void invalid() {
props.put("appoptics.batchSize", Integer.toString(AppOpticsConfig.MAX_BATCH_SIZE * 2));

assertThat(config.validate().failures().stream().map(Validated.Invalid::getMessage))
.containsExactlyInAnyOrder("must be a valid URL", "is required");
.containsExactlyInAnyOrder("must be a valid URL", "is required");
}

@Test
Expand Down Expand Up @@ -65,7 +65,7 @@ public String get(String key) {
}.validate();

assertThat(validate.failures().stream().map(Validated.Invalid::getMessage))
.containsOnly("cannot be greater than " + AppOpticsConfig.MAX_BATCH_SIZE);
.containsOnly("cannot be greater than " + AppOpticsConfig.MAX_BATCH_SIZE);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,12 @@ void writeFunctionCounter() {
@Test
void writeFunctionCounterShouldDropInfiniteValues() {
FunctionCounter counter = FunctionCounter.builder("myCounter", Double.POSITIVE_INFINITY, Number::doubleValue)
.register(meterRegistry);
.register(meterRegistry);
clock.add(config.step());
assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isFalse();

counter = FunctionCounter.builder("myCounter", Double.NEGATIVE_INFINITY, Number::doubleValue)
.register(meterRegistry);
.register(meterRegistry);
clock.add(config.step());
assertThat(meterRegistry.writeFunctionCounter(counter).isPresent()).isFalse();
}
Expand Down Expand Up @@ -188,7 +188,7 @@ void defaultValueDoesNoFlooring() {
clock.add(Duration.ofSeconds(63));

assertThat(meterRegistry.getBodyMeasurementsPrefix())
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 63));
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 63));
}

@Test
Expand All @@ -198,17 +198,17 @@ void flooringRoundsToNearestStep() {
clock.add(Duration.ofSeconds(63));

assertThat(meterRegistry.getBodyMeasurementsPrefix())
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60));
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60));

clock.addSeconds(56); // 119

assertThat(meterRegistry.getBodyMeasurementsPrefix())
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60));
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 60));

clock.addSeconds(1); // 120

assertThat(meterRegistry.getBodyMeasurementsPrefix())
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 120));
.isEqualTo(String.format(AppOpticsMeterRegistry.BODY_MEASUREMENTS_PREFIX, 120));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ private void registerHistogramGauges(HistogramSupport histogramSupport, Meter.Id

private Id spectatorId(Meter.Id id) {
List<com.netflix.spectator.api.Tag> tags = getConventionTags(id).stream()
.map(t -> new BasicTag(t.getKey(), t.getValue())).collect(toList());
.map(t -> new BasicTag(t.getKey(), t.getValue()))
.collect(toList());
return registry.createId(getConventionName(id), tags);
}

Expand All @@ -175,8 +176,9 @@ protected <T> io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, @Nullabl
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
FunctionCounter fc = new StepFunctionCounter<>(id, clock, atlasConfig.step().toMillis(), obj, countFunction);
PolledMeter.using(registry).withId(spectatorId(id)).monitorMonotonicCounter(obj,
obj2 -> (long) countFunction.applyAsDouble(obj2));
PolledMeter.using(registry)
.withId(spectatorId(id))
.monitorMonotonicCounter(obj, obj2 -> (long) countFunction.applyAsDouble(obj2));
return fc;
}

Expand Down Expand Up @@ -231,8 +233,10 @@ protected TimeUnit getBaseTimeUnit() {

@Override
protected DistributionStatisticConfig defaultHistogramConfig() {
return DistributionStatisticConfig.builder().expiry(atlasConfig.step()).build()
.merge(DistributionStatisticConfig.DEFAULT);
return DistributionStatisticConfig.builder()
.expiry(atlasConfig.step())
.build()
.merge(DistributionStatisticConfig.DEFAULT);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public double totalAmount() {
public double max() {
for (Measurement measurement : summary.measure()) {
if (stream(measurement.id().tags().spliterator(), false)
.anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) {
.anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) {
return measurement.value();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public double totalTime(TimeUnit unit) {
public double max(TimeUnit unit) {
for (Measurement measurement : timer.measure()) {
if (stream(measurement.id().tags().spliterator(), false)
.anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) {
.anyMatch(tag -> tag.key().equals("statistic") && tag.value().equals(Statistic.max.toString()))) {
return TimeUtils.secondsToUnit(measurement.value(), unit);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
* identical to com.netflix.spectator.api.ObjectGauge which is not accessible in
* Spectator.
*/
class SpectatorToDoubleGauge<T> extends AbstractMeter<T> implements Gauge {
class SpectatorToDoubleGauge<T>extends AbstractMeter<T> implements Gauge {

private final ToDoubleFunction<T> f;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,11 @@ public Duration lwcStep() {
AtlasRegistry r = (AtlasRegistry) registry.getSpectatorRegistry();
PolledMeter.update(r);
clock.add(Duration.ofMinutes(1));
return r.measurements().filter(m -> m.id().name().equals("test")).findFirst().map(Measurement::value)
.orElse(Double.NaN);
return r.measurements()
.filter(m -> m.id().name().equals("test"))
.findFirst()
.map(Measurement::value)
.orElse(Double.NaN);
};

count.addAndGet(60);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ private MetricTelemetry createMetricTelemetry(Meter meter, @Nullable String suff
MetricTelemetry mt = new MetricTelemetry();

Meter.Id id = meter.getId();
mt.setName(config().namingConvention().name(id.getName() + (suffix == null ? "" : "." + suffix), id.getType(),
id.getBaseUnit()));
mt.setName(config().namingConvention()
.name(id.getName() + (suffix == null ? "" : "." + suffix), id.getType(), id.getBaseUnit()));

for (Tag tag : getConventionTags(meter.getId())) {
mt.getContext().getProperties().putIfAbsent(tag.getKey(), tag.getValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ void useTelemetryConfigInstrumentationKeyWhenSet() {
@Test
void failWhenTelemetryConfigInstrumentationKeyIsUnsetAndConfigInstrumentationKeyIsNull() {
TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.createDefault();
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> AzureMonitorMeterRegistry
.builder(key -> null).telemetryConfiguration(telemetryConfiguration).build());
assertThatExceptionOfType(ValidationException.class)
.isThrownBy(() -> AzureMonitorMeterRegistry.builder(key -> null)
.telemetryConfiguration(telemetryConfiguration)
.build());
}

@Test
Expand All @@ -86,25 +88,25 @@ void trackTimerWhenCountIsZeroShouldReturnEmpty() {
@Test
void trackFunctionTimer() {
FunctionTimer functionTimer = FunctionTimer
.builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS)
.register(registry);
.builder("my.function.timer", 1d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS)
.register(registry);
clock.add(config.step());
assertThat(registry.trackFunctionTimer(functionTimer)).hasSize(1);
}

@Test
void trackFunctionTimerWhenCountIsZeroShouldReturnEmpty() {
FunctionTimer functionTimer = FunctionTimer
.builder("my.function.timer", 0d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS)
.register(registry);
.builder("my.function.timer", 0d, Number::longValue, Number::doubleValue, TimeUnit.MILLISECONDS)
.register(registry);
clock.add(config.step());
assertThat(registry.trackFunctionTimer(functionTimer)).isEmpty();
}

@Test
void trackDistributionSummary() {
DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution.summary")
.register(registry);
.register(registry);
distributionSummary.record(1d);
clock.add(config.step());
assertThat(registry.trackDistributionSummary(distributionSummary)).hasSize(1);
Expand All @@ -113,7 +115,7 @@ void trackDistributionSummary() {
@Test
void trackDistributionSummaryWhenCountIsZeroShouldReturnEmpty() {
DistributionSummary distributionSummary = DistributionSummary.builder("my.distribution.summary")
.register(registry);
.register(registry);
clock.add(config.step());
assertThat(registry.trackDistributionSummary(distributionSummary)).isEmpty();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ protected void publish() {
// VisibleForTesting
void sendMetricData(List<MetricDatum> metricData) throws InterruptedException {
PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest().withNamespace(config.namespace())
.withMetricData(metricData);
.withMetricData(metricData);
CountDownLatch latch = new CountDownLatch(1);
amazonCloudWatchAsync.putMetricDataAsync(putMetricDataRequest,
new AsyncHandler<PutMetricDataRequest, PutMetricDataResult>() {
Expand Down Expand Up @@ -182,8 +182,8 @@ private Stream<MetricDatum> counterData(Counter counter) {
// VisibleForTesting
Stream<MetricDatum> timerData(Timer timer) {
Stream.Builder<MetricDatum> metrics = Stream.builder();
metrics.add(
metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit())));
metrics
.add(metricDatum(timer.getId(), "sum", getBaseTimeUnit().name(), timer.totalTime(getBaseTimeUnit())));
long count = timer.count();
metrics.add(metricDatum(timer.getId(), "count", StandardUnit.Count, count));
if (count > 0) {
Expand Down Expand Up @@ -250,8 +250,8 @@ Stream<MetricDatum> functionTimerData(FunctionTimer timer) {
// VisibleForTesting
Stream<MetricDatum> metricData(Meter m) {
return stream(m.measure().spliterator(), false)
.map(ms -> metricDatum(m.getId().withTag(ms.getStatistic()), ms.getValue()))
.filter(Objects::nonNull);
.map(ms -> metricDatum(m.getId().withTag(ms.getStatistic()), ms.getValue()))
.filter(Objects::nonNull);
}

@Nullable
Expand All @@ -276,8 +276,11 @@ private MetricDatum metricDatum(Meter.Id id, @Nullable String suffix, StandardUn
}

List<Tag> tags = id.getConventionTags(config().namingConvention());
return new MetricDatum().withMetricName(getMetricName(id, suffix)).withDimensions(toDimensions(tags))
.withTimestamp(timestamp).withValue(CloudWatchUtils.clampMetricValue(value)).withUnit(standardUnit);
return new MetricDatum().withMetricName(getMetricName(id, suffix))
.withDimensions(toDimensions(tags))
.withTimestamp(timestamp)
.withValue(CloudWatchUtils.clampMetricValue(value))
.withUnit(standardUnit);
}

// VisibleForTesting
Expand All @@ -295,14 +298,16 @@ private StandardUnit toStandardUnit(@Nullable String unit) {
}

private List<Dimension> toDimensions(List<Tag> tags) {
return tags.stream().filter(this::isAcceptableTag)
.map(tag -> new Dimension().withName(tag.getKey()).withValue(tag.getValue())).collect(toList());
return tags.stream()
.filter(this::isAcceptableTag)
.map(tag -> new Dimension().withName(tag.getKey()).withValue(tag.getValue()))
.collect(toList());
}

private boolean isAcceptableTag(Tag tag) {
if (StringUtils.isBlank(tag.getValue())) {
warnThenDebugLogger
.log(() -> "Dropping a tag with key '" + tag.getKey() + "' because its value is blank.");
.log(() -> "Dropping a tag with key '" + tag.getKey() + "' because its value is blank.");
return false;
}
return true;
Expand Down
Loading

0 comments on commit d00abb9

Please sign in to comment.