Skip to content

Commit

Permalink
Use String.toLowerCase()/toUpperCase() with Locale.ROOT consistently
Browse files Browse the repository at this point in the history
This commit also adds Checkstyle rules for it.
  • Loading branch information
izeye committed Nov 27, 2024
1 parent 15b3674 commit ea93fd1
Show file tree
Hide file tree
Showing 28 changed files with 92 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.Locale;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
Expand Down Expand Up @@ -58,7 +59,7 @@ public static void main(String[] args) throws RunnerException {
public void setup() {
clock = new MockClock();
longTaskTimer = new DefaultLongTaskTimer(
new Meter.Id("ltt", Tags.empty(), TimeUnit.MILLISECONDS.toString().toLowerCase(), null,
new Meter.Id("ltt", Tags.empty(), TimeUnit.MILLISECONDS.toString().toLowerCase(Locale.ROOT), null,
Meter.Type.LONG_TASK_TIMER),
clock, TimeUnit.MILLISECONDS, DistributionStatisticConfig.DEFAULT, false);
int randomIndex = random.nextInt(activeSampleCount);
Expand Down
16 changes: 16 additions & 0 deletions config/checkstyle/checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,22 @@
<property name="message" value="Please use AssertJ imports." />
<property name="ignoreComments" value="true" />
</module>
<module name="com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck">
<property name="id" value="toLowerCaseWithoutLocale"/>
<property name="format" value="\.toLowerCase\(\)"/>
<property name="maximum" value="0"/>
<property name="message"
value="String.toLowerCase(Locale.ROOT) should be String.toLowerCase(Locale.ROOT)"/>
<property name="ignoreComments" value="true"/>
</module>
<module name="com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck">
<property name="id" value="toUpperCaseWithoutLocale"/>
<property name="format" value="\.toUpperCase\(\)"/>
<property name="maximum" value="0"/>
<property name="message"
value="String.toUpperCase(Locale.ROOT) should be String.toUpperCase(Locale.ROOT)"/>
<property name="ignoreComments" value="true"/>
</module>

<!-- Whitespace -->
<module name="SingleSpaceSeparator" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Locale;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
Expand Down Expand Up @@ -114,7 +115,7 @@ protected void publish() {

private Stream<MetricTelemetry> trackMeter(Meter meter) {
return stream(meter.measure().spliterator(), false).map(ms -> {
MetricTelemetry mt = createMetricTelemetry(meter, ms.getStatistic().toString().toLowerCase());
MetricTelemetry mt = createMetricTelemetry(meter, ms.getStatistic().toString().toLowerCase(Locale.ROOT));
mt.setValue(ms.getValue());
return mt;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public class CloudWatchMeterRegistry extends StepMeterRegistry {
Map<String, StandardUnit> standardUnitByLowercaseValue = new HashMap<>();
for (StandardUnit standardUnit : StandardUnit.values()) {
if (standardUnit != StandardUnit.UNKNOWN_TO_SDK_VERSION) {
standardUnitByLowercaseValue.put(standardUnit.toString().toLowerCase(), standardUnit);
standardUnitByLowercaseValue.put(standardUnit.toString().toLowerCase(Locale.ROOT), standardUnit);
}
}
STANDARD_UNIT_BY_LOWERCASE_VALUE = Collections.unmodifiableMap(standardUnitByLowercaseValue);
Expand Down Expand Up @@ -308,7 +308,7 @@ StandardUnit toStandardUnit(@Nullable String unit) {
if (unit == null) {
return StandardUnit.NONE;
}
StandardUnit standardUnit = STANDARD_UNIT_BY_LOWERCASE_VALUE.get(unit.toLowerCase());
StandardUnit standardUnit = STANDARD_UNIT_BY_LOWERCASE_VALUE.get(unit.toLowerCase(Locale.ROOT));
return standardUnit != null ? standardUnit : StandardUnit.NONE;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.junit.jupiter.api.extension.ExtendWith;
import ru.lanwen.wiremock.ext.WiremockResolver;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
Expand Down Expand Up @@ -71,7 +72,7 @@ public boolean enabled() {
server.stubFor(any(anyUrl()));

Counter.builder("my.counter#abc")
.baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase())
.baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase(Locale.ROOT))
.description("metric description")
.register(registry)
.increment(Math.PI);
Expand Down Expand Up @@ -121,7 +122,7 @@ public boolean enabled() {
server.stubFor(any(anyUrl()));

Counter.builder("my.counter#abc")
.baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase())
.baseUnit(TimeUnit.MICROSECONDS.toString().toLowerCase(Locale.ROOT))
.description("metric description")
.register(registry)
.increment(Math.PI);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.micrometer.core.instrument.util.StringEscapeUtils;

import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
Expand Down Expand Up @@ -109,7 +110,7 @@ enum DynatraceUnit {

private static Map<String, DynatraceUnit> UNITS_MAPPING = Collections
.unmodifiableMap(Stream.of(DynatraceUnit.values())
.collect(Collectors.toMap(k -> k.toString().toLowerCase() + "s", Function.identity())));
.collect(Collectors.toMap(k -> k.toString().toLowerCase(Locale.ROOT) + "s", Function.identity())));

@Nullable
static DynatraceUnit fromPlural(@Nullable String plural) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ private String extractMetricKey(String metadataLine) {
* @return The UCUM-compliant string if known, otherwise returns the original unit
*/
private static String mapUnitIfNeeded(String unit) {
return unit != null ? UCUM_TIME_UNIT_MAP.getOrDefault(unit.toLowerCase(), unit) : null;
return unit != null ? UCUM_TIME_UNIT_MAP.getOrDefault(unit.toLowerCase(Locale.ROOT), unit) : null;
}

/**
Expand All @@ -570,22 +570,22 @@ private static String mapUnitIfNeeded(String unit) {
private static Map<String, String> ucumTimeUnitMap() {
Map<String, String> mapping = new HashMap<>();
// There are redundant elements in case the toString method of TimeUnit changes
mapping.put(TimeUnit.NANOSECONDS.toString().toLowerCase(), "ns");
mapping.put(TimeUnit.NANOSECONDS.toString().toLowerCase(Locale.ROOT), "ns");
mapping.put("nanoseconds", "ns");
mapping.put("nanosecond", "ns");
mapping.put(TimeUnit.MICROSECONDS.toString().toLowerCase(), "us");
mapping.put(TimeUnit.MICROSECONDS.toString().toLowerCase(Locale.ROOT), "us");
mapping.put("microseconds", "us");
mapping.put("microsecond", "us");
mapping.put(TimeUnit.MILLISECONDS.toString().toLowerCase(), "ms");
mapping.put(TimeUnit.MILLISECONDS.toString().toLowerCase(Locale.ROOT), "ms");
mapping.put("milliseconds", "ms");
mapping.put("millisecond", "ms");
mapping.put(TimeUnit.SECONDS.toString().toLowerCase(), "s");
mapping.put(TimeUnit.SECONDS.toString().toLowerCase(Locale.ROOT), "s");
mapping.put("seconds", "s");
mapping.put("second", "s");
mapping.put(TimeUnit.MINUTES.toString().toLowerCase(), "min");
mapping.put(TimeUnit.MINUTES.toString().toLowerCase(Locale.ROOT), "min");
mapping.put("minutes", "min");
mapping.put("minute", "min");
mapping.put(TimeUnit.HOURS.toString().toLowerCase(), "h");
mapping.put(TimeUnit.HOURS.toString().toLowerCase(Locale.ROOT), "h");
mapping.put("hours", "h");
mapping.put("hour", "h");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.micrometer.common.lang.NonNull;
import io.micrometer.common.util.StringUtils;
import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.HistogramSnapshot;
import io.micrometer.core.instrument.step.StepMeterRegistry;
import io.micrometer.core.instrument.util.MeterPartition;
Expand All @@ -31,10 +32,7 @@
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
Expand Down Expand Up @@ -349,7 +347,7 @@ String writeDocument(Meter meter, Consumer<StringBuilder> consumer) {
StringBuilder sb = new StringBuilder(actionLine);
String timestamp = generateTimestamp();
String name = getConventionName(meter.getId());
String type = meter.getId().getType().toString().toLowerCase();
String type = meter.getId().getType().toString().toLowerCase(Locale.ROOT);
sb.append("{\"")
.append(config.timestampFieldName())
.append("\":\"")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -134,7 +135,7 @@ protected void publish() {

private void announceMeter(Meter meter) {
for (Measurement measurement : meter.measure()) {
announce(meter, measurement.getValue(), measurement.getStatistic().toString().toLowerCase());
announce(meter, measurement.getValue(), measurement.getStatistic().toString().toLowerCase(Locale.ROOT));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public double getValue(MeterRegistry registry) {
public String getValueAsString(MeterRegistry registry) {
double value = getValue(registry);
return Double.isNaN(value) ? "no value available"
: getBaseUnit() != null && getBaseUnit().toLowerCase().contains("percent")
: getBaseUnit() != null && getBaseUnit().toLowerCase(Locale.ROOT).contains("percent")
? WHOLE_OR_SHORT_DECIMAL.get().format(value * 100) + "%"
: WHOLE_OR_SHORT_DECIMAL.get().format(value);
}
Expand Down Expand Up @@ -366,7 +366,7 @@ public abstract static class NumericQuery {
abstract Double getValue(MeterRegistry registry);

private String thresholdString(double threshold) {
return baseUnit != null && baseUnit.toLowerCase().contains("percent")
return baseUnit != null && baseUnit.toLowerCase(Locale.ROOT).contains("percent")
? WHOLE_OR_SHORT_DECIMAL.get().format(threshold * 100) + "%"
: WHOLE_OR_SHORT_DECIMAL.get().format(threshold);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;

/**
* Enum for the version of the InfluxDB API.
Expand All @@ -32,8 +33,8 @@ public enum InfluxApiVersion {
V1 {
@Override
String writeEndpoint(final InfluxConfig config) {
String influxEndpoint = config.uri() + "/write?consistency=" + config.consistency().name().toLowerCase()
+ "&precision=ms&db=" + config.db();
String influxEndpoint = config.uri() + "/write?consistency="
+ config.consistency().name().toLowerCase(Locale.ROOT) + "&precision=ms&db=" + config.db();
if (StringUtils.isNotBlank(config.retentionPolicy())) {
influxEndpoint += "&rp=" + config.retentionPolicy();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
Expand Down Expand Up @@ -175,14 +176,14 @@ Stream<String> writeMeter(Meter m) {
String fieldKey = measurement.getStatistic()
.getTagValueRepresentation()
.replaceAll("(.)(\\p{Upper})", "$1_$2")
.toLowerCase();
.toLowerCase(Locale.ROOT);
fields.add(new Field(fieldKey, value));
}
if (fields.isEmpty()) {
return Stream.empty();
}
Meter.Id id = m.getId();
return Stream.of(influxLineProtocol(id, id.getType().name().toLowerCase(), fields.stream()));
return Stream.of(influxLineProtocol(id, id.getType().name().toLowerCase(Locale.ROOT), fields.stream()));
}

private Stream<String> writeLongTaskTimer(LongTaskTimer timer) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -386,7 +387,7 @@ private void publishSimpleStat(InfluxConfig config) {
InfluxMeterRegistry registry = new InfluxMeterRegistry(config, new MockClock());

Counter.builder("my.counter")
.baseUnit(TimeUnit.MICROSECONDS.name().toLowerCase())
.baseUnit(TimeUnit.MICROSECONDS.name().toLowerCase(Locale.ROOT))
.description("metric description")
.register(registry)
.increment(Math.PI);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -93,7 +94,7 @@ public Map<String, Object> writeLongTaskTimer(LongTaskTimer timer) {
Map<String, Object> attributes = new HashMap<>();
addAttribute(ACTIVE_TASKS, timer.activeTasks(), attributes);
addAttribute(DURATION, timer.duration(timer.baseTimeUnit()), attributes);
addAttribute(TIME_UNIT, timer.baseTimeUnit().name().toLowerCase(), attributes);
addAttribute(TIME_UNIT, timer.baseTimeUnit().name().toLowerCase(Locale.ROOT), attributes);
// process meter's name, type and tags
addMeterAsAttributes(timer.getId(), attributes);
return attributes;
Expand Down Expand Up @@ -141,7 +142,7 @@ public Map<String, Object> writeTimeGauge(TimeGauge gauge) {
}
Map<String, Object> attributes = new HashMap<>();
addAttribute(VALUE, value, attributes);
addAttribute(TIME_UNIT, gauge.baseTimeUnit().name().toLowerCase(), attributes);
addAttribute(TIME_UNIT, gauge.baseTimeUnit().name().toLowerCase(Locale.ROOT), attributes);
// process meter's name, type and tags
addMeterAsAttributes(gauge.getId(), attributes);
return attributes;
Expand All @@ -167,7 +168,7 @@ public Map<String, Object> writeTimer(Timer timer) {
addAttribute(AVG, timer.mean(timeUnit), attributes);
addAttribute(TOTAL_TIME, timer.totalTime(timeUnit), attributes);
addAttribute(MAX, timer.max(timeUnit), attributes);
addAttribute(TIME_UNIT, timeUnit.name().toLowerCase(), attributes);
addAttribute(TIME_UNIT, timeUnit.name().toLowerCase(Locale.ROOT), attributes);
// process meter's name, type and tags
addMeterAsAttributes(timer.getId(), attributes);
return attributes;
Expand All @@ -180,7 +181,7 @@ public Map<String, Object> writeFunctionTimer(FunctionTimer timer) {
addAttribute(COUNT, timer.count(), attributes);
addAttribute(AVG, timer.mean(timeUnit), attributes);
addAttribute(TOTAL_TIME, timer.totalTime(timeUnit), attributes);
addAttribute(TIME_UNIT, timeUnit.name().toLowerCase(), attributes);
addAttribute(TIME_UNIT, timeUnit.name().toLowerCase(Locale.ROOT), attributes);
// process meter's name, type and tags
addMeterAsAttributes(timer.getId(), attributes);
return attributes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package io.micrometer.newrelic;

import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.util.DoubleFormat;
import io.micrometer.core.instrument.util.MeterPartition;
Expand All @@ -26,10 +27,7 @@

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -125,7 +123,7 @@ public Stream<String> writeLongTaskTimer(LongTaskTimer timer) {
TimeUnit timeUnit = timer.baseTimeUnit();
return Stream.of(event(timer.getId(), new Attribute(ACTIVE_TASKS, timer.activeTasks()),
new Attribute(DURATION, timer.duration(timeUnit)),
new Attribute(TIME_UNIT, timeUnit.name().toLowerCase())));
new Attribute(TIME_UNIT, timeUnit.name().toLowerCase(Locale.ROOT))));
}

@Override
Expand Down Expand Up @@ -156,7 +154,7 @@ public Stream<String> writeTimeGauge(TimeGauge gauge) {
double value = gauge.value();
if (Double.isFinite(value)) {
return Stream.of(event(gauge.getId(), new Attribute(VALUE, value),
new Attribute(TIME_UNIT, gauge.baseTimeUnit().name().toLowerCase())));
new Attribute(TIME_UNIT, gauge.baseTimeUnit().name().toLowerCase(Locale.ROOT))));
}
return Stream.empty();
}
Expand All @@ -171,17 +169,18 @@ public Stream<String> writeSummary(DistributionSummary summary) {
@Override
public Stream<String> writeTimer(Timer timer) {
TimeUnit timeUnit = timer.baseTimeUnit();
return Stream.of(event(timer.getId(), new Attribute(COUNT, timer.count()),
new Attribute(AVG, timer.mean(timeUnit)), new Attribute(TOTAL_TIME, timer.totalTime(timeUnit)),
new Attribute(MAX, timer.max(timeUnit)), new Attribute(TIME_UNIT, timeUnit.name().toLowerCase())));
return Stream
.of(event(timer.getId(), new Attribute(COUNT, timer.count()), new Attribute(AVG, timer.mean(timeUnit)),
new Attribute(TOTAL_TIME, timer.totalTime(timeUnit)), new Attribute(MAX, timer.max(timeUnit)),
new Attribute(TIME_UNIT, timeUnit.name().toLowerCase(Locale.ROOT))));
}

@Override
public Stream<String> writeFunctionTimer(FunctionTimer timer) {
TimeUnit timeUnit = timer.baseTimeUnit();
return Stream.of(event(timer.getId(), new Attribute(COUNT, timer.count()),
new Attribute(AVG, timer.mean(timeUnit)), new Attribute(TOTAL_TIME, timer.totalTime(timeUnit)),
new Attribute(TIME_UNIT, timeUnit.name().toLowerCase())));
new Attribute(TIME_UNIT, timeUnit.name().toLowerCase(Locale.ROOT))));
}

@Override
Expand Down
Loading

0 comments on commit ea93fd1

Please sign in to comment.