Enable all errorprone checks (#3155)

* Enable all errorprone checks

* Fixes

* Finish

* Finish

* Add flag to disable error prone
This commit is contained in:
Anuraag Agrawal 2021-06-01 17:41:08 +09:00 committed by GitHub
parent a746c94b1c
commit c3dedbb64e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
238 changed files with 783 additions and 566 deletions

View File

@ -51,11 +51,11 @@ public class E2EAgentBenchmark {
}
@Test
void run() throws Exception {
void run() throws InterruptedException {
runBenchmark();
}
private void runBenchmark() throws Exception {
private void runBenchmark() throws InterruptedException {
String agentPath = System.getProperty("io.opentelemetry.smoketest.agent.shadowJar.path");
// otlp collector container

View File

@ -11,7 +11,7 @@ import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import java.util.concurrent.TimeUnit;
public class Worker {
public final class Worker {
private static final Tracer tracer = GlobalOpenTelemetry.getTracer("test");
@ -32,4 +32,6 @@ public class Worker {
span.end();
}
}
private Worker() {}
}

View File

@ -18,7 +18,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class JettyPerftest {
public final class JettyPerftest {
private static final int PORT = 8080;
private static final String PATH = "/work";
@ -53,7 +53,7 @@ public class JettyPerftest {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
if (request.getParameter("error") != null) {
throw new RuntimeException("some sync error");
throw new IllegalStateException("some sync error");
}
String workVal = request.getParameter("workTimeMillis");
long workTimeMillis = 0L;
@ -64,7 +64,7 @@ public class JettyPerftest {
response.getWriter().print("Did " + workTimeMillis + "ms of work.");
}
private void scheduleWork(long workTimeMillis) {
private static void scheduleWork(long workTimeMillis) {
Span span = tracer.spanBuilder("work").startSpan();
try (Scope scope = span.makeCurrent()) {
if (span != null) {
@ -79,4 +79,6 @@ public class JettyPerftest {
}
}
}
private JettyPerftest() {}
}

View File

@ -29,7 +29,7 @@ class HomeController @Inject()(cc: ControllerComponents) extends AbstractControl
def doGet(workTimeMillis: Option[Long], error: Option[String]) = Action {
implicit request: Request[AnyContent] =>
error match {
case Some(x) => throw new RuntimeException("some sync error")
case Some(x) => throw new IllegalStateException("some sync error")
case None => {
var workTime = workTimeMillis.getOrElse(0L)
scheduleWork(workTime)

View File

@ -34,8 +34,11 @@ public class HttpBenchmark {
while (!AbstractLifeCycle.STARTED.equals(jettyServer.getState())) {
Thread.sleep(500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
} catch (Exception e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
}

View File

@ -55,7 +55,8 @@ public class InstrumenterBenchmark {
}
static class ConstantHttpAttributesExtractor extends HttpAttributesExtractor<Void, Void> {
static HttpAttributesExtractor<Void, Void> INSTANCE = new ConstantHttpAttributesExtractor();
static final HttpAttributesExtractor<Void, Void> INSTANCE =
new ConstantHttpAttributesExtractor();
@Override
protected @Nullable String method(Void unused) {

View File

@ -50,7 +50,7 @@ public class TypeMatchingBenchmark {
}
}
} catch (IOException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
}
}

View File

@ -5,6 +5,7 @@
package io.opentelemetry.benchmark.classes;
@SuppressWarnings("ClassNamedLikeTypeParameter")
public interface A {
void a();
}

View File

@ -5,6 +5,7 @@
package io.opentelemetry.benchmark.classes;
@SuppressWarnings("ClassNamedLikeTypeParameter")
public interface B extends A {
void b();
}

View File

@ -5,6 +5,7 @@
package io.opentelemetry.benchmark.classes;
@SuppressWarnings("ClassNamedLikeTypeParameter")
public interface C extends A, B {
void c();
}

View File

@ -5,6 +5,7 @@
package io.opentelemetry.benchmark.classes;
@SuppressWarnings("ClassNamedLikeTypeParameter")
public interface D extends A, B, C {
void d();
}

View File

@ -5,6 +5,7 @@
package io.opentelemetry.benchmark.classes;
@SuppressWarnings("ClassNamedLikeTypeParameter")
public interface E extends B, C, D {
void e();
}

View File

@ -5,6 +5,7 @@
package io.opentelemetry.benchmark.classes;
@SuppressWarnings("ClassNamedLikeTypeParameter")
public abstract class F implements E {
public abstract void f();

View File

@ -19,8 +19,8 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class HttpClass {
private final String contextPath = "/path";
private final Integer port = 18888;
private static final String contextPath = "/path";
private static final Integer port = 18888;
public Server buildJettyServer() {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");

View File

@ -79,7 +79,10 @@ allprojects {
tasks.withType(JavaCompile).configureEach {
options.errorprone {
enabled = rootProject.findProperty("disableErrorProne") != "true"
disableWarningsInGeneratedCode = true
allDisabledChecksAsWarnings = true
excludedPaths = ".*/build/generated/.*"
// Doesn't work well with Java 8
@ -89,6 +92,15 @@ allprojects {
disable("AutoValueImmutableFields")
disable("StringSplitter")
// Don't currently use this (to indicate a local variable that's mutated) but could
// consider for future.
disable("Var")
// Don't support Android without desugar
disable("AndroidJdkLibsChecker")
disable("Java7ApiChecker")
disable("StaticOrDefaultInterfaceMethod")
// Great check, but for bytecode manipulation it's too common to separate over
// onEnter / onExit
// TODO(anuraaga): Only disable for auto instrumentation project.
@ -101,6 +113,9 @@ allprojects {
// We end up using obsolete types if a library we're instrumenting uses them.
disable("JdkObsolete")
// Limits API possibilities
disable("NoFunctionalReturnType")
// Storing into a variable in onEnter triggers this unfortunately.
// TODO(anuraaga): Only disable for auto instrumentation project.
disable("UnusedVariable")
@ -108,6 +123,19 @@ allprojects {
// TODO(anuraaga): Remove this, we use this pattern in several tests and it will mean
// some moving.
disable("DefaultPackage")
// TODO(anuraaga): Remove this, all our advice classes miss constructors but probably should
// address this.
disable("PrivateConstructorForUtilityClass")
// TODO(anuraaga): Remove this, probably after instrumenter API migration instead of dealing
// with older APIs.
disable("InconsistentOverloads")
disable("TypeParameterNaming")
if (name.contains("Jmh") || name.contains("Test")) {
disable("FieldMissingNullable")
}
}
}
}

View File

@ -64,7 +64,7 @@ public class ClasspathByteBuddyPlugin implements Plugin {
Class<?> clazz = Class.forName(className, false, classLoader);
return (Plugin) clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create ByteBuddy plugin instance", e);
throw new IllegalStateException("Failed to create ByteBuddy plugin instance", e);
}
}
@ -84,7 +84,7 @@ public class ClasspathByteBuddyPlugin implements Plugin {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException("Cannot resolve " + file + " as URL", e);
throw new IllegalStateException("Cannot resolve " + file + " as URL", e);
}
}
}

View File

@ -105,7 +105,7 @@ public class MuzzlePlugin implements Plugin<Project> {
.getMethod("printMuzzleReferences", ClassLoader.class);
assertionMethod.invoke(null, instrumentationCL);
} catch (Exception e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
});
});
@ -191,7 +191,7 @@ public class MuzzlePlugin implements Plugin<Project> {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
})
.toArray(URL[]::new);
@ -305,7 +305,7 @@ public class MuzzlePlugin implements Plugin<Project> {
userCL,
muzzleDirective.getAssertPass().get());
} catch (Exception e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
@ -366,7 +366,7 @@ public class MuzzlePlugin implements Plugin<Project> {
try {
rangeResult = system.resolveVersionRange(session, rangeRequest);
} catch (VersionRangeResolutionException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
Set<Artifact> allVersionArtifacts =
@ -426,7 +426,7 @@ public class MuzzlePlugin implements Plugin<Project> {
try {
allRangeResult = system.resolveVersionRange(session, allRangeRequest);
} catch (VersionRangeResolutionException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
VersionRangeRequest rangeRequest = new VersionRangeRequest();
@ -436,7 +436,7 @@ public class MuzzlePlugin implements Plugin<Project> {
try {
rangeResult = system.resolveVersionRange(session, rangeRequest);
} catch (VersionRangeResolutionException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
allRangeResult.getVersions().removeAll(rangeResult.getVersions());

View File

@ -84,7 +84,7 @@ val DEPENDENCIES = listOf(
"info.solidsoft.spock:spock-global-unroll:0.5.1",
"org.assertj:assertj-core:3.19.0",
"org.awaitility:awaitility:4.0.3",
"org.checkerframework:checker-qual:3.6.1",
"org.checkerframework:checker-qual:3.13.0",
"org.codehaus.groovy:groovy-all:${groovyVersion}",
"org.objenesis:objenesis:3.1",
"org.spockframework:spock-core:1.3-groovy-2.5",

View File

@ -133,7 +133,6 @@
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>

View File

@ -7,6 +7,7 @@ package io.opentelemetry.instrumentation.api.caching;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A builder of {@link Cache}. */
public final class CacheBuilder {
@ -16,7 +17,7 @@ public final class CacheBuilder {
private boolean weakKeys;
private boolean weakValues;
private long maximumSize = UNSET;
private Executor executor = null;
@Nullable private Executor executor = null;
/** Sets the maximum size of the cache. */
public CacheBuilder setMaximumSize(long maximumSize) {

View File

@ -5,7 +5,9 @@
package io.opentelemetry.instrumentation.api;
public class InstrumentationVersion {
public final class InstrumentationVersion {
public static final String VERSION =
InstrumentationVersion.class.getPackage().getImplementationVersion();
private InstrumentationVersion() {}
}

View File

@ -23,7 +23,7 @@ public abstract class Config {
// lazy initialized, so that javaagent can set it, and library instrumentation can fall back and
// read system properties
private static volatile Config INSTANCE = null;
@Nullable private static volatile Config instance = null;
/**
* Sets the agent configuration singleton. This method is only supposed to be called once, from
@ -31,21 +31,21 @@ public abstract class Config {
* Config#get()} is used for the first time).
*/
public static void internalInitializeConfig(Config config) {
if (INSTANCE != null) {
if (instance != null) {
log.warn("Config#INSTANCE was already set earlier");
return;
}
INSTANCE = requireNonNull(config);
instance = requireNonNull(config);
}
public static Config get() {
if (INSTANCE == null) {
if (instance == null) {
// this should only happen in library instrumentation
//
// no need to synchronize because worst case is creating INSTANCE more than once
INSTANCE = new ConfigBuilder().readEnvironmentVariables().readSystemProperties().build();
instance = new ConfigBuilder().readEnvironmentVariables().readSystemProperties().build();
}
return INSTANCE;
return instance;
}
public static Config create(Map<String, String> allProperties) {

View File

@ -423,4 +423,6 @@ public final class RedisCommandSanitizer {
}
}
}
private RedisCommandSanitizer() {}
}

View File

@ -58,8 +58,8 @@ public class Instrumenter<REQUEST, RESPONSE> {
private final List<? extends AttributesExtractor<? super REQUEST, ? super RESPONSE>> extractors;
private final List<? extends RequestListener> requestListeners;
private final ErrorCauseExtractor errorCauseExtractor;
private final StartTimeExtractor<REQUEST> startTimeExtractor;
private final EndTimeExtractor<RESPONSE> endTimeExtractor;
@Nullable private final StartTimeExtractor<REQUEST> startTimeExtractor;
@Nullable private final EndTimeExtractor<RESPONSE> endTimeExtractor;
Instrumenter(InstrumenterBuilder<REQUEST, RESPONSE> builder) {
this.instrumentationName = builder.instrumentationName;

View File

@ -17,6 +17,7 @@ import io.opentelemetry.instrumentation.api.annotations.UnstableApi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A builder of {@link Instrumenter}. Instrumentation libraries should generally expose their own
@ -34,12 +35,12 @@ public final class InstrumenterBuilder<REQUEST, RESPONSE> {
new ArrayList<>();
final List<RequestListener> requestListeners = new ArrayList<>();
SpanKindExtractor<? super REQUEST> spanKindExtractor = null;
SpanKindExtractor<? super REQUEST> spanKindExtractor = SpanKindExtractor.alwaysInternal();
SpanStatusExtractor<? super REQUEST, ? super RESPONSE> spanStatusExtractor =
SpanStatusExtractor.getDefault();
ErrorCauseExtractor errorCauseExtractor = ErrorCauseExtractor.jdk();
StartTimeExtractor<REQUEST> startTimeExtractor = null;
EndTimeExtractor<RESPONSE> endTimeExtractor = null;
@Nullable StartTimeExtractor<REQUEST> startTimeExtractor = null;
@Nullable EndTimeExtractor<RESPONSE> endTimeExtractor = null;
InstrumenterBuilder(
OpenTelemetry openTelemetry,

View File

@ -123,9 +123,6 @@ public final class SupportabilityMetrics {
case CONSUMER:
consumer.increment();
break;
default:
// in case a new kind gets added, we don't want to fail.
break;
}
}
@ -141,10 +138,8 @@ public final class SupportabilityMetrics {
return producer.sumThenReset();
case CONSUMER:
return consumer.sumThenReset();
default:
// in case a new kind gets added, we don't want to fail.
return 0;
}
return 0;
}
}
}

View File

@ -24,7 +24,7 @@ public class AppServerBridge {
* @return new context with AppServerBridge attached.
*/
public static Context init(Context ctx) {
return init(ctx, true);
return init(ctx, /* shouldRecordException= */ true);
}
/**

View File

@ -98,7 +98,7 @@ public final class ServerSpanNaming {
CONTAINER(1),
// for servlet filters we try to find the best name which isn't necessarily from the first
// filter that is called
FILTER(2, false),
FILTER(2, /* useFirst= */ false),
SERVLET(3),
CONTROLLER(4);
@ -106,7 +106,7 @@ public final class ServerSpanNaming {
private final boolean useFirst;
Source(int order) {
this(order, true);
this(order, /* useFirst= */ true);
}
Source(int order, boolean useFirst) {

View File

@ -18,7 +18,7 @@ import io.opentelemetry.context.ContextKey;
* the context key, since otherwise instrumentation across different class loaders would use
* different context keys and not be able to share the servlet context path.
*/
public class ServletContextPath {
public final class ServletContextPath {
// Keeps track of the servlet context path that needs to be prepended to the route when updating
// the span name
@ -34,4 +34,6 @@ public class ServletContextPath {
return spanName;
}
}
private ServletContextPath() {}
}

View File

@ -120,11 +120,11 @@ public abstract class BaseTracer {
return !suppressed;
}
private boolean inClientSpan(Context context) {
private static boolean inClientSpan(Context context) {
return ClientSpan.fromContextOrNull(context) != null;
}
private boolean inServerSpan(Context context) {
private static boolean inServerSpan(Context context) {
return ServerSpan.fromContextOrNull(context) != null;
}

View File

@ -36,7 +36,7 @@ enum Jdk8AsyncSpanEndStrategy implements AsyncSpanEndStrategy {
* synchronously ends the span to avoid additional allocations and overhead registering for
* notification of completion.
*/
private boolean endSynchronously(
private static boolean endSynchronously(
CompletableFuture<?> future, BaseTracer tracer, Context context) {
if (!future.isDone()) {

View File

@ -18,7 +18,12 @@ public class AkkaAsyncChild extends ForkJoinTask implements Runnable, Callable {
private final CountDownLatch latch = new CountDownLatch(1);
public AkkaAsyncChild() {
this(true, false);
this(/* doTraceableWork= */ true, /* blockThread= */ false);
}
public AkkaAsyncChild(boolean doTraceableWork, boolean blockThread) {
this.doTraceableWork = doTraceableWork;
this.blockThread = new AtomicBoolean(blockThread);
}
@Override
@ -35,11 +40,6 @@ public class AkkaAsyncChild extends ForkJoinTask implements Runnable, Callable {
return true;
}
public AkkaAsyncChild(boolean doTraceableWork, boolean blockThread) {
this.doTraceableWork = doTraceableWork;
this.blockThread = new AtomicBoolean(blockThread);
}
public void unblock() {
blockThread.set(false);
}
@ -69,7 +69,7 @@ public class AkkaAsyncChild extends ForkJoinTask implements Runnable, Callable {
latch.countDown();
}
private void asyncChild() {
private static void asyncChild() {
tracer.spanBuilder("asyncChild").startSpan().end();
}
}

View File

@ -51,7 +51,7 @@ final class CamelEventNotifier extends EventNotifierSupport {
}
/** Camel about to send (outbound). */
private void onExchangeSending(ExchangeSendingEvent ese) {
private static void onExchangeSending(ExchangeSendingEvent ese) {
SpanDecorator sd = CamelTracer.TRACER.getSpanDecorator(ese.getEndpoint());
if (!sd.shouldStartNewSpan()) {
return;
@ -69,7 +69,7 @@ final class CamelEventNotifier extends EventNotifierSupport {
}
/** Camel finished sending (outbound). Finish span and remove it from CAMEL holder. */
private void onExchangeSent(ExchangeSentEvent event) {
private static void onExchangeSent(ExchangeSentEvent event) {
ExchangeSentEvent ese = event;
SpanDecorator sd = CamelTracer.TRACER.getSpanDecorator(ese.getEndpoint());
if (!sd.shouldStartNewSpan()) {

View File

@ -36,7 +36,7 @@ final class CamelRoutePolicy extends RoutePolicySupport {
private static final Logger LOG = LoggerFactory.getLogger(CamelRoutePolicy.class);
private Span spanOnExchangeBegin(
private static Span spanOnExchangeBegin(
Route route, Exchange exchange, SpanDecorator sd, Context parentContext, SpanKind spanKind) {
Span activeSpan = Span.fromContext(parentContext);
if (!activeSpan.getSpanContext().isValid()) {
@ -49,7 +49,7 @@ final class CamelRoutePolicy extends RoutePolicySupport {
return Span.fromContext(context);
}
private SpanKind spanKind(Context context, SpanDecorator sd) {
private static SpanKind spanKind(Context context, SpanDecorator sd) {
Span activeSpan = Span.fromContext(context);
// if there's an active span, this is not a root span which we always mark as INTERNAL
return (activeSpan.getSpanContext().isValid() ? SpanKind.INTERNAL : sd.getReceiverSpanKind());

View File

@ -93,7 +93,7 @@ class HttpSpanDecorator extends BaseSpanDecorator {
}
}
private boolean shouldSetPathAsName(CamelDirection camelDirection) {
private static boolean shouldSetPathAsName(CamelDirection camelDirection) {
return CamelDirection.INBOUND.equals(camelDirection);
}
@ -109,7 +109,8 @@ class HttpSpanDecorator extends BaseSpanDecorator {
}
}
private boolean shouldUpdateServerSpanName(Span serverSpan, CamelDirection camelDirection) {
private static boolean shouldUpdateServerSpanName(
Span serverSpan, CamelDirection camelDirection) {
return (serverSpan != null && shouldSetPathAsName(camelDirection));
}

View File

@ -89,7 +89,7 @@ class KafkaSpanDecorator extends MessagingSpanDecorator {
* @param header the header name
* @param type the class type of the exchange header
*/
private <T> String getValue(final Exchange exchange, final String header, Class<T> type) {
private static <T> String getValue(final Exchange exchange, final String header, Class<T> type) {
T value = exchange.getIn().getHeader(header, type);
return value != null ? String.valueOf(value) : exchange.getIn().getHeader(header, String.class);
}

View File

@ -18,7 +18,6 @@ import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
@Activate(group = {"consumer", "provider"})
@ -30,7 +29,7 @@ public class OpenTelemetryFilter implements Filter {
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
public Result invoke(Invoker<?> invoker, Invocation invocation) {
if (!(invocation instanceof RpcInvocation)) {
return invoker.invoke(invocation);
}

View File

@ -57,7 +57,7 @@ class CommonsHttpClientTest extends HttpClientTest<HttpMethod> implements AgentT
request = new TraceMethod(uri.toString())
break
default:
throw new RuntimeException("Unsupported method: " + method)
throw new IllegalStateException("Unsupported method: " + method)
}
headers.each { request.setRequestHeader(it.key, it.value) }
return request

View File

@ -13,6 +13,7 @@ import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.AbstractHttpMessage;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Wraps HttpHost and HttpRequest into a HttpUriRequest for tracers and injectors. */
public final class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage
@ -21,12 +22,11 @@ public final class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage
private final String method;
private final RequestLine requestLine;
private final ProtocolVersion protocolVersion;
private final java.net.URI uri;
@Nullable private final URI uri;
private final HttpRequest actualRequest;
public HostAndRequestAsHttpUriRequest(HttpHost httpHost, HttpRequest httpRequest) {
method = httpRequest.getRequestLine().getMethod();
requestLine = httpRequest.getRequestLine();
protocolVersion = requestLine.getProtocolVersion();
@ -42,7 +42,7 @@ public final class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage
}
@Override
public void abort() throws UnsupportedOperationException {
public void abort() {
throw new UnsupportedOperationException();
}
@ -72,7 +72,7 @@ public final class HostAndRequestAsHttpUriRequest extends AbstractHttpMessage
}
@Override
public java.net.URI getURI() {
public URI getURI() {
return uri;
}
}

View File

@ -123,7 +123,7 @@ final class ArmeriaHttpAttributesExtractor
return null;
}
private HttpRequest request(RequestContext ctx) {
private static HttpRequest request(RequestContext ctx) {
HttpRequest request = ctx.request();
if (request == null) {
throw new IllegalStateException(

View File

@ -67,7 +67,7 @@ public class AwsLambdaMessageTracer extends BaseTracer {
return parentContext.with(span.startSpan());
}
private void addLinkToMessageParent(SQSMessage message, SpanBuilder span) {
private static void addLinkToMessageParent(SQSMessage message, SpanBuilder span) {
String parentHeader = message.getAttributes().get(AWS_TRACE_HEADER_SQS_ATTRIBUTE_KEY);
if (parentHeader != null) {
SpanContext parentCtx =

View File

@ -26,9 +26,11 @@ import java.util.Collections;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
// Context is defined in both OTel and Lambda
@SuppressWarnings("ParameterPackage")
public class AwsLambdaTracer extends BaseTracer {
private static final MethodHandle GET_FUNCTION_ARN;
@Nullable private static final MethodHandle GET_FUNCTION_ARN;
static {
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
@ -43,7 +45,6 @@ public class AwsLambdaTracer extends BaseTracer {
GET_FUNCTION_ARN = getFunctionArn;
}
private final HttpSpanAttributes httpSpanAttributes = new HttpSpanAttributes();
// cached accountId value
private volatile String accountId;
@ -55,7 +56,7 @@ public class AwsLambdaTracer extends BaseTracer {
setCommonAttributes(span, context);
if (input instanceof APIGatewayProxyRequestEvent) {
span.setAttribute(FAAS_TRIGGER, FaasTriggerValues.HTTP);
httpSpanAttributes.onRequest(span, (APIGatewayProxyRequestEvent) input);
HttpSpanAttributes.onRequest(span, (APIGatewayProxyRequestEvent) input);
}
}
@ -72,7 +73,7 @@ public class AwsLambdaTracer extends BaseTracer {
}
@Nullable
private String getFunctionArn(Context context) {
private static String getFunctionArn(Context context) {
if (GET_FUNCTION_ARN == null) {
return null;
}
@ -101,7 +102,7 @@ public class AwsLambdaTracer extends BaseTracer {
return accountId;
}
private String spanName(Context context, Object input) {
private static String spanName(Context context, Object input) {
String name = null;
if (input instanceof APIGatewayProxyRequestEvent) {
name = ((APIGatewayProxyRequestEvent) input).getResource();
@ -126,7 +127,7 @@ public class AwsLambdaTracer extends BaseTracer {
public void onOutput(io.opentelemetry.context.Context context, Object output) {
if (output instanceof APIGatewayProxyResponseEvent) {
httpSpanAttributes.onResponse(
HttpSpanAttributes.onResponse(
Span.fromContext(context), (APIGatewayProxyResponseEvent) output);
}
}

View File

@ -14,7 +14,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class HeadersFactory {
final class HeadersFactory {
private static final Logger log = LoggerFactory.getLogger(HeadersFactory.class);
@ -35,4 +35,6 @@ class HeadersFactory {
}
return null;
}
private HeadersFactory() {}
}

View File

@ -22,7 +22,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
final class HttpSpanAttributes {
void onRequest(SpanBuilder span, APIGatewayProxyRequestEvent request) {
static void onRequest(SpanBuilder span, APIGatewayProxyRequestEvent request) {
String httpMethod = request.getHttpMethod();
if (httpMethod != null) {
span.setAttribute(HTTP_METHOD, httpMethod);
@ -39,7 +39,8 @@ final class HttpSpanAttributes {
}
}
private String getHttpUrl(APIGatewayProxyRequestEvent request, Map<String, String> headers) {
private static String getHttpUrl(
APIGatewayProxyRequestEvent request, Map<String, String> headers) {
StringBuilder str = new StringBuilder();
String scheme = headers.get("x-forwarded-proto");
@ -70,10 +71,12 @@ final class HttpSpanAttributes {
return str.toString();
}
void onResponse(Span span, APIGatewayProxyResponseEvent response) {
static void onResponse(Span span, APIGatewayProxyResponseEvent response) {
Integer statusCode = response.getStatusCode();
if (statusCode != null) {
span.setAttribute(HTTP_STATUS_CODE, statusCode);
}
}
private HttpSpanAttributes() {}
}

View File

@ -17,7 +17,7 @@ import java.util.Collections;
import java.util.Locale;
import java.util.Map;
public class ParentContextExtractor {
public final class ParentContextExtractor {
private static final String AWS_TRACE_HEADER_ENV_KEY = "_X_AMZN_TRACE_ID";
@ -73,4 +73,6 @@ public class ParentContextExtractor {
return map.get(s.toLowerCase(Locale.ROOT));
}
}
private ParentContextExtractor() {}
}

View File

@ -38,7 +38,7 @@ public class TracingRequestStreamWrapper extends TracingRequestStreamHandler {
throws IOException {
if (!(wrappedLambda.getTargetObject() instanceof RequestStreamHandler)) {
throw new RuntimeException(
throw new IllegalStateException(
wrappedLambda.getTargetClass().getName() + " is not an instance of RequestStreamHandler");
}

View File

@ -58,11 +58,11 @@ abstract class TracingRequestWrapperBase<I, O> extends TracingRequestHandler<I,
try {
result = (O) targetMethod.invoke(wrappedLambda.getTargetObject(), parameters);
} catch (IllegalAccessException e) {
throw new RuntimeException("Method is inaccessible", e);
throw new IllegalStateException("Method is inaccessible", e);
} catch (InvocationTargetException e) {
throw (e.getCause() instanceof RuntimeException
? (RuntimeException) e.getCause()
: new RuntimeException(e.getTargetException()));
: new IllegalStateException(e.getTargetException()));
}
return result;
}

View File

@ -32,12 +32,12 @@ class WrappedLambda {
String lambdaHandler = System.getenv(OTEL_LAMBDA_HANDLER_ENV_KEY);
if (lambdaHandler == null || lambdaHandler.isEmpty()) {
throw new RuntimeException(OTEL_LAMBDA_HANDLER_ENV_KEY + " was not specified.");
throw new IllegalStateException(OTEL_LAMBDA_HANDLER_ENV_KEY + " was not specified.");
}
// expect format to be package.ClassName::methodName
String[] split = lambdaHandler.split("::");
if (split.length != 2) {
throw new RuntimeException(
throw new IllegalStateException(
lambdaHandler
+ " is not a valid handler name. Expected format: package.ClassName::methodName");
}
@ -48,7 +48,7 @@ class WrappedLambda {
targetClass = Class.forName(handlerClassName);
} catch (ClassNotFoundException e) {
// no class found
throw new RuntimeException(handlerClassName + " not found in classpath");
throw new IllegalStateException(handlerClassName + " not found in classpath", e);
}
return new WrappedLambda(targetClass, targetMethodName);
}
@ -60,26 +60,26 @@ class WrappedLambda {
}
private Object instantiateTargetClass() {
Object targetObject;
try {
Constructor<?> ctor = targetClass.getConstructor();
targetObject = ctor.newInstance();
} catch (NoSuchMethodException e) {
throw new RuntimeException(
targetClass.getName() + " does not have an appropriate constructor");
throw new IllegalStateException(
targetClass.getName() + " does not have an appropriate constructor", e);
} catch (InstantiationException e) {
throw new RuntimeException(targetClass.getName() + " cannot be an abstract class");
throw new IllegalStateException(targetClass.getName() + " cannot be an abstract class", e);
} catch (IllegalAccessException e) {
throw new RuntimeException(targetClass.getName() + "'s constructor is not accessible");
throw new IllegalStateException(
targetClass.getName() + "'s constructor is not accessible", e);
} catch (InvocationTargetException e) {
throw new RuntimeException(
targetClass.getName() + " threw an exception from the constructor");
throw new IllegalStateException(
targetClass.getName() + " threw an exception from the constructor", e);
}
return targetObject;
}
private boolean isLastParameterContext(Parameter[] parameters) {
private static boolean isLastParameterContext(Parameter[] parameters) {
if (parameters.length == 0) {
return false;
}
@ -92,10 +92,9 @@ class WrappedLambda {
Optional<Method> firstOptional =
methods.stream()
.filter((Method m) -> m.getName().equals(targetMethodName))
.sorted(this::methodComparator)
.findFirst();
.min(WrappedLambda::methodComparator);
if (!firstOptional.isPresent()) {
throw new RuntimeException("Method " + targetMethodName + " not found");
throw new IllegalStateException("Method " + targetMethodName + " not found");
}
return firstOptional.get();
}
@ -114,7 +113,7 @@ class WrappedLambda {
- handleA(String, String, Integer), handleB(String, String, Context) - handleB is selected (has Context as the last parameter)
- generic method handleG(T, U, Context), implementation (T, U - String) handleA(String, String, Context), bridge method handleB(Object, Object, Context) - handleA is selected (non-bridge)
*/
private int methodComparator(Method a, Method b) {
private static int methodComparator(Method a, Method b) {
// greater number of params wins
if (a.getParameterCount() != b.getParameterCount()) {
return b.getParameterCount() - a.getParameterCount();
@ -128,7 +127,7 @@ class WrappedLambda {
return onlyOneIsBridgeMethod(a, b);
}
private int onlyOneIsBridgeMethod(Method first, Method second) {
private static int onlyOneIsBridgeMethod(Method first, Method second) {
boolean firstBridge = first.isBridge();
boolean secondBridge = second.isBridge();
if (firstBridge && !secondBridge) {
@ -139,7 +138,7 @@ class WrappedLambda {
return 0;
}
private int onlyOneHasContextAsLastParam(Method first, Method second) {
private static int onlyOneHasContextAsLastParam(Method first, Method second) {
boolean firstCtx = isLastParameterContext(first.getParameters());
boolean secondCtx = isLastParameterContext(second.getParameters());
// only one of the methods has last param context ?

View File

@ -28,7 +28,7 @@ class TracingRequestApiGatewayWrapperTest extends TracingRequestWrapperTestBase
} else if (input.getBody() == "empty") {
return new APIGatewayProxyResponseEvent()
}
throw new RuntimeException("bad request")
throw new IllegalStateException("bad request")
}
}

View File

@ -19,11 +19,11 @@ import org.junit.Test;
public class TracingRequestHandlerTest {
private Response<SendMessageResult> response(Request request) {
private static Response<SendMessageResult> response(Request request) {
return new Response<>(new SendMessageResult(), new HttpResponse(request, new HttpGet()));
}
private Request<SendMessageRequest> request() {
private static Request<SendMessageRequest> request() {
Request<SendMessageRequest> request = new DefaultRequest<>(new SendMessageRequest(), "test");
request.setEndpoint(URI.create("http://test.uri"));
return request;

View File

@ -77,7 +77,7 @@ class Aws1ClientTest extends AbstractAws1ClientTest implements AgentTestTrait {
def client = new AmazonS3Client(CREDENTIALS_PROVIDER_CHAIN)
client.addRequestHandler(new RequestHandler2() {
void beforeRequest(Request<?> request) {
throw new RuntimeException("bad handler")
throw new IllegalStateException("bad handler")
}
})
@ -86,7 +86,7 @@ class Aws1ClientTest extends AbstractAws1ClientTest implements AgentTestTrait {
then:
!Span.current().getSpanContext().isValid()
thrown RuntimeException
thrown IllegalStateException
assertTraces(1) {
trace(0, 1) {
@ -94,7 +94,7 @@ class Aws1ClientTest extends AbstractAws1ClientTest implements AgentTestTrait {
name "S3.HeadBucket"
kind SpanKind.CLIENT
status ERROR
errorEvent RuntimeException, "bad handler"
errorEvent IllegalStateException, "bad handler"
hasNoParent()
attributes {
"${SemanticAttributes.NET_TRANSPORT.key}" IP_TCP

View File

@ -193,7 +193,7 @@ class Aws0ClientTest extends AgentInstrumentationSpecification {
def client = new AmazonS3Client(CREDENTIALS_PROVIDER_CHAIN)
client.addRequestHandler(new RequestHandler2() {
void beforeRequest(Request<?> request) {
throw new RuntimeException("bad handler")
throw new IllegalStateException("bad handler")
}
})
@ -202,7 +202,7 @@ class Aws0ClientTest extends AgentInstrumentationSpecification {
then:
!Span.current().getSpanContext().isValid()
thrown RuntimeException
thrown IllegalStateException
assertTraces(1) {
trace(0, 1) {
@ -210,7 +210,7 @@ class Aws0ClientTest extends AgentInstrumentationSpecification {
name "S3.GetObject"
kind CLIENT
status ERROR
errorEvent RuntimeException, "bad handler"
errorEvent IllegalStateException, "bad handler"
hasNoParent()
attributes {
"${SemanticAttributes.NET_TRANSPORT.key}" IP_TCP

View File

@ -40,7 +40,7 @@ final class TracingRequestHandler extends RequestHandler2 {
request.addHandlerContext(CONTEXT, context);
}
private boolean isSqsProducer(AmazonWebServiceRequest request) {
private static boolean isSqsProducer(AmazonWebServiceRequest request) {
return request
.getClass()
.getName()

View File

@ -22,7 +22,7 @@ final class AwsJsonProtocolFactoryAccess {
private static final OperationInfo OPERATION_INFO =
OperationInfo.builder().hasPayloadMembers(true).httpMethod(SdkHttpMethod.POST).build();
private static final MethodHandle INVOKE_CREATE_PROTOCOL_MARSHALLER;
@Nullable private static final MethodHandle INVOKE_CREATE_PROTOCOL_MARSHALLER;
static {
MethodHandle invokeCreateProtocolMarshaller = null;

View File

@ -12,7 +12,7 @@ import java.util.concurrent.ConcurrentHashMap;
class MethodHandleFactory {
private String lowerCase(String string) {
private static String unCapitalize(String string) {
return string.substring(0, 1).toLowerCase(Locale.ROOT) + string.substring(1);
}
@ -29,7 +29,8 @@ class MethodHandleFactory {
MethodHandle methodHandle = getterCache.get(clazz).get(fieldName);
if (methodHandle == null) {
// getter in AWS SDK is lowercased field name
methodHandle = MethodHandles.publicLookup().unreflect(clazz.getMethod(lowerCase(fieldName)));
methodHandle =
MethodHandles.publicLookup().unreflect(clazz.getMethod(unCapitalize(fieldName)));
getterCache.get(clazz).put(fieldName, methodHandle);
}
return methodHandle;

View File

@ -42,7 +42,7 @@ class Serializer {
}
@Nullable
private String serialize(SdkPojo sdkPojo) {
private static String serialize(SdkPojo sdkPojo) {
ProtocolMarshaller<SdkHttpFullRequest> marshaller =
AwsJsonProtocolFactoryAccess.createMarshaller();
if (marshaller == null) {

View File

@ -163,7 +163,7 @@ final class TracingExecutionInterceptor implements ExecutionInterceptor {
tracer.endExceptionally(otelContext, context.exception());
}
private void clearAttributes(ExecutionAttributes executionAttributes) {
private static void clearAttributes(ExecutionAttributes executionAttributes) {
Scope scope = executionAttributes.getAttribute(SCOPE_ATTRIBUTE);
if (scope != null) {
scope.close();

View File

@ -8,9 +8,9 @@ package io.opentelemetry.instrumentation.awssdk.v2_2;
import static io.opentelemetry.instrumentation.awssdk.v2_2.AwsSdkRequest.BatchWriteItem;
import static io.opentelemetry.instrumentation.awssdk.v2_2.AwsSdkRequest.UpdateTable;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.mock;
import static org.mockito.BDDMockito.verify;
import static org.mockito.BDDMockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import io.opentelemetry.api.trace.Span;
import java.util.Collection;

View File

@ -208,7 +208,7 @@ public class TracingSession implements Session {
return query == null ? "" : query;
}
private void addCallbackToEndSpan(
private static void addCallbackToEndSpan(
ResultSetFuture future, Context context, CassandraRequest request) {
Futures.addCallback(
future,

View File

@ -10,14 +10,15 @@ import io.opentelemetry.instrumentation.api.db.SqlStatementSanitizer;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import org.checkerframework.checker.nullness.qual.Nullable;
public final class CouchbaseQuerySanitizer {
private static final Class<?> QUERY_CLASS;
private static final Class<?> STATEMENT_CLASS;
private static final Class<?> N1QL_QUERY_CLASS;
private static final MethodHandle N1QL_GET_STATEMENT;
private static final Class<?> ANALYTICS_QUERY_CLASS;
private static final MethodHandle ANALYTICS_GET_STATEMENT;
@Nullable private static final Class<?> QUERY_CLASS;
@Nullable private static final Class<?> STATEMENT_CLASS;
@Nullable private static final Class<?> N1QL_QUERY_CLASS;
@Nullable private static final MethodHandle N1QL_GET_STATEMENT;
@Nullable private static final Class<?> ANALYTICS_QUERY_CLASS;
@Nullable private static final MethodHandle ANALYTICS_GET_STATEMENT;
static {
Class<?> queryClass;

View File

@ -18,7 +18,12 @@ public class JavaAsyncChild extends ForkJoinTask implements Runnable, Callable {
private final CountDownLatch latch = new CountDownLatch(1);
public JavaAsyncChild() {
this(true, false);
this(/* doTraceableWork= */ true, /* blockThread= */ false);
}
public JavaAsyncChild(boolean doTraceableWork, boolean blockThread) {
this.doTraceableWork = doTraceableWork;
this.blockThread = new AtomicBoolean(blockThread);
}
@Override
@ -35,11 +40,6 @@ public class JavaAsyncChild extends ForkJoinTask implements Runnable, Callable {
return true;
}
public JavaAsyncChild(boolean doTraceableWork, boolean blockThread) {
this.doTraceableWork = doTraceableWork;
this.blockThread = new AtomicBoolean(blockThread);
}
public void unblock() {
blockThread.set(false);
}
@ -69,7 +69,7 @@ public class JavaAsyncChild extends ForkJoinTask implements Runnable, Callable {
latch.countDown();
}
private void asyncChild() {
private static void asyncChild() {
tracer.spanBuilder("asyncChild").startSpan().end();
}
}

View File

@ -69,21 +69,20 @@ public class ExternalAnnotationInstrumentation implements TypeInstrumentation {
private static final String TRACE_ANNOTATED_METHODS_EXCLUDE_CONFIG =
"otel.instrumentation.external-annotations.exclude-methods";
private final Set<String> additionalTraceAnnotations;
private final ElementMatcher.Junction<ClassLoader> classLoaderOptimization;
private final ElementMatcher.Junction<NamedElement> traceAnnotationMatcher;
/** This matcher matches all methods that should be excluded from transformation. */
private final ElementMatcher.Junction<MethodDescription> excludedMethodsMatcher;
public ExternalAnnotationInstrumentation() {
additionalTraceAnnotations = configureAdditionalTraceAnnotations(Config.get());
Set<String> additionalTraceAnnotations = configureAdditionalTraceAnnotations(Config.get());
if (additionalTraceAnnotations.isEmpty()) {
classLoaderOptimization = none();
traceAnnotationMatcher = none();
} else {
ElementMatcher.Junction<ClassLoader> classLoaderMatcher = null;
ElementMatcher.Junction<NamedElement> methodTraceMatcher = null;
ElementMatcher.Junction<ClassLoader> classLoaderMatcher = none();
ElementMatcher.Junction<NamedElement> methodTraceMatcher = none();
for (String annotationName : additionalTraceAnnotations) {
if (methodTraceMatcher == null) {
classLoaderMatcher = hasClassesNamed(annotationName);

View File

@ -8,6 +8,8 @@ package io.opentelemetry.test.annotation;
import io.opentelemetry.api.trace.Span;
import java.util.concurrent.Callable;
// To better see which library is tested
@SuppressWarnings("UnnecessarilyFullyQualified")
public class SayTracedHello {
@com.appoptics.api.ext.LogMethod
@ -78,7 +80,7 @@ public class SayTracedHello {
@io.opentracing.contrib.dropwizard.Trace
public static String sayError() {
throw new RuntimeException();
throw new IllegalStateException();
}
public static String fromCallable() {

View File

@ -6,6 +6,7 @@
package io.opentelemetry.instrumentation.guava;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.Uninterruptibles;
import io.opentelemetry.context.Context;
import io.opentelemetry.instrumentation.api.tracer.BaseTracer;
import io.opentelemetry.instrumentation.api.tracer.async.AsyncSpanEndStrategy;
@ -29,9 +30,9 @@ public enum GuavaAsyncSpanEndStrategy implements AsyncSpanEndStrategy {
return future;
}
private void endSpan(BaseTracer tracer, Context context, ListenableFuture<?> future) {
private static void endSpan(BaseTracer tracer, Context context, ListenableFuture<?> future) {
try {
future.get();
Uninterruptibles.getUninterruptibly(future);
tracer.end(context);
} catch (Throwable exception) {
tracer.endExceptionally(context, exception);

View File

@ -134,7 +134,7 @@ class GwtTest extends AgentInstrumentationSpecification implements HttpServerTes
assertTraces(1) {
trace(0, 2) {
serverSpan(it, 0, getContextPath() + "/greeting/greet")
basicSpan(it, 1, "MessageServiceImpl.sendMessage", span(0), new IllegalArgumentException())
basicSpan(it, 1, "MessageServiceImpl.sendMessage", span(0), new IOException())
}
}

View File

@ -13,6 +13,7 @@ import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import java.io.IOException;
import test.gwt.shared.MessageService;
import test.gwt.shared.MessageServiceAsync;
@ -49,21 +50,25 @@ public class GreetingEntryPoint implements EntryPoint {
messageLabel.setText("");
messageLabel.setStyleName("");
messageServiceAsync.sendMessage(
message,
new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
messageLabel.setText("Error");
messageLabel.addStyleName("error.received");
}
try {
messageServiceAsync.sendMessage(
message,
new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
messageLabel.setText("Error");
messageLabel.addStyleName("error.received");
}
@Override
public void onSuccess(String result) {
messageLabel.setText(result);
messageLabel.addStyleName("message.received");
}
});
@Override
public void onSuccess(String result) {
messageLabel.setText(result);
messageLabel.addStyleName("message.received");
}
});
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}

View File

@ -6,6 +6,7 @@
package test.gwt.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.io.IOException;
import test.gwt.shared.MessageService;
/** The server-side implementation of the RPC service. */
@ -13,9 +14,9 @@ import test.gwt.shared.MessageService;
public class MessageServiceImpl extends RemoteServiceServlet implements MessageService {
@Override
public String sendMessage(String message) throws IllegalArgumentException {
public String sendMessage(String message) throws IOException {
if (message == null || "Error".equals(message)) {
throw new IllegalArgumentException();
throw new IOException();
}
return "Hello, " + message;

View File

@ -7,9 +7,10 @@ package test.gwt.shared;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import java.io.IOException;
/** The client-side stub for the RPC service. */
@RemoteServiceRelativePath("greet")
public interface MessageService extends RemoteService {
String sendMessage(String message) throws IllegalArgumentException;
String sendMessage(String message) throws IOException;
}

View File

@ -6,8 +6,9 @@
package test.gwt.shared;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.io.IOException;
/** The async counterpart of <code>MessageService</code>. */
public interface MessageServiceAsync {
void sendMessage(String input, AsyncCallback<String> callback) throws IllegalArgumentException;
void sendMessage(String input, AsyncCallback<String> callback) throws IOException;
}

View File

@ -52,7 +52,7 @@ public class PersistenceConfig {
return dataSource;
}
private Properties additionalProperties() {
private static Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.hbm2ddl.auto", "create");

View File

@ -52,7 +52,7 @@ public class PersistenceConfig {
return dataSource;
}
private Properties additionalProperties() {
private static Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.hbm2ddl.auto", "create");

View File

@ -19,7 +19,7 @@ import java.util.Set;
import java.util.function.Supplier;
import org.checkerframework.checker.nullness.qual.Nullable;
public class SessionMethodUtils {
public final class SessionMethodUtils {
public static final Set<String> SCOPE_ONLY_METHODS =
new HashSet<>(Arrays.asList("immediateLoad", "internalLoad"));
@ -107,4 +107,6 @@ public class SessionMethodUtils {
targetContextStore.putIfAbsent(target, sessionContext);
}
private SessionMethodUtils() {}
}

View File

@ -15,7 +15,8 @@ import org.apache.cxf.message.Message;
public final class CxfClientUtil {
public static void handleException(Message message, Throwable throwable) {
ClientRequestContext context = new ClientRequestContextImpl(message, false);
ClientRequestContext context =
new ClientRequestContextImpl(message, /* responseContext= */ false);
Object prop = context.getProperty(ClientTracingFilter.CONTEXT_PROPERTY_NAME);
if (prop instanceof Context) {
tracer().endExceptionally((Context) prop, throwable);

View File

@ -57,14 +57,14 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return parentContext.with(span);
}
private void setCodeAttributes(SpanBuilder spanBuilder, Class<?> target, Method method) {
private static void setCodeAttributes(SpanBuilder spanBuilder, Class<?> target, Method method) {
spanBuilder.setAttribute(SemanticAttributes.CODE_NAMESPACE, target.getName());
if (method != null) {
spanBuilder.setAttribute(SemanticAttributes.CODE_FUNCTION, method.getName());
}
}
private void updateServerSpanName(Context context, Span span, String spanName) {
private static void updateServerSpanName(Context context, Span span, String spanName) {
if (!spanName.isEmpty()) {
span.updateName(ServletContextPath.prepend(context, spanName));
}
@ -111,7 +111,7 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return spanName;
}
private String locateHttpMethod(Method method) {
private static String locateHttpMethod(Method method) {
String httpMethod = null;
for (Annotation ann : method.getDeclaredAnnotations()) {
if (ann.annotationType().getAnnotation(HttpMethod.class) != null) {
@ -121,11 +121,11 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return httpMethod;
}
private Path findMethodPath(Method method) {
private static Path findMethodPath(Method method) {
return method.getAnnotation(Path.class);
}
private Path findClassPath(Class<?> target) {
private static Path findClassPath(Class<?> target) {
for (Class<?> currentClass : new ClassHierarchyIterable(target)) {
Path annotation = currentClass.getAnnotation(Path.class);
if (annotation != null) {
@ -137,7 +137,7 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return null;
}
private Method findMatchingMethod(Method baseMethod, Method[] methods) {
private static Method findMatchingMethod(Method baseMethod, Method[] methods) {
nextMethod:
for (Method method : methods) {
if (!baseMethod.getReturnType().equals(method.getReturnType())) {
@ -163,7 +163,7 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return null;
}
private String buildSpanName(Path classPath, Path methodPath) {
private static String buildSpanName(Path classPath, Path methodPath) {
String spanName;
StringBuilder spanNameBuilder = new StringBuilder();
boolean skipSlash = false;

View File

@ -73,13 +73,13 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
}
}
private void updateSpanName(Span span, String spanName) {
private static void updateSpanName(Span span, String spanName) {
if (!spanName.isEmpty()) {
span.updateName(spanName);
}
}
private void setCodeAttributes(SpanBuilder spanBuilder, Class<?> target, Method method) {
private static void setCodeAttributes(SpanBuilder spanBuilder, Class<?> target, Method method) {
spanBuilder.setAttribute(SemanticAttributes.CODE_NAMESPACE, target.getName());
if (method != null) {
spanBuilder.setAttribute(SemanticAttributes.CODE_FUNCTION, method.getName());
@ -143,7 +143,7 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return spanName;
}
private String locateHttpMethod(Method method) {
private static String locateHttpMethod(Method method) {
String httpMethod = null;
for (Annotation ann : method.getDeclaredAnnotations()) {
if (ann.annotationType().getAnnotation(HttpMethod.class) != null) {
@ -153,11 +153,11 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return httpMethod;
}
private Path findMethodPath(Method method) {
private static Path findMethodPath(Method method) {
return method.getAnnotation(Path.class);
}
private Path findClassPath(Class<?> target) {
private static Path findClassPath(Class<?> target) {
for (Class<?> currentClass : new ClassHierarchyIterable(target)) {
Path annotation = currentClass.getAnnotation(Path.class);
if (annotation != null) {
@ -169,7 +169,7 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return null;
}
private Method findMatchingMethod(Method baseMethod, Method[] methods) {
private static Method findMatchingMethod(Method baseMethod, Method[] methods) {
nextMethod:
for (Method method : methods) {
if (!baseMethod.getReturnType().equals(method.getReturnType())) {
@ -195,7 +195,7 @@ public class JaxRsAnnotationsTracer extends BaseTracer {
return null;
}
private String buildSpanName(Path classPath, Path methodPath) {
private static String buildSpanName(Path classPath, Path methodPath) {
String spanName;
StringBuilder spanNameBuilder = new StringBuilder();
boolean skipSlash = false;

View File

@ -10,6 +10,7 @@ import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -17,7 +18,7 @@ public final class JdbcUtils {
private static final Logger log = LoggerFactory.getLogger(JdbcUtils.class);
private static Field c3poField = null;
@Nullable private static Field c3poField = null;
/** Returns the unwrapped connection or null if exception was thrown. */
public static Connection connectionFromStatement(Statement statement) {

View File

@ -29,7 +29,7 @@ import java.util.concurrent.Executor
class TestConnection implements Connection {
TestConnection(boolean throwException) {
if (throwException) {
throw new RuntimeException("connection exception")
throw new IllegalStateException("connection exception")
}
}

View File

@ -18,13 +18,13 @@ public class Jetty11HttpServerTracer extends JakartaServletHttpServerTracer {
}
public Context startServerSpan(HttpServletRequest request) {
return startSpan(request, "HTTP " + request.getMethod(), false);
return startSpan(request, "HTTP " + request.getMethod(), /* servlet= */ false);
}
@Override
protected Context customizeContext(Context context, HttpServletRequest request) {
context = super.customizeContext(context, request);
return AppServerBridge.init(context, false);
return AppServerBridge.init(context, /* shouldRecordException= */ false);
}
@Override

View File

@ -18,13 +18,13 @@ public class Jetty8HttpServerTracer extends Servlet3HttpServerTracer {
}
public Context startServerSpan(HttpServletRequest request) {
return startSpan(request, "HTTP " + request.getMethod(), false);
return startSpan(request, "HTTP " + request.getMethod(), /* servlet= */ false);
}
@Override
protected Context customizeContext(Context context, HttpServletRequest request) {
context = super.customizeContext(context, request);
return AppServerBridge.init(context, false);
return AppServerBridge.init(context, /* shouldRecordException= */ false);
}
@Override

View File

@ -18,7 +18,12 @@ public class JavaAsyncChild extends ForkJoinTask implements Runnable, Callable {
private final CountDownLatch latch = new CountDownLatch(1);
public JavaAsyncChild() {
this(true, false);
this(/* doTraceableWork= */ true, /* blockThread= */ false);
}
public JavaAsyncChild(boolean doTraceableWork, boolean blockThread) {
this.doTraceableWork = doTraceableWork;
this.blockThread = new AtomicBoolean(blockThread);
}
@Override
@ -35,11 +40,6 @@ public class JavaAsyncChild extends ForkJoinTask implements Runnable, Callable {
return true;
}
public JavaAsyncChild(boolean doTraceableWork, boolean blockThread) {
this.doTraceableWork = doTraceableWork;
this.blockThread = new AtomicBoolean(blockThread);
}
public void unblock() {
blockThread.set(false);
}
@ -69,7 +69,7 @@ public class JavaAsyncChild extends ForkJoinTask implements Runnable, Callable {
latch.countDown();
}
private void asyncChild() {
private static void asyncChild() {
tracer.spanBuilder("asyncChild").startSpan().end();
}
}

View File

@ -49,7 +49,13 @@ class MessageWithDestinationTest {
MessageWithDestination.create(message, MessageOperation.SEND, null, START_TIME);
// then
assertMessage(MessageOperation.SEND, "unknown", "unknown", false, START_TIME, result);
assertMessage(
MessageOperation.SEND,
"unknown",
"unknown",
/* expectedTemporary= */ false,
START_TIME,
result);
}
@Test
@ -62,7 +68,13 @@ class MessageWithDestinationTest {
MessageWithDestination.create(message, MessageOperation.SEND, destination, START_TIME);
// then
assertMessage(MessageOperation.SEND, "unknown", "unknown", false, START_TIME, result);
assertMessage(
MessageOperation.SEND,
"unknown",
"unknown",
/* expectedTemporary= */ false,
START_TIME,
result);
}
@ParameterizedTest

View File

@ -27,7 +27,7 @@ public final class MessagePropertyGetter implements TextMapGetter<MessageWithDes
try {
value = carrier.getMessage().getObjectProperty(propName);
} catch (JMSException e) {
throw new RuntimeException(e);
throw new IllegalStateException(e);
}
if (value instanceof String) {
return (String) value;

View File

@ -93,7 +93,8 @@ public final class MessageWithDestination {
if (jmsDestination instanceof Topic) {
return createMessageWithTopic(message, operation, (Topic) jmsDestination, startTime);
}
return new MessageWithDestination(message, operation, "unknown", "unknown", false, startTime);
return new MessageWithDestination(
message, operation, "unknown", "unknown", /* temporary= */ false, startTime);
}
private static MessageWithDestination createMessageWithQueue(

View File

@ -9,6 +9,7 @@ import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import java.util.Iterator;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -23,9 +24,9 @@ public class TracingIterator implements Iterator<ConsumerRecord<?, ?>> {
* Note: this may potentially create problems if this iterator is used from different threads. But
* at the moment we cannot do much about this.
*/
private Context currentContext;
@Nullable private Context currentContext;
private Scope currentScope;
@Nullable private Scope currentScope;
public TracingIterator(
Iterator<ConsumerRecord<?, ?>> delegateIterator, KafkaConsumerTracer tracer) {

View File

@ -39,7 +39,7 @@ class KubernetesRequestDigest {
return new KubernetesRequestDigest(
urlPath,
false,
/* isNonResourceRequest= */ false,
resourceMeta,
KubernetesVerb.of(
request.method(), hasNamePathParameter(resourceMeta), hasWatchParameter(request)));
@ -49,8 +49,7 @@ class KubernetesRequestDigest {
}
private static KubernetesRequestDigest nonResource(String urlPath) {
KubernetesRequestDigest digest = new KubernetesRequestDigest(urlPath, true, null, null);
return digest;
return new KubernetesRequestDigest(urlPath, /* isNonResourceRequest= */ true, null, null);
}
public static boolean isResourceRequest(String urlPath) {

View File

@ -58,7 +58,7 @@ public class LettuceFluxTerminationRunnable implements Consumer<Signal<?>>, Runn
public void accept(Signal signal) {
if (SignalType.ON_COMPLETE.equals(signal.getType())
|| SignalType.ON_ERROR.equals(signal.getType())) {
finishSpan(false, signal.getThrowable());
finishSpan(/* isCommandCancelled= */ false, signal.getThrowable());
} else if (SignalType.ON_NEXT.equals(signal.getType())) {
++numResults;
}
@ -66,7 +66,7 @@ public class LettuceFluxTerminationRunnable implements Consumer<Signal<?>>, Runn
@Override
public void run() {
finishSpan(true, null);
finishSpan(/* isCommandCancelled= */ true, null);
}
public static class FluxOnSubscribeConsumer implements Consumer<Subscription> {

View File

@ -17,7 +17,7 @@ public class LibertyHttpServerTracer extends Servlet3HttpServerTracer {
}
public Context startSpan(HttpServletRequest request) {
return startSpan(request, "HTTP " + request.getMethod(), false);
return startSpan(request, "HTTP " + request.getMethod(), /* servlet= */ false);
}
@Override

View File

@ -33,7 +33,7 @@ public class ListAppender extends AbstractAppender {
private final List<LoggedEvent> events = Collections.synchronizedList(new ArrayList<>());
public ListAppender() {
super("ListAppender", null, null, true);
super("ListAppender", null, null, /* ignoreExceptions= */ true);
}
public List<LoggedEvent> getEvents() {

View File

@ -10,12 +10,13 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggerContextVO;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Marker;
final class LoggingEventWrapper implements ILoggingEvent {
private final ILoggingEvent event;
private final Map<String, String> mdcPropertyMap;
private final LoggerContextVO vo;
@Nullable private final LoggerContextVO vo;
LoggingEventWrapper(ILoggingEvent event, Map<String, String> mdcPropertyMap) {
this.event = event;

View File

@ -60,7 +60,7 @@ final class MongoClientTracer
jsonWriterSettings != null
? new JsonWriter(stringWriter, jsonWriterSettings)
: new JsonWriter(stringWriter);
writeScrubbed(command, jsonWriter, true);
writeScrubbed(command, jsonWriter, /* isRoot= */ true);
// If using MongoDB driver >= 3.7, the substring invocation will be a no-op due to use of
// JsonWriterSettings.Builder.maxLength in the static initializer for JSON_WRITER_SETTINGS
StringBuffer buf = stringWriter.getBuffer();
@ -147,7 +147,7 @@ final class MongoClientTracer
}
@Nullable
private JsonWriterSettings createJsonWriterSettings(int maxNormalizedQueryLength) {
private static JsonWriterSettings createJsonWriterSettings(int maxNormalizedQueryLength) {
JsonWriterSettings settings = null;
try {
// The static JsonWriterSettings.builder() method was introduced in the 3.5 release
@ -234,7 +234,7 @@ final class MongoClientTracer
private static boolean writeScrubbed(BsonValue origin, JsonWriter writer) {
if (origin.isDocument()) {
return writeScrubbed(origin.asDocument(), writer, false);
return writeScrubbed(origin.asDocument(), writer, /* isRoot= */ false);
} else if (origin.isArray()) {
return writeScrubbed(origin.asArray(), writer);
} else {

View File

@ -8,7 +8,7 @@ package io.opentelemetry.instrumentation.netty.v4_1;
import io.netty.util.AttributeKey;
import io.opentelemetry.context.Context;
public class AttributeKeys {
public final class AttributeKeys {
public static final AttributeKey<Context> CONNECT_CONTEXT =
AttributeKey.valueOf(AttributeKeys.class, "connect-context");
@ -26,4 +26,6 @@ public class AttributeKeys {
public static final AttributeKey<Context> CLIENT_PARENT_CONTEXT =
AttributeKey.valueOf(AttributeKeys.class, "client-parent-context");
private AttributeKeys() {}
}

View File

@ -11,6 +11,8 @@ import application.io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.javaagent.instrumentation.opentelemetryapi.context.propagation.ApplicationContextPropagators;
import io.opentelemetry.javaagent.instrumentation.opentelemetryapi.trace.ApplicationTracerProvider;
// Our convention for accessing agent package
@SuppressWarnings("UnnecessarilyFullyQualified")
public class ApplicationOpenTelemetry implements OpenTelemetry {
public static final OpenTelemetry INSTANCE = new ApplicationOpenTelemetry();

View File

@ -16,6 +16,8 @@ import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
// Our convention for accessing agent package
@SuppressWarnings("UnnecessarilyFullyQualified")
public class OpenTelemetryInstrumentation implements TypeInstrumentation {
@Override

View File

@ -14,6 +14,7 @@ import application.io.opentelemetry.context.Scope;
import io.opentelemetry.javaagent.instrumentation.opentelemetryapi.baggage.BaggageBridging;
import io.opentelemetry.javaagent.instrumentation.opentelemetryapi.trace.Bridging;
import java.lang.reflect.Field;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -31,6 +32,8 @@ import org.slf4j.LoggerFactory;
* always stores and retrieves them from the agent context, even when accessed from the application.
* All other accesses are to the concrete application context.
*/
// Annotation doesn't work on some fields due to fully qualified name (no clue why it matters...)
@SuppressWarnings("FieldMissingNullable")
public class AgentContextStorage implements ContextStorage, AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(AgentContextStorage.class);
@ -53,11 +56,11 @@ public class AgentContextStorage implements ContextStorage, AutoCloseable {
static final io.opentelemetry.context.ContextKey<io.opentelemetry.api.trace.Span>
AGENT_SPAN_CONTEXT_KEY;
static final ContextKey<Span> APPLICATION_SPAN_CONTEXT_KEY;
@Nullable static final ContextKey<Span> APPLICATION_SPAN_CONTEXT_KEY;
static final io.opentelemetry.context.ContextKey<io.opentelemetry.api.baggage.Baggage>
AGENT_BAGGAGE_CONTEXT_KEY;
static final ContextKey<Baggage> APPLICATION_BAGGAGE_CONTEXT_KEY;
@Nullable static final ContextKey<Baggage> APPLICATION_BAGGAGE_CONTEXT_KEY;
static {
io.opentelemetry.context.ContextKey<io.opentelemetry.api.trace.Span> agentSpanContextKey;

View File

@ -29,6 +29,8 @@ import org.slf4j.LoggerFactory;
*
* <p>Also see comments in this module's gradle file.
*/
// Our convention for accessing agent package
@SuppressWarnings("UnnecessarilyFullyQualified")
public class Bridging {
private static final Logger log = LoggerFactory.getLogger(Bridging.class);
@ -135,10 +137,9 @@ public class Bridging {
return io.opentelemetry.api.common.AttributeKey.longArrayKey(applicationKey.getKey());
case DOUBLE_ARRAY:
return io.opentelemetry.api.common.AttributeKey.doubleArrayKey(applicationKey.getKey());
default:
log.debug("unexpected attribute key type: {}", applicationKey.getType());
return null;
}
log.debug("unexpected attribute key type: {}", applicationKey.getType());
return null;
}
public static io.opentelemetry.api.trace.StatusCode toAgent(StatusCode applicationStatus) {

View File

@ -17,6 +17,8 @@ import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
// Our convention for accessing agent package
@SuppressWarnings("UnnecessarilyFullyQualified")
public class OpenTelemetryMetricsInstrumentation implements TypeInstrumentation {
@Override

View File

@ -10,6 +10,8 @@ import application.io.opentelemetry.api.metrics.DoubleSumObserverBuilder;
import application.io.opentelemetry.api.metrics.common.Labels;
import java.util.function.Consumer;
// For observers, which have no API, there might be a better pattern than wrapping.
@SuppressWarnings("FieldCanBeLocal")
class ApplicationDoubleSumObserver implements DoubleSumObserver {
private final io.opentelemetry.api.metrics.DoubleSumObserver agentDoubleSumObserver;

View File

@ -10,6 +10,8 @@ import application.io.opentelemetry.api.metrics.DoubleUpDownSumObserverBuilder;
import application.io.opentelemetry.api.metrics.common.Labels;
import java.util.function.Consumer;
// For observers, which have no API, there might be a better pattern than wrapping.
@SuppressWarnings("FieldCanBeLocal")
class ApplicationDoubleUpDownSumObserver implements DoubleUpDownSumObserver {
private final io.opentelemetry.api.metrics.DoubleUpDownSumObserver agentDoubleUpDownSumObserver;

View File

@ -10,6 +10,8 @@ import application.io.opentelemetry.api.metrics.DoubleValueObserverBuilder;
import application.io.opentelemetry.api.metrics.common.Labels;
import java.util.function.Consumer;
// For observers, which have no API, there might be a better pattern than wrapping.
@SuppressWarnings("FieldCanBeLocal")
class ApplicationDoubleValueObserver implements DoubleValueObserver {
private final io.opentelemetry.api.metrics.DoubleValueObserver agentDoubleValueObserver;

View File

@ -10,6 +10,8 @@ import application.io.opentelemetry.api.metrics.LongSumObserverBuilder;
import application.io.opentelemetry.api.metrics.common.Labels;
import java.util.function.Consumer;
// For observers, which have no API, there might be a better pattern than wrapping.
@SuppressWarnings("FieldCanBeLocal")
class ApplicationLongSumObserver implements LongSumObserver {
private final io.opentelemetry.api.metrics.LongSumObserver agentLongSumObserver;

Some files were not shown because too many files have changed in this diff Show More