diff --git a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/BeanstalkResource.java b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/BeanstalkResource.java index 9f294d4fb..7441b7c81 100644 --- a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/BeanstalkResource.java +++ b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/BeanstalkResource.java @@ -12,6 +12,7 @@ import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.SERVICE_INSTANCE_ID; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.SERVICE_NAMESPACE; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_VERSION; +import static java.util.logging.Level.WARNING; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; @@ -22,7 +23,6 @@ import io.opentelemetry.semconv.SchemaUrls; import java.io.File; import java.io.IOException; -import java.util.logging.Level; import java.util.logging.Logger; /** @@ -65,7 +65,7 @@ static Resource buildResource(String configPath) { parser.nextToken(); if (!parser.isExpectedStartObjectToken()) { - logger.log(Level.WARNING, "Invalid Beanstalk config: ", configPath); + logger.log(WARNING, "Invalid Beanstalk config: ", configPath); return Resource.create(attrBuilders.build(), SchemaUrls.V1_25_0); } @@ -87,7 +87,7 @@ static Resource buildResource(String configPath) { } } } catch (IOException e) { - logger.log(Level.WARNING, "Could not parse Beanstalk config.", e); + logger.log(WARNING, "Could not parse Beanstalk config.", e); return Resource.empty(); } diff --git a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/DockerHelper.java b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/DockerHelper.java index 5b8aefeac..a52cf1c18 100644 --- a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/DockerHelper.java +++ b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/DockerHelper.java @@ -5,11 +5,12 @@ package io.opentelemetry.contrib.aws.resource; +import static java.util.logging.Level.WARNING; + import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; -import java.util.logging.Level; import java.util.logging.Logger; class DockerHelper { @@ -44,9 +45,9 @@ public String getContainerId() { } } } catch (FileNotFoundException e) { - logger.log(Level.WARNING, "Failed to read container id, cgroup file does not exist."); + logger.log(WARNING, "Failed to read container id, cgroup file does not exist."); } catch (IOException e) { - logger.log(Level.WARNING, "Unable to read container id: " + e.getMessage()); + logger.log(WARNING, "Unable to read container id: " + e.getMessage()); } return ""; diff --git a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/Ec2Resource.java b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/Ec2Resource.java index d4bdb4228..5aa930b1c 100644 --- a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/Ec2Resource.java +++ b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/Ec2Resource.java @@ -15,6 +15,7 @@ import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.HOST_IMAGE_ID; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.HOST_NAME; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.HOST_TYPE; +import static java.util.logging.Level.WARNING; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; @@ -28,7 +29,6 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; -import java.util.logging.Level; import java.util.logging.Logger; /** @@ -125,7 +125,7 @@ static Resource buildResource(String endpoint) { } } } catch (IOException e) { - logger.log(Level.WARNING, "Could not parse identity document, resource not filled.", e); + logger.log(WARNING, "Could not parse identity document, resource not filled.", e); return Resource.empty(); } diff --git a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EcsResource.java b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EcsResource.java index efb112de8..83440819b 100644 --- a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EcsResource.java +++ b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EcsResource.java @@ -26,6 +26,9 @@ import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.CONTAINER_NAME; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.CloudPlatformIncubatingValues.AWS_ECS; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.CloudProviderIncubatingValues.AWS; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static java.util.logging.Level.WARNING; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; @@ -35,11 +38,9 @@ import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.SchemaUrls; import java.io.IOException; -import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.Optional; -import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -88,7 +89,7 @@ static Resource buildResource(Map sysEnv, SimpleHttpClient httpC static void fetchMetadata( SimpleHttpClient httpClient, String url, AttributesBuilder attrBuilders) { - String json = httpClient.fetchString("GET", url, Collections.emptyMap(), null); + String json = httpClient.fetchString("GET", url, emptyMap(), null); if (json.isEmpty()) { return; } @@ -103,17 +104,17 @@ static void fetchMetadata( .getLogGroupArn() .ifPresent( logGroupArn -> { - attrBuilders.put(AWS_LOG_GROUP_ARNS, Collections.singletonList(logGroupArn)); + attrBuilders.put(AWS_LOG_GROUP_ARNS, singletonList(logGroupArn)); }); logArnBuilder .getLogStreamArn() .ifPresent( logStreamArn -> { - attrBuilders.put(AWS_LOG_STREAM_ARNS, Collections.singletonList(logStreamArn)); + attrBuilders.put(AWS_LOG_STREAM_ARNS, singletonList(logStreamArn)); }); } catch (IOException e) { - logger.log(Level.WARNING, "Can't get ECS metadata", e); + logger.log(WARNING, "Can't get ECS metadata", e); } } @@ -156,7 +157,7 @@ static void parseResponse( JsonParser parser, AttributesBuilder attrBuilders, LogArnBuilder logArnBuilder) throws IOException { if (!parser.isExpectedStartObjectToken()) { - logger.log(Level.WARNING, "Couldn't parse ECS metadata, invalid JSON"); + logger.log(WARNING, "Couldn't parse ECS metadata, invalid JSON"); return; } @@ -339,7 +340,7 @@ static DockerImage parse(@Nullable String image) { } Matcher matcher = imagePattern.matcher(image); if (!matcher.matches()) { - logger.log(Level.WARNING, "Couldn't parse image '" + image + "'"); + logger.log(WARNING, "Couldn't parse image '" + image + "'"); return null; } String repository = matcher.group("repository"); diff --git a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EksResource.java b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EksResource.java index 8ed3fb512..156755446 100644 --- a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EksResource.java +++ b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/EksResource.java @@ -11,6 +11,8 @@ import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.CloudPlatformIncubatingValues.AWS_EKS; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.CloudProviderIncubatingValues.AWS; import static io.opentelemetry.contrib.aws.resource.IncubatingAttributes.K8S_CLUSTER_NAME; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.WARNING; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; @@ -26,7 +28,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import java.util.logging.Level; import java.util.logging.Logger; /** @@ -91,7 +92,7 @@ static Resource buildResource( private static boolean isEks( String k8sTokenPath, String k8sKeystorePath, SimpleHttpClient httpClient) { if (!isK8s(k8sTokenPath, k8sKeystorePath)) { - logger.log(Level.FINE, "Not running on k8s."); + logger.log(FINE, "Not running on k8s."); return false; } @@ -145,7 +146,7 @@ private static String getClusterName(SimpleHttpClient httpClient) { } } } catch (IOException e) { - logger.log(Level.WARNING, "Can't get cluster name on EKS.", e); + logger.log(WARNING, "Can't get cluster name on EKS.", e); } return ""; } @@ -156,7 +157,7 @@ private static String getK8sCredHeader() { new String(Files.readAllBytes(Paths.get(K8S_TOKEN_PATH)), StandardCharsets.UTF_8); return "Bearer " + content; } catch (IOException e) { - logger.log(Level.WARNING, "Unable to load K8s client token.", e); + logger.log(WARNING, "Unable to load K8s client token.", e); } return ""; } diff --git a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/SimpleHttpClient.java b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/SimpleHttpClient.java index 12bc6e34e..f78719d99 100644 --- a/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/SimpleHttpClient.java +++ b/aws-resources/src/main/java/io/opentelemetry/contrib/aws/resource/SimpleHttpClient.java @@ -5,6 +5,9 @@ package io.opentelemetry.contrib.aws.resource; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.WARNING; + import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; @@ -13,7 +16,6 @@ import java.time.Duration; import java.util.Collection; import java.util.Map; -import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.net.ssl.SSLContext; @@ -72,7 +74,7 @@ public String fetchString( int responseCode = response.code(); if (responseCode != 200) { logger.log( - Level.FINE, + FINE, "Error response from " + urlStr + " code (" @@ -84,7 +86,7 @@ public String fetchString( ResponseBody body = response.body(); return body != null ? body.string() : ""; } catch (IOException e) { - logger.log(Level.FINE, "SimpleHttpClient fetch string failed.", e); + logger.log(FINE, "SimpleHttpClient fetch string failed.", e); } return ""; @@ -101,7 +103,7 @@ private static X509TrustManager buildTrustManager(@Nullable KeyStore keyStore) { tmf.init(keyStore); return (X509TrustManager) tmf.getTrustManagers()[0]; } catch (Exception e) { - logger.log(Level.WARNING, "Build SslSocketFactory for K8s restful client exception.", e); + logger.log(WARNING, "Build SslSocketFactory for K8s restful client exception.", e); return null; } } @@ -117,7 +119,7 @@ private static SSLSocketFactory buildSslSocketFactory(@Nullable TrustManager tru return context.getSocketFactory(); } catch (Exception e) { - logger.log(Level.WARNING, "Build SslSocketFactory for K8s restful client exception.", e); + logger.log(WARNING, "Build SslSocketFactory for K8s restful client exception.", e); } return null; } @@ -138,7 +140,7 @@ private static KeyStore getKeystoreForTrustedCert(String certPath) { } return trustStore; } catch (Exception e) { - logger.log(Level.WARNING, "Cannot load KeyStore from " + certPath); + logger.log(WARNING, "Cannot load KeyStore from " + certPath); return null; } } diff --git a/aws-xray-propagator/src/main/java/io/opentelemetry/contrib/awsxray/propagator/AwsXrayLambdaPropagator.java b/aws-xray-propagator/src/main/java/io/opentelemetry/contrib/awsxray/propagator/AwsXrayLambdaPropagator.java index a6b6a2ab4..b34bc961c 100644 --- a/aws-xray-propagator/src/main/java/io/opentelemetry/contrib/awsxray/propagator/AwsXrayLambdaPropagator.java +++ b/aws-xray-propagator/src/main/java/io/opentelemetry/contrib/awsxray/propagator/AwsXrayLambdaPropagator.java @@ -5,12 +5,13 @@ package io.opentelemetry.contrib.awsxray.propagator; +import static java.util.Collections.singletonMap; + import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.context.propagation.TextMapSetter; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -75,7 +76,7 @@ public Context extract(Context context, @Nullable C carrier, TextMapGetter FIELDS = Collections.singletonList(TRACE_HEADER_KEY); + private static final List FIELDS = singletonList(TRACE_HEADER_KEY); private static final AwsXrayPropagator INSTANCE = new AwsXrayPropagator(); diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsAttributeKeys.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsAttributeKeys.java index 101641f08..c9e762d63 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsAttributeKeys.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsAttributeKeys.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.awsxray; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + import io.opentelemetry.api.common.AttributeKey; /** Utility class holding attribute keys with special meaning to AWS components */ @@ -12,28 +14,25 @@ final class AwsAttributeKeys { private AwsAttributeKeys() {} - static final AttributeKey AWS_SPAN_KIND = AttributeKey.stringKey("aws.span.kind"); + static final AttributeKey AWS_SPAN_KIND = stringKey("aws.span.kind"); - static final AttributeKey AWS_LOCAL_SERVICE = AttributeKey.stringKey("aws.local.service"); + static final AttributeKey AWS_LOCAL_SERVICE = stringKey("aws.local.service"); - static final AttributeKey AWS_LOCAL_OPERATION = - AttributeKey.stringKey("aws.local.operation"); + static final AttributeKey AWS_LOCAL_OPERATION = stringKey("aws.local.operation"); - static final AttributeKey AWS_REMOTE_SERVICE = - AttributeKey.stringKey("aws.remote.service"); + static final AttributeKey AWS_REMOTE_SERVICE = stringKey("aws.remote.service"); - static final AttributeKey AWS_REMOTE_OPERATION = - AttributeKey.stringKey("aws.remote.operation"); + static final AttributeKey AWS_REMOTE_OPERATION = stringKey("aws.remote.operation"); - static final AttributeKey AWS_REMOTE_TARGET = AttributeKey.stringKey("aws.remote.target"); + static final AttributeKey AWS_REMOTE_TARGET = stringKey("aws.remote.target"); // use the same AWS Resource attribute name defined by OTel java auto-instr for aws_sdk_v_1_1 // TODO: all AWS specific attributes should be defined in semconv package and reused cross all // otel packages. Related sim - // https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/8710 - static final AttributeKey AWS_BUCKET_NAME = AttributeKey.stringKey("aws.bucket.name"); - static final AttributeKey AWS_QUEUE_NAME = AttributeKey.stringKey("aws.queue.name"); - static final AttributeKey AWS_STREAM_NAME = AttributeKey.stringKey("aws.stream.name"); - static final AttributeKey AWS_TABLE_NAME = AttributeKey.stringKey("aws.table.name"); + static final AttributeKey AWS_BUCKET_NAME = stringKey("aws.bucket.name"); + static final AttributeKey AWS_QUEUE_NAME = stringKey("aws.queue.name"); + static final AttributeKey AWS_STREAM_NAME = stringKey("aws.stream.name"); + static final AttributeKey AWS_TABLE_NAME = stringKey("aws.table.name"); } diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsMetricAttributeGenerator.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsMetricAttributeGenerator.java index 42275b4b1..3fed3b3f3 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsMetricAttributeGenerator.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsMetricAttributeGenerator.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.awsxray; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.contrib.awsxray.AwsAttributeKeys.AWS_BUCKET_NAME; import static io.opentelemetry.contrib.awsxray.AwsAttributeKeys.AWS_LOCAL_OPERATION; import static io.opentelemetry.contrib.awsxray.AwsAttributeKeys.AWS_LOCAL_SERVICE; @@ -16,6 +18,7 @@ import static io.opentelemetry.contrib.awsxray.AwsAttributeKeys.AWS_STREAM_NAME; import static io.opentelemetry.contrib.awsxray.AwsAttributeKeys.AWS_TABLE_NAME; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_NAME; +import static java.util.logging.Level.FINEST; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; @@ -27,7 +30,6 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Optional; -import java.util.logging.Level; import java.util.logging.Logger; /** @@ -54,36 +56,31 @@ final class AwsMetricAttributeGenerator implements MetricAttributeGenerator { private static final String UNKNOWN_REMOTE_OPERATION = "UnknownRemoteOperation"; // copied from DbIncubatingAttributes - private static final AttributeKey DB_OPERATION = AttributeKey.stringKey("db.operation"); - private static final AttributeKey DB_SYSTEM = AttributeKey.stringKey("db.system"); + private static final AttributeKey DB_OPERATION = stringKey("db.operation"); + private static final AttributeKey DB_SYSTEM = stringKey("db.system"); // copied from FaasIncubatingAttributes - private static final AttributeKey FAAS_INVOKED_NAME = - AttributeKey.stringKey("faas.invoked_name"); - private static final AttributeKey FAAS_TRIGGER = AttributeKey.stringKey("faas.trigger"); + private static final AttributeKey FAAS_INVOKED_NAME = stringKey("faas.invoked_name"); + private static final AttributeKey FAAS_TRIGGER = stringKey("faas.trigger"); // copied from GraphqlIncubatingAttributes private static final AttributeKey GRAPHQL_OPERATION_TYPE = - AttributeKey.stringKey("graphql.operation.type"); + stringKey("graphql.operation.type"); // copied from HttpIncubatingAttributes - private static final AttributeKey HTTP_METHOD = AttributeKey.stringKey("http.method"); - private static final AttributeKey HTTP_TARGET = AttributeKey.stringKey("http.target"); - private static final AttributeKey HTTP_URL = AttributeKey.stringKey("http.url"); + private static final AttributeKey HTTP_METHOD = stringKey("http.method"); + private static final AttributeKey HTTP_TARGET = stringKey("http.target"); + private static final AttributeKey HTTP_URL = stringKey("http.url"); // copied from MessagingIncubatingAttributes - private static final AttributeKey MESSAGING_OPERATION = - AttributeKey.stringKey("messaging.operation"); - private static final AttributeKey MESSAGING_SYSTEM = - AttributeKey.stringKey("messaging.system"); + private static final AttributeKey MESSAGING_OPERATION = stringKey("messaging.operation"); + private static final AttributeKey MESSAGING_SYSTEM = stringKey("messaging.system"); // copied from NetIncubatingAttributes - private static final AttributeKey NET_PEER_NAME = AttributeKey.stringKey("net.peer.name"); - private static final AttributeKey NET_PEER_PORT = AttributeKey.longKey("net.peer.port"); - private static final AttributeKey NET_SOCK_PEER_ADDR = - AttributeKey.stringKey("net.sock.peer.addr"); - private static final AttributeKey NET_SOCK_PEER_PORT = - AttributeKey.longKey("net.sock.peer.port"); + private static final AttributeKey NET_PEER_NAME = stringKey("net.peer.name"); + private static final AttributeKey NET_PEER_PORT = longKey("net.peer.port"); + private static final AttributeKey NET_SOCK_PEER_ADDR = stringKey("net.sock.peer.addr"); + private static final AttributeKey NET_SOCK_PEER_PORT = longKey("net.sock.peer.port"); // copied from PeerIncubatingAttributes - private static final AttributeKey PEER_SERVICE = AttributeKey.stringKey("peer.service"); + private static final AttributeKey PEER_SERVICE = stringKey("peer.service"); // copied from RpcIncubatingAttributes - private static final AttributeKey RPC_METHOD = AttributeKey.stringKey("rpc.method"); - private static final AttributeKey RPC_SERVICE = AttributeKey.stringKey("rpc.service"); + private static final AttributeKey RPC_METHOD = stringKey("rpc.method"); + private static final AttributeKey RPC_SERVICE = stringKey("rpc.service"); @Override public Attributes generateMetricAttributesFromSpan(SpanData span, Resource resource) { @@ -307,7 +304,7 @@ private static String generateRemoteOperation(SpanData span) { remoteOperation = extractApiPathValue(url.getPath()); } } catch (MalformedURLException e) { - logger.log(Level.FINEST, "invalid http.url attribute: ", httpUrl); + logger.log(FINEST, "invalid http.url attribute: ", httpUrl); } } if (isKeyPresent(span, HTTP_METHOD)) { @@ -387,6 +384,6 @@ private static void logUnknownAttribute(AttributeKey attributeKey, SpanD String[] params = { attributeKey.getKey(), span.getKind().name(), span.getSpanContext().getSpanId() }; - logger.log(Level.FINEST, "No valid {0} value found for {1} span {2}", params); + logger.log(FINEST, "No valid {0} value found for {1} span {2}", params); } } diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsSpanMetricsProcessor.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsSpanMetricsProcessor.java index 244138a47..9a3e60519 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsSpanMetricsProcessor.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsSpanMetricsProcessor.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.awsxray; +import static io.opentelemetry.api.common.AttributeKey.longKey; + import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.DoubleHistogram; @@ -40,8 +42,7 @@ @Immutable public final class AwsSpanMetricsProcessor implements SpanProcessor { - private static final AttributeKey HTTP_STATUS_CODE = - AttributeKey.longKey("http.status_code"); + private static final AttributeKey HTTP_STATUS_CODE = longKey("http.status_code"); private static final double NANOS_TO_MILLIS = 1_000_000.0; diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSampler.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSampler.java index ad9b72a2c..9c997f042 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSampler.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSampler.java @@ -5,6 +5,14 @@ package io.opentelemetry.contrib.awsxray; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static java.util.function.Function.identity; +import static java.util.logging.Level.FINE; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toSet; + import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.context.Context; @@ -29,17 +37,13 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import java.util.logging.Level; import java.util.logging.Logger; -import java.util.stream.Collectors; import javax.annotation.Nullable; /** Remote sampler that gets sampling configuration from AWS X-Ray. */ public final class AwsXrayRemoteSampler implements Sampler, Closeable { - static final long DEFAULT_TARGET_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(10); + static final long DEFAULT_TARGET_INTERVAL_NANOS = SECONDS.toNanos(10); private static final Logger logger = Logger.getLogger(AwsXrayRemoteSampler.class.getName()); @@ -134,7 +138,7 @@ private void getAndUpdateSampler() { initialSampler, response.getSamplingRules().stream() .map(SamplingRuleRecord::getRule) - .collect(Collectors.toList()))); + .collect(toList()))); previousRulesResponse = response; ScheduledFuture existingFetchTargetsFuture = fetchTargetsFuture; @@ -142,18 +146,17 @@ private void getAndUpdateSampler() { existingFetchTargetsFuture.cancel(false); } fetchTargetsFuture = - executor.schedule( - this::fetchTargets, DEFAULT_TARGET_INTERVAL_NANOS, TimeUnit.NANOSECONDS); + executor.schedule(this::fetchTargets, DEFAULT_TARGET_INTERVAL_NANOS, NANOSECONDS); } } catch (Throwable t) { - logger.log(Level.FINE, "Failed to update sampler", t); + logger.log(FINE, "Failed to update sampler", t); } scheduleSamplerUpdate(); } private void scheduleSamplerUpdate() { long delay = pollingIntervalNanos + jitterNanos.next(); - pollFuture = executor.schedule(this::getAndUpdateSampler, delay, TimeUnit.NANOSECONDS); + pollFuture = executor.schedule(this::getAndUpdateSampler, delay, NANOSECONDS); } /** @@ -168,7 +171,7 @@ Duration getNextSamplerUpdateScheduledDuration() { if (pollFuture == null) { return null; } - return Duration.ofNanos(pollFuture.getDelay(TimeUnit.NANOSECONDS)); + return Duration.ofNanos(pollFuture.getDelay(NANOSECONDS)); } private void fetchTargets() { @@ -181,28 +184,25 @@ private void fetchTargets() { Date now = Date.from(Instant.ofEpochSecond(0, clock.now())); List statistics = xrayRulesSampler.snapshot(now); Set requestedTargetRuleNames = - statistics.stream() - .map(SamplingStatisticsDocument::getRuleName) - .collect(Collectors.toSet()); + statistics.stream().map(SamplingStatisticsDocument::getRuleName).collect(toSet()); GetSamplingTargetsResponse response = client.getSamplingTargets(GetSamplingTargetsRequest.create(statistics)); Map targets = response.getDocuments().stream() - .collect(Collectors.toMap(SamplingTargetDocument::getRuleName, Function.identity())); + .collect(toMap(SamplingTargetDocument::getRuleName, identity())); updateInternalSamplers(xrayRulesSampler.withTargets(targets, requestedTargetRuleNames, now)); } catch (Throwable t) { // Might be a transient API failure, try again after a default interval. fetchTargetsFuture = - executor.schedule( - this::fetchTargets, DEFAULT_TARGET_INTERVAL_NANOS, TimeUnit.NANOSECONDS); + executor.schedule(this::fetchTargets, DEFAULT_TARGET_INTERVAL_NANOS, NANOSECONDS); return; } long nextTargetFetchIntervalNanos = xrayRulesSampler.nextTargetFetchTimeNanos() - clock.nanoTime(); fetchTargetsFuture = - executor.schedule(this::fetchTargets, nextTargetFetchIntervalNanos, TimeUnit.NANOSECONDS); + executor.schedule(this::fetchTargets, nextTargetFetchIntervalNanos, NANOSECONDS); } @Override diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSamplerBuilder.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSamplerBuilder.java index 1ce0d41c1..25485e4b0 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSamplerBuilder.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/AwsXrayRemoteSamplerBuilder.java @@ -6,6 +6,8 @@ package io.opentelemetry.contrib.awsxray; import static java.util.Objects.requireNonNull; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.opentelemetry.sdk.common.Clock; @@ -26,7 +28,7 @@ public final class AwsXrayRemoteSamplerBuilder { private Clock clock = Clock.getDefault(); private String endpoint = DEFAULT_ENDPOINT; @Nullable private Sampler initialSampler; - private long pollingIntervalNanos = TimeUnit.SECONDS.toNanos(DEFAULT_POLLING_INTERVAL_SECS); + private long pollingIntervalNanos = SECONDS.toNanos(DEFAULT_POLLING_INTERVAL_SECS); AwsXrayRemoteSamplerBuilder(Resource resource) { this.resource = resource; @@ -51,7 +53,7 @@ public AwsXrayRemoteSamplerBuilder setEndpoint(String endpoint) { @CanIgnoreReturnValue public AwsXrayRemoteSamplerBuilder setPollingInterval(Duration delay) { requireNonNull(delay, "delay"); - return setPollingInterval(delay.toNanos(), TimeUnit.NANOSECONDS); + return setPollingInterval(delay.toNanos(), NANOSECONDS); } /** diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/SamplingRuleApplier.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/SamplingRuleApplier.java index 1d97c4aed..ae4cac018 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/SamplingRuleApplier.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/SamplingRuleApplier.java @@ -5,7 +5,10 @@ package io.opentelemetry.contrib.awsxray; +import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_NAME; +import static java.util.concurrent.TimeUnit.SECONDS; +import static java.util.stream.Collectors.toMap; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; @@ -28,22 +31,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; import java.util.regex.Pattern; -import java.util.stream.Collectors; import javax.annotation.Nullable; final class SamplingRuleApplier { // copied from AwsIncubatingAttributes private static final AttributeKey AWS_ECS_CONTAINER_ARN = - AttributeKey.stringKey("aws.ecs.container.arn"); + stringKey("aws.ecs.container.arn"); // copied from CloudIncubatingAttributes - private static final AttributeKey CLOUD_PLATFORM = - AttributeKey.stringKey("cloud.platform"); - private static final AttributeKey CLOUD_RESOURCE_ID = - AttributeKey.stringKey("cloud.resource_id"); + private static final AttributeKey CLOUD_PLATFORM = stringKey("cloud.platform"); + private static final AttributeKey CLOUD_RESOURCE_ID = stringKey("cloud.resource_id"); // copied from CloudIncubatingAttributes.CloudPlatformIncubatingValues public static final String AWS_EC2 = "aws_ec2"; public static final String AWS_ECS = "aws_ecs"; @@ -51,12 +50,12 @@ final class SamplingRuleApplier { public static final String AWS_LAMBDA = "aws_lambda"; public static final String AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; // copied from HttpIncubatingAttributes - private static final AttributeKey HTTP_HOST = AttributeKey.stringKey("http.host"); - private static final AttributeKey HTTP_METHOD = AttributeKey.stringKey("http.method"); - private static final AttributeKey HTTP_TARGET = AttributeKey.stringKey("http.target"); - private static final AttributeKey HTTP_URL = AttributeKey.stringKey("http.url"); + private static final AttributeKey HTTP_HOST = stringKey("http.host"); + private static final AttributeKey HTTP_METHOD = stringKey("http.method"); + private static final AttributeKey HTTP_TARGET = stringKey("http.target"); + private static final AttributeKey HTTP_URL = stringKey("http.url"); // copied from NetIncubatingAttributes - private static final AttributeKey NET_HOST_NAME = AttributeKey.stringKey("net.host.name"); + private static final AttributeKey NET_HOST_NAME = stringKey("net.host.name"); private static final Map XRAY_CLOUD_PLATFORM; @@ -131,7 +130,7 @@ final class SamplingRuleApplier { } else { attributeMatchers = rule.getAttributes().entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> toMatcher(e.getValue()))); + .collect(toMap(Map.Entry::getKey, e -> toMatcher(e.getValue()))); } urlPathMatcher = toMatcher(rule.getUrlPath()); @@ -317,7 +316,7 @@ SamplingRuleApplier withTarget(SamplingTargetDocument target, Date now) { } long intervalNanos = target.getIntervalSecs() != null - ? TimeUnit.SECONDS.toNanos(target.getIntervalSecs()) + ? SECONDS.toNanos(target.getIntervalSecs()) : AwsXrayRemoteSampler.DEFAULT_TARGET_INTERVAL_NANOS; long newNextSnapshotTimeNanos = clock.nanoTime() + intervalNanos; diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XrayRulesSampler.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XrayRulesSampler.java index 75977dc0f..e187da972 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XrayRulesSampler.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XrayRulesSampler.java @@ -5,6 +5,9 @@ package io.opentelemetry.contrib.awsxray; +import static java.util.logging.Level.FINE; +import static java.util.stream.Collectors.toList; + import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.context.Context; @@ -21,9 +24,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.logging.Level; import java.util.logging.Logger; -import java.util.stream.Collectors; final class XrayRulesSampler implements Sampler { @@ -84,7 +85,7 @@ public SamplingResult shouldSample( // In practice, X-Ray always returns a Default rule that matches all requests so it is a bug in // our code or X-Ray to reach here, fallback just in case. logger.log( - Level.FINE, + FINE, "No sampling rule matched the request. " + "This is a bug in either the OpenTelemetry SDK or X-Ray."); return fallbackSampler.shouldSample( @@ -100,7 +101,7 @@ List snapshot(Date now) { return Arrays.stream(ruleAppliers) .map(rule -> rule.snapshot(now)) .filter(Objects::nonNull) - .collect(Collectors.toList()); + .collect(toList()); } long nextTargetFetchTimeNanos() { diff --git a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XraySamplerClient.java b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XraySamplerClient.java index 5dbbbbbbf..1c7958889 100644 --- a/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XraySamplerClient.java +++ b/aws-xray/src/main/java/io/opentelemetry/contrib/awsxray/XraySamplerClient.java @@ -25,6 +25,8 @@ package io.opentelemetry.contrib.awsxray; +import static java.util.logging.Level.FINE; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; @@ -37,7 +39,6 @@ import java.io.UncheckedIOException; import java.math.BigDecimal; import java.util.Date; -import java.util.logging.Level; import java.util.logging.Logger; import okhttp3.Call; import okhttp3.MediaType; @@ -114,7 +115,7 @@ private T executeJsonRequest(String endpoint, Object request, Class respo private static String readResponse(Response response, String endpoint) throws IOException { if (!response.isSuccessful()) { logger.log( - Level.FINE, + FINE, "Error response from " + endpoint + " code (" diff --git a/azure-resources/build.gradle.kts b/azure-resources/build.gradle.kts index c17d14787..43a154970 100644 --- a/azure-resources/build.gradle.kts +++ b/azure-resources/build.gradle.kts @@ -5,8 +5,8 @@ plugins { id("maven-publish") } -description = "OpenTelemetry GCP Resources Support" -otelJava.moduleName.set("io.opentelemetry.contrib.gcp.resource") +description = "OpenTelemetry Azure Resources Support" +otelJava.moduleName.set("io.opentelemetry.contrib.azure.resource") // enable publishing to maven local java { diff --git a/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProvider.java b/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProvider.java index 74ad96334..485ef7b01 100644 --- a/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProvider.java +++ b/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProvider.java @@ -12,6 +12,7 @@ import static io.opentelemetry.contrib.azure.resource.IncubatingAttributes.HOST_ID; import static io.opentelemetry.contrib.azure.resource.IncubatingAttributes.SERVICE_INSTANCE_ID; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_NAME; +import static java.util.Objects.requireNonNull; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; @@ -20,7 +21,6 @@ import io.opentelemetry.sdk.resources.Resource; import java.util.HashMap; import java.util.Map; -import java.util.Objects; import javax.annotation.Nullable; public class AzureAppServiceResourceProvider extends CloudResourceProvider { @@ -68,7 +68,7 @@ public Attributes getAttributes() { if (detect != AzureEnvVarPlatform.APP_SERVICE) { return Attributes.empty(); } - String name = Objects.requireNonNull(env.get(WEBSITE_SITE_NAME)); + String name = requireNonNull(env.get(WEBSITE_SITE_NAME)); AttributesBuilder builder = AzureVmResourceProvider.azureAttributeBuilder(AZURE_APP_SERVICE); builder.put(SERVICE_NAME, name); diff --git a/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureMetadataService.java b/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureMetadataService.java index d5bf44520..ced58f0d2 100644 --- a/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureMetadataService.java +++ b/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureMetadataService.java @@ -5,12 +5,13 @@ package io.opentelemetry.contrib.azure.resource; +import static java.util.Objects.requireNonNull; + import com.fasterxml.jackson.core.JsonFactory; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; -import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; import java.util.logging.Level; @@ -22,6 +23,8 @@ public class AzureMetadataService { static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final URL METADATA_URL; + private static final Duration TIMEOUT = Duration.ofSeconds(5); + private static final Logger logger = Logger.getLogger(AzureMetadataService.class.getName()); static { try { @@ -31,12 +34,6 @@ public class AzureMetadataService { } } - private AzureMetadataService() {} - - private static final Duration TIMEOUT = Duration.ofSeconds(5); - - private static final Logger logger = Logger.getLogger(AzureMetadataService.class.getName()); - static Supplier> defaultClient() { return () -> fetchMetadata(METADATA_URL); } @@ -66,10 +63,12 @@ static Optional fetchMetadata(URL url) { return Optional.empty(); } - return Optional.of(Objects.requireNonNull(response.body()).string()); + return Optional.of(requireNonNull(response.body()).string()); } catch (IOException e) { logger.log(Level.FINE, "Failed to fetch Azure VM metadata", e); return Optional.empty(); } } + + private AzureMetadataService() {} } diff --git a/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureVmResourceProvider.java b/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureVmResourceProvider.java index 38c983b4a..f36590622 100644 --- a/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureVmResourceProvider.java +++ b/azure-resources/src/main/java/io/opentelemetry/contrib/azure/resource/AzureVmResourceProvider.java @@ -36,20 +36,6 @@ public class AzureVmResourceProvider extends CloudResourceProvider { - static class Entry { - final AttributeKey key; - final Function transform; - - Entry(AttributeKey key) { - this(key, Function.identity()); - } - - Entry(AttributeKey key, Function transform) { - this.key = key; - this.transform = transform; - } - } - private static final Map COMPUTE_MAPPING = new HashMap<>(); static { @@ -161,4 +147,18 @@ private static void consumeJson(JsonParser parser, BiConsumer co consumer.accept(parser.currentName(), parser.nextTextValue()); } } + + static class Entry { + final AttributeKey key; + final Function transform; + + Entry(AttributeKey key) { + this(key, Function.identity()); + } + + Entry(AttributeKey key, Function transform) { + this.key = key; + this.transform = transform; + } + } } diff --git a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProviderTest.java b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProviderTest.java index 20d856cba..75360f0e9 100644 --- a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProviderTest.java +++ b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureAppServiceResourceProviderTest.java @@ -5,6 +5,7 @@ package io.opentelemetry.contrib.azure.resource; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_NAME; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PLATFORM; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PROVIDER; @@ -16,7 +17,6 @@ import com.google.common.collect.ImmutableMap; import io.opentelemetry.sdk.testing.assertj.AttributesAssert; -import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.NotNull; @@ -98,7 +98,7 @@ void isFunction() { @NotNull private static AttributesAssert createResource(Map map) { - return OpenTelemetryAssertions.assertThat( + return assertThat( new AzureAppServiceResourceProvider(map).createResource(null).getAttributes()); } } diff --git a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureContainersResourceProviderTest.java b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureContainersResourceProviderTest.java index 5ac1a4be7..082ceaf6a 100644 --- a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureContainersResourceProviderTest.java +++ b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureContainersResourceProviderTest.java @@ -5,6 +5,7 @@ package io.opentelemetry.contrib.azure.resource; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_NAME; import static io.opentelemetry.semconv.ServiceAttributes.SERVICE_VERSION; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PLATFORM; @@ -13,7 +14,6 @@ import com.google.common.collect.ImmutableMap; import io.opentelemetry.sdk.testing.assertj.AttributesAssert; -import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.NotNull; @@ -50,7 +50,7 @@ void isNotContainer() { @NotNull private static AttributesAssert createResource(Map map) { - return OpenTelemetryAssertions.assertThat( + return assertThat( new AzureContainersResourceProvider(map).createResource(null).getAttributes()); } } diff --git a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureFunctionsResourceProviderTest.java b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureFunctionsResourceProviderTest.java index 520e44543..e2c39cc7a 100644 --- a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureFunctionsResourceProviderTest.java +++ b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/AzureFunctionsResourceProviderTest.java @@ -5,6 +5,7 @@ package io.opentelemetry.contrib.azure.resource; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PLATFORM; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PROVIDER; import static io.opentelemetry.semconv.incubating.FaasIncubatingAttributes.FAAS_INSTANCE; @@ -14,7 +15,6 @@ import com.google.common.collect.ImmutableMap; import io.opentelemetry.sdk.testing.assertj.AttributesAssert; -import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.NotNull; @@ -55,7 +55,6 @@ void isNotFunction() { @NotNull private static AttributesAssert createResource(Map map) { - return OpenTelemetryAssertions.assertThat( - new AzureFunctionsResourceProvider(map).createResource(null).getAttributes()); + return assertThat(new AzureFunctionsResourceProvider(map).createResource(null).getAttributes()); } } diff --git a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/MetadataBasedResourceProviderTest.java b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/MetadataBasedResourceProviderTest.java index d827e8fd4..25d9e065c 100644 --- a/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/MetadataBasedResourceProviderTest.java +++ b/azure-resources/src/test/java/io/opentelemetry/contrib/azure/resource/MetadataBasedResourceProviderTest.java @@ -5,6 +5,7 @@ package io.opentelemetry.contrib.azure.resource; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PLATFORM; import static io.opentelemetry.semconv.incubating.CloudIncubatingAttributes.CLOUD_PROVIDER; @@ -16,7 +17,6 @@ import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.assertj.AttributesAssert; -import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; @@ -47,7 +47,7 @@ private AttributesAssert mockServerResponse() { @NotNull private AttributesAssert createResource(Supplier> client) { Resource resource = getResourceProvider(client).createResource(null); - return OpenTelemetryAssertions.assertThat(resource.getAttributes()); + return assertThat(resource.getAttributes()); } @NotNull diff --git a/baggage-processor/src/main/java/io/opentelemetry/contrib/baggage/processor/BaggageLogRecordProcessor.java b/baggage-processor/src/main/java/io/opentelemetry/contrib/baggage/processor/BaggageLogRecordProcessor.java index 4e8c91505..b3701bf52 100644 --- a/baggage-processor/src/main/java/io/opentelemetry/contrib/baggage/processor/BaggageLogRecordProcessor.java +++ b/baggage-processor/src/main/java/io/opentelemetry/contrib/baggage/processor/BaggageLogRecordProcessor.java @@ -18,14 +18,6 @@ */ public class BaggageLogRecordProcessor implements LogRecordProcessor { - /** - * Creates a new {@link BaggageLogRecordProcessor} that copies all baggage entries into the newly - * created log record. - */ - public static BaggageLogRecordProcessor allowAllBaggageKeys() { - return new BaggageLogRecordProcessor(baggageKey -> true); - } - private final Predicate baggageKeyPredicate; /** @@ -36,6 +28,14 @@ public BaggageLogRecordProcessor(Predicate baggageKeyPredicate) { this.baggageKeyPredicate = baggageKeyPredicate; } + /** + * Creates a new {@link BaggageLogRecordProcessor} that copies all baggage entries into the newly + * created log record. + */ + public static BaggageLogRecordProcessor allowAllBaggageKeys() { + return new BaggageLogRecordProcessor(baggageKey -> true); + } + @Override public void onEmit(Context context, ReadWriteLogRecord logRecord) { Baggage.fromContext(context) diff --git a/cloudfoundry-resources/src/main/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResource.java b/cloudfoundry-resources/src/main/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResource.java index 7d6313928..c8e7bd2f2 100644 --- a/cloudfoundry-resources/src/main/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResource.java +++ b/cloudfoundry-resources/src/main/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResource.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.cloudfoundry.resources; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; @@ -22,24 +24,22 @@ public final class CloudFoundryResource { private static final String ENV_VCAP_APPLICATION = "VCAP_APPLICATION"; // copied from CloudfoundryIncubatingAttributes - private static final AttributeKey CLOUDFOUNDRY_APP_ID = - AttributeKey.stringKey("cloudfoundry.app.id"); + private static final AttributeKey CLOUDFOUNDRY_APP_ID = stringKey("cloudfoundry.app.id"); private static final AttributeKey CLOUDFOUNDRY_APP_INSTANCE_ID = - AttributeKey.stringKey("cloudfoundry.app.instance.id"); + stringKey("cloudfoundry.app.instance.id"); private static final AttributeKey CLOUDFOUNDRY_APP_NAME = - AttributeKey.stringKey("cloudfoundry.app.name"); - private static final AttributeKey CLOUDFOUNDRY_ORG_ID = - AttributeKey.stringKey("cloudfoundry.org.id"); + stringKey("cloudfoundry.app.name"); + private static final AttributeKey CLOUDFOUNDRY_ORG_ID = stringKey("cloudfoundry.org.id"); private static final AttributeKey CLOUDFOUNDRY_ORG_NAME = - AttributeKey.stringKey("cloudfoundry.org.name"); + stringKey("cloudfoundry.org.name"); private static final AttributeKey CLOUDFOUNDRY_PROCESS_ID = - AttributeKey.stringKey("cloudfoundry.process.id"); + stringKey("cloudfoundry.process.id"); private static final AttributeKey CLOUDFOUNDRY_PROCESS_TYPE = - AttributeKey.stringKey("cloudfoundry.process.type"); + stringKey("cloudfoundry.process.type"); private static final AttributeKey CLOUDFOUNDRY_SPACE_ID = - AttributeKey.stringKey("cloudfoundry.space.id"); + stringKey("cloudfoundry.space.id"); private static final AttributeKey CLOUDFOUNDRY_SPACE_NAME = - AttributeKey.stringKey("cloudfoundry.space.name"); + stringKey("cloudfoundry.space.name"); private static final Logger LOG = Logger.getLogger(CloudFoundryResource.class.getName()); private static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final Resource INSTANCE = buildResource(System::getenv); diff --git a/cloudfoundry-resources/src/test/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResourceTest.java b/cloudfoundry-resources/src/test/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResourceTest.java index 1c533cd8a..96474c966 100644 --- a/cloudfoundry-resources/src/test/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResourceTest.java +++ b/cloudfoundry-resources/src/test/java/io/opentelemetry/contrib/cloudfoundry/resources/CloudFoundryResourceTest.java @@ -5,7 +5,9 @@ package io.opentelemetry.contrib.cloudfoundry.resources; +import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.SchemaUrls; @@ -18,8 +20,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.stream.Collectors; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; class CloudFoundryResourceTest { @@ -36,11 +36,11 @@ private static String loadVcapApplicationSample(String filename) { if (is != null) { return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)) .lines() - .collect(Collectors.joining()); + .collect(joining()); } - Assertions.fail("Cannot load resource " + filename); + fail("Cannot load resource " + filename); } catch (IOException e) { - Assertions.fail("Error reading " + filename); + fail("Error reading " + filename); } return ""; } diff --git a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/config/StorageConfiguration.java b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/config/StorageConfiguration.java index 4853ee72f..e8a7f0bd0 100644 --- a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/config/StorageConfiguration.java +++ b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/config/StorageConfiguration.java @@ -5,9 +5,11 @@ package io.opentelemetry.contrib.disk.buffering.config; +import static java.util.concurrent.TimeUnit.HOURS; +import static java.util.concurrent.TimeUnit.SECONDS; + import com.google.auto.value.AutoValue; import java.io.File; -import java.util.concurrent.TimeUnit; /** Defines how the storage should be managed. */ @AutoValue @@ -56,9 +58,9 @@ public static Builder builder() { return new AutoValue_StorageConfiguration.Builder() .setMaxFileSize(1024 * 1024) // 1MB .setMaxFolderSize(10 * 1024 * 1024) // 10MB - .setMaxFileAgeForWriteMillis(TimeUnit.SECONDS.toMillis(30)) - .setMinFileAgeForReadMillis(TimeUnit.SECONDS.toMillis(33)) - .setMaxFileAgeForReadMillis(TimeUnit.HOURS.toMillis(18)) + .setMaxFileAgeForWriteMillis(SECONDS.toMillis(30)) + .setMinFileAgeForReadMillis(SECONDS.toMillis(33)) + .setMaxFileAgeForReadMillis(HOURS.toMillis(18)) .setDebugEnabled(false); } diff --git a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SignalStorageExporter.java b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SignalStorageExporter.java index 51d135299..c508d042f 100644 --- a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SignalStorageExporter.java +++ b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SignalStorageExporter.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.disk.buffering.exporters; +import static java.util.concurrent.TimeUnit.MILLISECONDS; + import io.opentelemetry.contrib.disk.buffering.SignalType; import io.opentelemetry.contrib.disk.buffering.storage.SignalStorage; import io.opentelemetry.contrib.disk.buffering.storage.result.WriteResult; @@ -13,7 +15,6 @@ import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** Internal utility for common export to disk operations across all exporters. */ @@ -34,7 +35,7 @@ public SignalStorageExporter( public CompletableResultCode exportToStorage(Collection items) { CompletableFuture future = storage.write(items); try { - WriteResult operation = future.get(writeTimeout.toMillis(), TimeUnit.MILLISECONDS); + WriteResult operation = future.get(writeTimeout.toMillis(), MILLISECONDS); if (operation.isSuccessful()) { callback.onExportSuccess(type); return CompletableResultCode.ofSuccess(); diff --git a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SpanToDiskExporter.java b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SpanToDiskExporter.java index 2bda19da9..3efe5c367 100644 --- a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SpanToDiskExporter.java +++ b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/exporters/SpanToDiskExporter.java @@ -16,9 +16,10 @@ /** Exporter that stores spans into disk. */ public final class SpanToDiskExporter implements SpanExporter { + private static final SignalType TYPE = SignalType.SPAN; + private final SignalStorageExporter storageExporter; private final ExporterCallback callback; - private static final SignalType TYPE = SignalType.SPAN; private SpanToDiskExporter( SignalStorageExporter storageExporter, ExporterCallback callback) { @@ -26,7 +27,7 @@ private SpanToDiskExporter( this.callback = callback; } - public Builder builder(SignalStorage.Span storage) { + public static Builder builder(SignalStorage.Span storage) { return new Builder(storage); } @@ -51,6 +52,10 @@ public static final class Builder { private ExporterCallback callback = ExporterCallback.noop(); private Duration writeTimeout = Duration.ofSeconds(10); + private Builder(SignalStorage.Span storage) { + this.storage = storage; + } + @CanIgnoreReturnValue public Builder setExporterCallback(ExporterCallback value) { callback = value; @@ -68,9 +73,5 @@ public SpanToDiskExporter build() { new SignalStorageExporter<>(storage, callback, writeTimeout, TYPE); return new SpanToDiskExporter(storageExporter, callback); } - - private Builder(SignalStorage.Span storage) { - this.storage = storage; - } } } diff --git a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/exporter/ToDiskExporter.java b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/exporter/ToDiskExporter.java index 5b2dcd186..a3104a892 100644 --- a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/exporter/ToDiskExporter.java +++ b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/exporter/ToDiskExporter.java @@ -5,6 +5,9 @@ package io.opentelemetry.contrib.disk.buffering.internal.exporter; +import static java.util.logging.Level.FINER; +import static java.util.logging.Level.WARNING; + import io.opentelemetry.contrib.disk.buffering.internal.serialization.serializers.SignalSerializer; import io.opentelemetry.contrib.disk.buffering.internal.storage.Storage; import io.opentelemetry.contrib.disk.buffering.internal.utils.DebugLogger; @@ -12,7 +15,6 @@ import java.io.IOException; import java.util.Collection; import java.util.function.Function; -import java.util.logging.Level; import java.util.logging.Logger; public class ToDiskExporter { @@ -39,7 +41,7 @@ public static ToDiskExporterBuilder builder(Storage storage) { } public synchronized CompletableResultCode export(Collection data) { - logger.log("Intercepting exporter batch.", Level.FINER); + logger.log("Intercepting exporter batch.", FINER); try { serializer.initialize(data); if (storage.write(serializer)) { @@ -50,7 +52,7 @@ public synchronized CompletableResultCode export(Collection data) { } catch (IOException e) { logger.log( "An unexpected error happened while attempting to write the data in disk. Exporting it right away.", - Level.WARNING, + WARNING, e); return exportFunction.apply(data); } finally { diff --git a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/storage/StorageBuilder.java b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/storage/StorageBuilder.java index d43bc18b2..ebea37171 100644 --- a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/storage/StorageBuilder.java +++ b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/storage/StorageBuilder.java @@ -5,13 +5,14 @@ package io.opentelemetry.contrib.disk.buffering.internal.storage; +import static java.util.logging.Level.INFO; + import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.opentelemetry.contrib.disk.buffering.config.StorageConfiguration; import io.opentelemetry.contrib.disk.buffering.internal.utils.SignalTypes; import io.opentelemetry.sdk.common.Clock; import java.io.File; import java.io.IOException; -import java.util.logging.Level; import java.util.logging.Logger; public class StorageBuilder { @@ -43,7 +44,7 @@ public Storage build() throws IOException { File folder = ensureSubdir(configuration.getRootDir(), folderName); FolderManager folderManager = new FolderManager(folder, configuration, clock); if (configuration.isDebugEnabled()) { - logger.log(Level.INFO, "Building storage with configuration => " + configuration); + logger.log(INFO, "Building storage with configuration => " + configuration); } return new Storage(folderManager, configuration.isDebugEnabled()); } diff --git a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/utils/DebugLogger.java b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/utils/DebugLogger.java index 46ff72ebf..b0bb67624 100644 --- a/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/utils/DebugLogger.java +++ b/disk-buffering/src/main/java/io/opentelemetry/contrib/disk/buffering/internal/utils/DebugLogger.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.disk.buffering.internal.utils; +import static java.util.logging.Level.INFO; + import java.util.logging.Level; import java.util.logging.Logger; @@ -22,7 +24,7 @@ public static DebugLogger wrap(Logger logger, boolean debugEnabled) { } public void log(String msg) { - log(msg, Level.INFO); + log(msg, INFO); } public void log(String msg, Level level) { diff --git a/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/ConfigurableOption.java b/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/ConfigurableOption.java index 639207909..aba0ddf11 100644 --- a/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/ConfigurableOption.java +++ b/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/ConfigurableOption.java @@ -5,9 +5,10 @@ package io.opentelemetry.contrib.gcp.auth; +import static java.util.Locale.ROOT; + import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import java.util.Locale; import java.util.Optional; import java.util.function.Supplier; @@ -60,8 +61,7 @@ enum ConfigurableOption { ConfigurableOption(String userReadableName) { this.userReadableName = userReadableName; this.environmentVariableName = this.name(); - this.systemPropertyName = - this.environmentVariableName.toLowerCase(Locale.ROOT).replace('_', '.'); + this.systemPropertyName = this.environmentVariableName.toLowerCase(ROOT).replace('_', '.'); } /** diff --git a/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProvider.java b/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProvider.java index 1de583029..12f73d5bb 100644 --- a/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProvider.java +++ b/gcp-auth-extension/src/main/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProvider.java @@ -5,9 +5,13 @@ package io.opentelemetry.contrib.gcp.auth; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static java.util.Arrays.stream; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toMap; + import com.google.auth.oauth2.GoogleCredentials; import com.google.auto.service.AutoService; -import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.contrib.gcp.auth.GoogleAuthException.Reason; import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; @@ -25,14 +29,12 @@ import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.export.SpanExporter; import java.io.IOException; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; -import java.util.stream.Collectors; import javax.annotation.Nonnull; /** @@ -150,7 +152,7 @@ private static boolean isSignalTargeted(String checkSignal, ConfigProperties con String userSpecifiedTargetedSignals = ConfigurableOption.GOOGLE_OTEL_AUTH_TARGET_SIGNALS.getConfiguredValueWithFallback( configProperties, () -> SIGNAL_TYPE_ALL); - return Arrays.stream(userSpecifiedTargetedSignals.split(",")) + return stream(userSpecifiedTargetedSignals.split(",")) .map(String::trim) .anyMatch( targetedSignal -> @@ -202,17 +204,16 @@ private static Map getRequiredHeaderMap( } catch (IOException e) { throw new GoogleAuthException(Reason.FAILED_ADC_REFRESH, e); } - // flatten list Map flattenedHeaders = gcpHeaders.entrySet().stream() .collect( - Collectors.toMap( + toMap( Map.Entry::getKey, entry -> entry.getValue().stream() .filter(Objects::nonNull) // Filter nulls .filter(s -> !s.isEmpty()) // Filter empty strings - .collect(Collectors.joining(",")))); + .collect(joining(",")))); // Add quota user project header if not detected by the auth library and user provided it via // system properties. if (!flattenedHeaders.containsKey(QUOTA_USER_PROJECT_HEADER)) { @@ -230,9 +231,7 @@ private static Map getRequiredHeaderMap( private static Resource customizeResource(Resource resource, ConfigProperties configProperties) { String gcpProjectId = ConfigurableOption.GOOGLE_CLOUD_PROJECT.getConfiguredValue(configProperties); - Resource res = - Resource.create( - Attributes.of(AttributeKey.stringKey(GCP_USER_PROJECT_ID_KEY), gcpProjectId)); + Resource res = Resource.create(Attributes.of(stringKey(GCP_USER_PROJECT_ID_KEY), gcpProjectId)); return resource.merge(res); } } diff --git a/gcp-auth-extension/src/test/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProviderTest.java b/gcp-auth-extension/src/test/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProviderTest.java index 4fb687925..be0dbe7b2 100644 --- a/gcp-auth-extension/src/test/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProviderTest.java +++ b/gcp-auth-extension/src/test/java/io/opentelemetry/contrib/gcp/auth/GcpAuthAutoConfigurationCustomizerProviderTest.java @@ -14,6 +14,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; @@ -135,15 +138,15 @@ public void testTraceCustomizerOtlpHttp() { ConfigurableOption.GOOGLE_OTEL_AUTH_TARGET_SIGNALS.getSystemProperty(), SIGNAL_TYPE_TRACES); // Prepare mocks prepareMockBehaviorForGoogleCredentials(); - OtlpHttpSpanExporter mockOtlpHttpSpanExporter = Mockito.mock(OtlpHttpSpanExporter.class); + OtlpHttpSpanExporter mockOtlpHttpSpanExporter = mock(OtlpHttpSpanExporter.class); OtlpHttpSpanExporterBuilder otlpSpanExporterBuilder = OtlpHttpSpanExporter.builder(); OtlpHttpSpanExporterBuilder spyOtlpHttpSpanExporterBuilder = Mockito.spy(otlpSpanExporterBuilder); - Mockito.when(spyOtlpHttpSpanExporterBuilder.build()).thenReturn(mockOtlpHttpSpanExporter); + when(spyOtlpHttpSpanExporterBuilder.build()).thenReturn(mockOtlpHttpSpanExporter); - Mockito.when(mockOtlpHttpSpanExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockOtlpHttpSpanExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); List exportedSpans = new ArrayList<>(); - Mockito.when(mockOtlpHttpSpanExporter.export(Mockito.anyCollection())) + when(mockOtlpHttpSpanExporter.export(any())) .thenAnswer( invocationOnMock -> { exportedSpans.addAll(invocationOnMock.getArgument(0)); diff --git a/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/GCPResourceProvider.java b/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/GCPResourceProvider.java index b7e49c1a9..4b92ade57 100644 --- a/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/GCPResourceProvider.java +++ b/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/GCPResourceProvider.java @@ -65,6 +65,7 @@ public class GCPResourceProvider implements ConditionalResourceProvider { private static final Logger LOGGER = Logger.getLogger(GCPResourceProvider.class.getSimpleName()); + private final GCPPlatformDetector detector; // for testing only diff --git a/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/IncubatingAttributes.java b/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/IncubatingAttributes.java index 745d440fd..2f0f937f0 100644 --- a/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/IncubatingAttributes.java +++ b/gcp-resources/src/main/java/io/opentelemetry/contrib/gcp/resource/IncubatingAttributes.java @@ -13,8 +13,6 @@ */ class IncubatingAttributes { - private IncubatingAttributes() {} - public static final AttributeKey CLOUD_ACCOUNT_ID = AttributeKey.stringKey("cloud.account.id"); public static final AttributeKey CLOUD_AVAILABILITY_ZONE = @@ -26,7 +24,6 @@ private IncubatingAttributes() {} public static final AttributeKey CLOUD_REGION = AttributeKey.stringKey("cloud.region"); public static final class CloudPlatformIncubatingValues { - private CloudPlatformIncubatingValues() {} public static final String GCP_COMPUTE_ENGINE = "gcp_compute_engine"; public static final String GCP_CLOUD_RUN = "gcp_cloud_run"; @@ -34,6 +31,8 @@ private CloudPlatformIncubatingValues() {} public static final String GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; public static final String GCP_APP_ENGINE = "gcp_app_engine"; public static final String GCP = "gcp"; + + private CloudPlatformIncubatingValues() {} } public static final AttributeKey FAAS_INSTANCE = AttributeKey.stringKey("faas.instance"); @@ -56,4 +55,6 @@ private CloudPlatformIncubatingValues() {} public static final AttributeKey K8S_CLUSTER_NAME = AttributeKey.stringKey("k8s.cluster.name"); + + private IncubatingAttributes() {} } diff --git a/ibm-mq-metrics/src/test/java/io/opentelemetry/ibm/mq/metricscollector/MetricAssert.java b/ibm-mq-metrics/src/test/java/io/opentelemetry/ibm/mq/metricscollector/MetricAssert.java index 25d173d3d..e6ddfae17 100644 --- a/ibm-mq-metrics/src/test/java/io/opentelemetry/ibm/mq/metricscollector/MetricAssert.java +++ b/ibm-mq-metrics/src/test/java/io/opentelemetry/ibm/mq/metricscollector/MetricAssert.java @@ -5,9 +5,10 @@ package io.opentelemetry.ibm.mq.metricscollector; +import static org.assertj.core.api.Assertions.assertThat; + import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; -import org.assertj.core.api.Assertions; public class MetricAssert { @@ -24,12 +25,12 @@ static MetricAssert assertThatMetric(MetricData metric, int pointOffset) { } MetricAssert hasName(String name) { - Assertions.assertThat(metric.getName()).isEqualTo(name); + assertThat(metric.getName()).isEqualTo(name); return this; } MetricAssert hasValue(long value) { - Assertions.assertThat( + assertThat( ((LongPointData) metric.getLongGaugeData().getPoints().toArray()[this.pointOffset]) .getValue()) .isEqualTo(value); diff --git a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansAutoConfig.java b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansAutoConfig.java index 9c8118ec5..7ee78943e 100644 --- a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansAutoConfig.java +++ b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansAutoConfig.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.inferredspans; +import static java.util.stream.Collectors.toList; + import com.google.auto.service.AutoService; import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.SpanContext; @@ -17,7 +19,6 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.logging.Logger; -import java.util.stream.Collectors; import javax.annotation.Nullable; @AutoService(AutoConfigurationCustomizerProvider.class) @@ -117,7 +118,7 @@ void applyWildcards(String configKey, Consumer> fu Arrays.stream(wildcardListString.split(",")) .filter(str -> !str.isEmpty()) .map(WildcardMatcher::valueOf) - .collect(Collectors.toList()); + .collect(toList()); if (!values.isEmpty()) { funcToApply.accept(values); } diff --git a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessor.java b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessor.java index 22f59ba53..a9288bac2 100644 --- a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessor.java +++ b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessor.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.inferredspans; +import static java.util.Objects.requireNonNull; + import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerProvider; @@ -19,7 +21,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.Objects; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; @@ -33,14 +34,12 @@ public class InferredSpansProcessor implements SpanProcessor { private static final Logger logger = Logger.getLogger(InferredSpansProcessor.class.getName()); public static final String TRACER_NAME = "inferred-spans"; - public static final String TRACER_VERSION = readInferredSpansVersion(); // Visible for testing final SamplingProfiler profiler; private Supplier tracerProvider = GlobalOpenTelemetry::getTracerProvider; - @Nullable private volatile Tracer tracer; InferredSpansProcessor( @@ -134,7 +133,7 @@ private static String readInferredSpansVersion() { Properties properties = new Properties(); properties.load(is); String version = (String) properties.get("contrib.version"); - Objects.requireNonNull(version); + requireNonNull(version); return version; } catch (IOException e) { throw new IllegalStateException(e); diff --git a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessorBuilder.java b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessorBuilder.java index b464f0f42..3124f3341 100644 --- a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessorBuilder.java +++ b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/InferredSpansProcessorBuilder.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.inferredspans; +import static java.util.Arrays.asList; + import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.contrib.inferredspans.internal.CallTree; @@ -12,7 +14,6 @@ import io.opentelemetry.contrib.inferredspans.internal.SpanAnchoredClock; import java.io.File; import java.time.Duration; -import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; import javax.annotation.Nullable; @@ -27,7 +28,7 @@ public class InferredSpansProcessorBuilder { private Duration inferredSpansMinDuration = Duration.ZERO; private List includedClasses = WildcardMatcher.matchAllList(); private List excludedClasses = - Arrays.asList( + asList( WildcardMatcher.caseSensitiveMatcher("java.*"), WildcardMatcher.caseSensitiveMatcher("javax.*"), WildcardMatcher.caseSensitiveMatcher("sun.*"), @@ -43,13 +44,11 @@ public class InferredSpansProcessorBuilder { WildcardMatcher.caseSensitiveMatcher("io.undertow.*")); private Duration profilerInterval = Duration.ofSeconds(5); private Duration profilingDuration = Duration.ofSeconds(5); - @Nullable private String profilerLibDirectory = null; // The following options are only intended to be modified in tests private SpanAnchoredClock clock = new SpanAnchoredClock(); private boolean startScheduledProfiling = true; - @Nullable private File activationEventsFile = null; @Nullable private File jfrFile = null; private BiConsumer parentOverrideHandler = diff --git a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/WildcardMatcher.java b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/WildcardMatcher.java index b6b788c55..7e82a0ec1 100644 --- a/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/WildcardMatcher.java +++ b/inferred-spans/src/main/java/io/opentelemetry/contrib/inferredspans/WildcardMatcher.java @@ -5,8 +5,9 @@ package io.opentelemetry.contrib.inferredspans; +import static java.util.Collections.singletonList; + import java.util.ArrayList; -import java.util.Collections; import java.util.List; import javax.annotation.Nullable; @@ -32,7 +33,7 @@ public abstract class WildcardMatcher { private static final String CASE_SENSITIVE_PREFIX = "(?-i)"; private static final String WILDCARD = "*"; private static final WildcardMatcher MATCH_ALL = valueOf(WILDCARD); - private static final List MATCH_ALL_LIST = Collections.singletonList(MATCH_ALL); + private static final List MATCH_ALL_LIST = singletonList(MATCH_ALL); public static WildcardMatcher caseSensitiveMatcher(String matcher) { return valueOf(CASE_SENSITIVE_PREFIX + matcher); diff --git a/jfr-events/src/test/java/io/opentelemetry/contrib/jfrevent/JfrSpanProcessorTest.java b/jfr-events/src/test/java/io/opentelemetry/contrib/jfrevent/JfrSpanProcessorTest.java index 939a60af6..7225e72fa 100644 --- a/jfr-events/src/test/java/io/opentelemetry/contrib/jfrevent/JfrSpanProcessorTest.java +++ b/jfr-events/src/test/java/io/opentelemetry/contrib/jfrevent/JfrSpanProcessorTest.java @@ -5,7 +5,7 @@ package io.opentelemetry.contrib.jfrevent; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; @@ -52,7 +52,7 @@ void tearDown() { * @throws java.io.IOException on io error */ @Test - public void basicSpan() throws IOException { + void basicSpan() throws IOException { Path output = Files.createTempFile("test-basic-span", ".jfr"); try { @@ -89,7 +89,7 @@ public void basicSpan() throws IOException { * @throws java.lang.InterruptedException interrupted sleep */ @Test - public void basicSpanWithScope() throws IOException, InterruptedException { + void basicSpanWithScope() throws IOException, InterruptedException { Path output = Files.createTempFile("test-basic-span-with-scope", ".jfr"); try { diff --git a/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxConnectorBuilder.java b/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxConnectorBuilder.java index ceba4b2fe..b3c432db6 100644 --- a/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxConnectorBuilder.java +++ b/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxConnectorBuilder.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.jmxscraper; +import static java.util.logging.Level.WARNING; + import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; import java.net.MalformedURLException; @@ -17,7 +19,6 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.management.remote.JMXConnector; @@ -146,7 +147,7 @@ private Map buildEnv() { } }); } catch (ReflectiveOperationException e) { - logger.log(Level.WARNING, "SASL unsupported in current environment: " + e.getMessage()); + logger.log(WARNING, "SASL unsupported in current environment: " + e.getMessage()); } return env; } diff --git a/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxScraper.java b/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxScraper.java index 85c47ba0e..a5e0d4de1 100644 --- a/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxScraper.java +++ b/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/JmxScraper.java @@ -5,6 +5,12 @@ package io.opentelemetry.contrib.jmxscraper; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static java.util.Optional.ofNullable; +import static java.util.logging.Level.INFO; +import static java.util.logging.Level.SEVERE; + import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.contrib.jmxscraper.config.JmxScraperConfig; import io.opentelemetry.contrib.jmxscraper.config.PropertiesCustomizer; @@ -21,14 +27,10 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; import java.util.logging.Logger; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; @@ -55,7 +57,7 @@ public static void main(String[] args) { // set log format System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT %4$s %5$s%n"); - List effectiveArgs = new ArrayList<>(Arrays.asList(args)); + List effectiveArgs = new ArrayList<>(asList(args)); boolean testMode = effectiveArgs.remove(TEST_ARG); try { @@ -73,7 +75,7 @@ public static void main(String[] args) { JmxScraperConfig scraperConfig = configCustomizer.getScraperConfig(); long exportSeconds = scraperConfig.getSamplingInterval().toMillis() / 1000; - logger.log(Level.INFO, "metrics export interval (seconds) = " + exportSeconds); + logger.log(INFO, "metrics export interval (seconds) = " + exportSeconds); JmxMetricInsight service = JmxMetricInsight.createService( @@ -81,8 +83,8 @@ public static void main(String[] args) { JmxConnectorBuilder connectorBuilder = JmxConnectorBuilder.createNew(scraperConfig.getServiceUrl()); - Optional.ofNullable(scraperConfig.getUsername()).ifPresent(connectorBuilder::withUser); - Optional.ofNullable(scraperConfig.getPassword()).ifPresent(connectorBuilder::withPassword); + ofNullable(scraperConfig.getUsername()).ifPresent(connectorBuilder::withUser); + ofNullable(scraperConfig.getPassword()).ifPresent(connectorBuilder::withPassword); if (scraperConfig.isRegistrySsl()) { connectorBuilder.withSslRegistry(); @@ -95,20 +97,20 @@ public static void main(String[] args) { jmxScraper.start(); } } catch (ConfigurationException e) { - logger.log(Level.SEVERE, "invalid configuration: " + e.getMessage(), e); + logger.log(SEVERE, "invalid configuration: " + e.getMessage(), e); System.exit(1); } catch (InvalidArgumentException e) { - logger.log(Level.SEVERE, e.getMessage(), e); + logger.log(SEVERE, e.getMessage(), e); logger.info("Usage: java -jar [-test] [-config ]"); logger.info(" -test test JMX connection with provided configuration and exit"); logger.info( " -config provide configuration, where is - for stdin, or "); System.exit(1); } catch (IOException e) { - logger.log(Level.SEVERE, "Unable to connect ", e); + logger.log(SEVERE, "Unable to connect ", e); System.exit(2); } catch (RuntimeException e) { - logger.log(Level.SEVERE, e.getMessage(), e); + logger.log(SEVERE, e.getMessage(), e); System.exit(3); } } @@ -119,14 +121,14 @@ private static boolean testConnection(JmxConnectorBuilder connectorBuilder) { MBeanServerConnection connection = connector.getMBeanServerConnection(); Integer mbeanCount = connection.getMBeanCount(); if (mbeanCount > 0) { - logger.log(Level.INFO, "JMX connection test OK"); + logger.log(INFO, "JMX connection test OK"); return true; } else { - logger.log(Level.SEVERE, "JMX connection test ERROR"); + logger.log(SEVERE, "JMX connection test ERROR"); return false; } } catch (IOException e) { - logger.log(Level.SEVERE, "JMX connection test ERROR", e); + logger.log(SEVERE, "JMX connection test ERROR", e); return false; } } @@ -210,7 +212,7 @@ private void start() throws IOException { try (JMXConnector connector = client.build()) { MBeanServerConnection connection = connector.getMBeanServerConnection(); - service.startRemote(getMetricConfig(config), () -> Collections.singletonList(connection)); + service.startRemote(getMetricConfig(config), () -> singletonList(connection)); running.set(true); logger.info("JMX scraping started"); diff --git a/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/config/JmxScraperConfig.java b/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/config/JmxScraperConfig.java index 09a97eb83..62b6c38ea 100644 --- a/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/config/JmxScraperConfig.java +++ b/jmx-scraper/src/main/java/io/opentelemetry/contrib/jmxscraper/config/JmxScraperConfig.java @@ -5,15 +5,19 @@ package io.opentelemetry.contrib.jmxscraper.config; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptySet; +import static java.util.Collections.unmodifiableList; +import static java.util.Collections.unmodifiableSet; +import static java.util.Locale.ROOT; + import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; import java.io.InputStream; import java.time.Duration; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.List; -import java.util.Locale; import java.util.Set; import java.util.logging.Logger; import javax.annotation.Nullable; @@ -49,9 +53,9 @@ public class JmxScraperConfig { private String serviceUrl = ""; - private List jmxConfig = Collections.emptyList(); + private List jmxConfig = emptyList(); - private Set targetSystems = Collections.emptySet(); + private Set targetSystems = emptySet(); private TargetSystemSource targetSystemSource = TargetSystemSource.AUTO; @@ -73,7 +77,7 @@ public enum TargetSystemSource { static TargetSystemSource fromString(String source) { try { - return TargetSystemSource.valueOf(source.toUpperCase(Locale.ROOT)); + return TargetSystemSource.valueOf(source.toUpperCase(ROOT)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid target system source: " + source, e); } @@ -217,8 +221,8 @@ public static JmxScraperConfig fromConfig(ConfigProperties config) { "at least one of '" + JMX_TARGET_SYSTEM + "' or '" + JMX_CONFIG + "' must be set"); } - scraperConfig.jmxConfig = Collections.unmodifiableList(jmxConfig); - scraperConfig.targetSystems = Collections.unmodifiableSet(new HashSet<>(targetSystem)); + scraperConfig.jmxConfig = unmodifiableList(jmxConfig); + scraperConfig.targetSystems = unmodifiableSet(new HashSet<>(targetSystem)); scraperConfig.username = config.getString("otel.jmx.username"); scraperConfig.password = config.getString("otel.jmx.password"); diff --git a/jmx-scraper/src/test/java/io/opentelemetry/contrib/jmxscraper/JmxScraperTest.java b/jmx-scraper/src/test/java/io/opentelemetry/contrib/jmxscraper/JmxScraperTest.java index b51144360..430476d51 100644 --- a/jmx-scraper/src/test/java/io/opentelemetry/contrib/jmxscraper/JmxScraperTest.java +++ b/jmx-scraper/src/test/java/io/opentelemetry/contrib/jmxscraper/JmxScraperTest.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.jmxscraper; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -12,8 +14,6 @@ import io.opentelemetry.contrib.jmxscraper.config.TestUtil; import java.io.IOException; import java.io.InputStream; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Properties; import org.junit.jupiter.api.Test; @@ -32,7 +32,7 @@ void shouldThrowExceptionWhenInvalidCommandLineArgsProvided() { @Test void emptyArgumentsAllowed() throws InvalidArgumentException { - assertThat(JmxScraper.argsToConfig(Collections.emptyList())) + assertThat(JmxScraper.argsToConfig(emptyList())) .describedAs("empty config allowed to use JVM properties") .isEmpty(); } @@ -43,7 +43,7 @@ void shouldThrowExceptionWhenMissingProperties() { } private static void testInvalidArguments(String... args) { - assertThatThrownBy(() -> JmxScraper.argsToConfig(Arrays.asList(args))) + assertThatThrownBy(() -> JmxScraper.argsToConfig(asList(args))) .isInstanceOf(InvalidArgumentException.class); } @@ -54,7 +54,7 @@ void shouldCreateConfig_propertiesLoadedFromFile() throws InvalidArgumentExcepti // Windows returns /C:/path/to/file, which is not a valid path for Path.get() in Java. String filePath = ClassLoader.getSystemClassLoader().getResource("validConfig.properties").getPath(); - List args = Arrays.asList("-config", filePath); + List args = asList("-config", filePath); // When Properties parsedConfig = JmxScraper.argsToConfig(args); @@ -73,7 +73,7 @@ void shouldCreateConfig_propertiesLoadedFromStdIn() throws InvalidArgumentExcept ClassLoader.getSystemClassLoader().getResourceAsStream("validConfig.properties")) { // Given System.setIn(stream); - List args = Arrays.asList("-config", "-"); + List args = asList("-config", "-"); // When Properties parsedConfig = JmxScraper.argsToConfig(args); diff --git a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeter.java b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeter.java index e8a6b827c..2a080c8e8 100644 --- a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeter.java +++ b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeter.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.metrics.micrometer; +import static java.util.Objects.requireNonNull; + import io.opentelemetry.api.metrics.DoubleGaugeBuilder; import io.opentelemetry.api.metrics.DoubleHistogramBuilder; import io.opentelemetry.api.metrics.LongCounterBuilder; @@ -15,7 +17,6 @@ import io.opentelemetry.contrib.metrics.micrometer.internal.instruments.MicrometerLongCounter; import io.opentelemetry.contrib.metrics.micrometer.internal.instruments.MicrometerLongUpDownCounter; import io.opentelemetry.contrib.metrics.micrometer.internal.state.MeterSharedState; -import java.util.Objects; final class MicrometerMeter implements Meter { final MeterSharedState meterSharedState; @@ -26,25 +27,25 @@ final class MicrometerMeter implements Meter { @Override public LongCounterBuilder counterBuilder(String name) { - Objects.requireNonNull(name, "name"); + requireNonNull(name, "name"); return MicrometerLongCounter.builder(meterSharedState, name); } @Override public LongUpDownCounterBuilder upDownCounterBuilder(String name) { - Objects.requireNonNull(name, "name"); + requireNonNull(name, "name"); return MicrometerLongUpDownCounter.builder(meterSharedState, name); } @Override public DoubleHistogramBuilder histogramBuilder(String name) { - Objects.requireNonNull(name, "name"); + requireNonNull(name, "name"); return MicrometerDoubleHistogram.builder(meterSharedState, name); } @Override public DoubleGaugeBuilder gaugeBuilder(String name) { - Objects.requireNonNull(name, "name"); + requireNonNull(name, "name"); return MicrometerDoubleGauge.builder(meterSharedState, name); } } diff --git a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeterProvider.java b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeterProvider.java index d76e19a34..2817754e2 100644 --- a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeterProvider.java +++ b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/MicrometerMeterProvider.java @@ -5,12 +5,13 @@ package io.opentelemetry.contrib.metrics.micrometer; +import static java.util.Objects.requireNonNull; + import io.micrometer.core.instrument.MeterRegistry; import io.opentelemetry.api.metrics.MeterBuilder; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.contrib.metrics.micrometer.internal.MemoizingSupplier; import io.opentelemetry.contrib.metrics.micrometer.internal.state.MeterProviderSharedState; -import java.util.Objects; import java.util.function.Supplier; /** @@ -44,13 +45,13 @@ public void close() { /** {@inheritDoc} */ @Override public MeterBuilder meterBuilder(String instrumentationScopeName) { - Objects.requireNonNull(instrumentationScopeName, "instrumentationScopeName"); + requireNonNull(instrumentationScopeName, "instrumentationScopeName"); return new MicrometerMeterBuilder(meterProviderSharedState, instrumentationScopeName); } /** Returns a new builder instance for this provider with the specified {@link MeterRegistry}. */ public static MicrometerMeterProviderBuilder builder(MeterRegistry meterRegistry) { - Objects.requireNonNull(meterRegistry, "meterRegistry"); + requireNonNull(meterRegistry, "meterRegistry"); return new MicrometerMeterProviderBuilder(() -> meterRegistry); } @@ -62,7 +63,7 @@ public static MicrometerMeterProviderBuilder builder(MeterRegistry meterRegistry */ public static MicrometerMeterProviderBuilder builder( Supplier meterRegistrySupplier) { - Objects.requireNonNull(meterRegistrySupplier, "meterRegistrySupplier"); + requireNonNull(meterRegistrySupplier, "meterRegistrySupplier"); return new MicrometerMeterProviderBuilder(new MemoizingSupplier<>(meterRegistrySupplier)); } } diff --git a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrar.java b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrar.java index d9021a234..e3c34b2bb 100644 --- a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrar.java +++ b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrar.java @@ -5,8 +5,9 @@ package io.opentelemetry.contrib.metrics.micrometer; +import static java.util.Objects.requireNonNull; + import java.util.List; -import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -39,7 +40,7 @@ public final class ScheduledCallbackRegistrar implements CallbackRegistrar { public static ScheduledCallbackRegistrarBuilder builder( ScheduledExecutorService scheduledExecutorService) { - Objects.requireNonNull(scheduledExecutorService, "scheduledExecutorService"); + requireNonNull(scheduledExecutorService, "scheduledExecutorService"); return new ScheduledCallbackRegistrarBuilder(scheduledExecutorService); } diff --git a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrarBuilder.java b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrarBuilder.java index de0da54f7..fb7ff0326 100644 --- a/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrarBuilder.java +++ b/micrometer-meter-provider/src/main/java/io/opentelemetry/contrib/metrics/micrometer/ScheduledCallbackRegistrarBuilder.java @@ -5,9 +5,10 @@ package io.opentelemetry.contrib.metrics.micrometer; +import static java.util.Objects.requireNonNull; + import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.time.Duration; -import java.util.Objects; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -27,7 +28,7 @@ public final class ScheduledCallbackRegistrarBuilder { /** Sets the period between successive executions of each registered callback */ @CanIgnoreReturnValue public ScheduledCallbackRegistrarBuilder setPeriod(long period, TimeUnit unit) { - Objects.requireNonNull(unit, "unit"); + requireNonNull(unit, "unit"); this.period = period; this.timeUnit = unit; return this; @@ -36,7 +37,7 @@ public ScheduledCallbackRegistrarBuilder setPeriod(long period, TimeUnit unit) { /** Sets the period between successive executions of each registered callback */ @CanIgnoreReturnValue public ScheduledCallbackRegistrarBuilder setPeriod(Duration period) { - Objects.requireNonNull(period, "period"); + requireNonNull(period, "period"); this.period = period.toMillis(); this.timeUnit = TimeUnit.MILLISECONDS; return this; diff --git a/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/connectivity/websocket/OkHttpWebSocket.java b/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/connectivity/websocket/OkHttpWebSocket.java index ec453bf6f..8ff386251 100644 --- a/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/connectivity/websocket/OkHttpWebSocket.java +++ b/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/connectivity/websocket/OkHttpWebSocket.java @@ -5,7 +5,8 @@ package io.opentelemetry.opamp.client.internal.connectivity.websocket; -import java.util.Objects; +import static java.util.Objects.requireNonNull; + import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -65,7 +66,7 @@ public void close(int code, @Nullable String reason) { } private okhttp3.WebSocket getWebSocket() { - return Objects.requireNonNull(webSocket.get()); + return requireNonNull(webSocket.get()); } private class ListenerAdapter extends WebSocketListener { diff --git a/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/state/InMemoryState.java b/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/state/InMemoryState.java index 89ba8b1cb..be2d34215 100644 --- a/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/state/InMemoryState.java +++ b/opamp-client/src/main/java/io/opentelemetry/opamp/client/internal/state/InMemoryState.java @@ -5,7 +5,8 @@ package io.opentelemetry.opamp.client.internal.state; -import java.util.Objects; +import static java.util.Objects.requireNonNull; + import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; @@ -33,6 +34,6 @@ public void set(T value) { @Nonnull @Override public T get() { - return Objects.requireNonNull(state.get()); + return requireNonNull(state.get()); } } diff --git a/processors/src/test/java/io/opentelemetry/contrib/filter/FilteringLogRecordProcessorTest.java b/processors/src/test/java/io/opentelemetry/contrib/filter/FilteringLogRecordProcessorTest.java index 874895340..3b775a527 100644 --- a/processors/src/test/java/io/opentelemetry/contrib/filter/FilteringLogRecordProcessorTest.java +++ b/processors/src/test/java/io/opentelemetry/contrib/filter/FilteringLogRecordProcessorTest.java @@ -79,7 +79,7 @@ public SdkLoggerProviderBuilder apply( logRecordData -> { SpanContext spanContext = logRecordData.getSpanContext(); return spanContext.isSampled(); - }) {}) + })) .build() .get("TestScope"); } diff --git a/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/MetricAdapter.java b/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/MetricAdapter.java index c0b381e7d..e71331964 100644 --- a/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/MetricAdapter.java +++ b/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/MetricAdapter.java @@ -6,6 +6,8 @@ package io.opentelemetry.contrib.metrics.prometheus.clientbridge; import static io.prometheus.client.Collector.doubleToGoString; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.NANOSECONDS; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; @@ -28,7 +30,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.function.Function; import javax.annotation.Nullable; @@ -54,6 +55,8 @@ final class MetricAdapter { static final String LABEL_NAME_QUANTILE = "quantile"; static final String LABEL_NAME_LE = "le"; + static final Function sanitizer = new NameSanitizer(); + // Converts a MetricData to a Prometheus MetricFamilySamples. static MetricFamilySamples toMetricFamilySamples(MetricData metricData) { String cleanMetricName = cleanMetricName(metricData.getName()); @@ -99,8 +102,6 @@ static Collector.Type toMetricFamilyType(MetricData metricData) { return Collector.Type.UNKNOWN; } - static final Function sanitizer = new NameSanitizer(); - // Converts a list of points from MetricData to a list of Prometheus Samples. static List toSamples( String name, MetricDataType type, Collection points) { @@ -291,7 +292,7 @@ private static Sample createSample( labelValues, value, toPrometheusExemplar(exemplar), - TimeUnit.MILLISECONDS.convert(timestampNanos, TimeUnit.NANOSECONDS)); + MILLISECONDS.convert(timestampNanos, NANOSECONDS)); } return new Sample( name, @@ -299,7 +300,7 @@ private static Sample createSample( labelValues, value, null, - TimeUnit.MILLISECONDS.convert(timestampNanos, TimeUnit.NANOSECONDS)); + MILLISECONDS.convert(timestampNanos, NANOSECONDS)); } private static io.prometheus.client.exemplars.Exemplar toPrometheusExemplar( @@ -309,7 +310,7 @@ private static io.prometheus.client.exemplars.Exemplar toPrometheusExemplar( return new io.prometheus.client.exemplars.Exemplar( getExemplarValue(exemplar), // Convert to ms for prometheus, truncate nanosecond precision. - TimeUnit.NANOSECONDS.toMillis(exemplar.getEpochNanos()), + NANOSECONDS.toMillis(exemplar.getEpochNanos()), "trace_id", spanContext.getTraceId(), "span_id", diff --git a/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/PrometheusCollector.java b/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/PrometheusCollector.java index 3acc1096a..e9c574f92 100644 --- a/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/PrometheusCollector.java +++ b/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/PrometheusCollector.java @@ -5,6 +5,8 @@ package io.opentelemetry.contrib.metrics.prometheus.clientbridge; +import static java.util.Collections.unmodifiableList; + import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; @@ -15,7 +17,6 @@ import io.prometheus.client.CollectorRegistry; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.function.Supplier; @@ -79,7 +80,7 @@ public List collect() { for (MetricData metricData : allMetrics) { allSamples.add(MetricAdapter.toMetricFamilySamples(metricData)); } - return Collections.unmodifiableList(allSamples); + return unmodifiableList(allSamples); } } } diff --git a/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/Serializer.java b/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/Serializer.java index d696a14b7..d79892a27 100644 --- a/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/Serializer.java +++ b/prometheus-client-bridge/src/main/java/io/opentelemetry/contrib/metrics/prometheus/clientbridge/Serializer.java @@ -21,11 +21,12 @@ package io.opentelemetry.contrib.metrics.prometheus.clientbridge; +import static java.util.Collections.emptyList; + import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.data.PointData; import java.util.Collection; -import java.util.Collections; import java.util.List; /** Serializes metrics into Prometheus exposition formats. */ @@ -71,7 +72,7 @@ static Collection getPoints(MetricData metricData) { case EXPONENTIAL_HISTOGRAM: return metricData.getExponentialHistogramData().getPoints(); } - return Collections.emptyList(); + return emptyList(); } private Serializer() {} diff --git a/span-stacktrace/src/main/java/io/opentelemetry/contrib/stacktrace/StackTraceAutoConfig.java b/span-stacktrace/src/main/java/io/opentelemetry/contrib/stacktrace/StackTraceAutoConfig.java index 2315d2a10..3a427b7e3 100644 --- a/span-stacktrace/src/main/java/io/opentelemetry/contrib/stacktrace/StackTraceAutoConfig.java +++ b/span-stacktrace/src/main/java/io/opentelemetry/contrib/stacktrace/StackTraceAutoConfig.java @@ -5,6 +5,9 @@ package io.opentelemetry.contrib.stacktrace; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.SEVERE; + import com.google.auto.service.AutoService; import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; @@ -50,7 +53,7 @@ static long getMinDuration(ConfigProperties properties) { log.fine("Stack traces capture is disabled"); } else { log.log( - Level.FINE, + FINE, "Stack traces will be added to spans with a minimum duration of {0} nanos", minDuration); } @@ -70,7 +73,7 @@ static Predicate getFilterPredicate(ConfigProperties properties) { if (filter == null) { // if value is set, lack of filtering is likely an error and must be reported - Level disabledLogLevel = filterClass != null ? Level.SEVERE : Level.FINE; + Level disabledLogLevel = filterClass != null ? SEVERE : FINE; log.log(disabledLogLevel, "Span stacktrace filtering disabled"); return span -> true; } else {