diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 643e5e5f77..b95a557b72 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -23,7 +23,7 @@ can be automatically added by running `./mvnw com.mycila:license-maven-plugin:fo ``` /** - * Copyright 2020 The OpenZipkin Authors + * Copyright 2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at diff --git a/.github/workflows/create_release.yml b/.github/workflows/create_release.yml index d9d2a387df..3bb12b15a3 100644 --- a/.github/workflows/create_release.yml +++ b/.github/workflows/create_release.yml @@ -11,17 +11,22 @@ on: jobs: create_release: - runs-on: ubuntu-20.04 # newest available distribution, aka focal + runs-on: ubuntu-22.04 # newest available distribution, aka jellyfish steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: # Prevent use of implicit GitHub Actions read-only token GITHUB_TOKEN. We don't deploy on # the tag MAJOR.MINOR.PATCH event, but we still need to deploy the maven-release-plugin master commit. token: ${{ secrets.GH_TOKEN }} - fetch-depth: 1 # only need the base commit as license check isn't run + fetch-depth: 1 # only need the HEAD commit as license check isn't run + - name: Setup java + uses: actions/setup-java@v4 + with: + distribution: 'zulu' # zulu as it supports a wide version range + java-version: '11' # earliest LTS and last that can compile the 1.6 release profile. - name: Cache local Maven repository - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index aacfe79d48..e4069ac180 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -14,17 +14,22 @@ on: jobs: deploy: - runs-on: ubuntu-20.04 # newest available distribution, aka focal + runs-on: ubuntu-22.04 # newest available distribution, aka jellyfish steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: # Prevent use of implicit GitHub Actions read-only token GITHUB_TOKEN. # We push Javadocs to the gh-pages branch on commit. token: ${{ secrets.GH_TOKEN }} - fetch-depth: 0 # allow build-bin/javadoc_to_gh_pages to get the full history + fetch-depth: 0 # allow build-bin/idl_to_gh_pages to get the full history + - name: Setup java + uses: actions/setup-java@v4 + with: + distribution: 'zulu' # zulu as it supports a wide version range + java-version: '11' # earliest LTS and last that can compile the 1.6 release profile. - name: Cache local Maven repository - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 49040c10b0..133923247f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,21 +15,58 @@ on: paths-ignore: '**/*.md' jobs: + test-javadoc: + name: Test JavaDoc Builds + runs-on: ubuntu-22.04 # newest available distribution, aka jellyfish + if: "!contains(github.event.head_commit.message, 'maven-release-plugin')" + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 # full git history for license check + - name: Setup java + uses: actions/setup-java@v4 + with: + distribution: 'zulu' # zulu as it supports a wide version range + java-version: '11' # earliest LTS and last that can compile the 1.6 release profile. + - name: Cache local Maven repository + uses: actions/cache@v3 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-jdk-11-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-jdk-11-maven- + - name: Build JavaDoc + run: ./mvnw clean javadoc:aggregate -Prelease + test: - runs-on: ubuntu-20.04 # newest available distribution, aka focal + name: test (JDK ${{ matrix.java_version }}) + runs-on: ubuntu-22.04 # newest available distribution, aka jellyfish if: "!contains(github.event.head_commit.message, 'maven-release-plugin')" + strategy: + fail-fast: false # don't fail fast as sometimes failures are operating system specific + matrix: # use latest available versions and be consistent on all workflows! + include: + - java_version: 11 # Last that can compile brave to 1.6 + maven_args: -Prelease -Dgpg.skip -Dmaven.javadoc.skip=true + - java_version: 21 # Most recent LTS steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 + with: + fetch-depth: 0 # full git history for license check + - name: Setup java + uses: actions/setup-java@v4 with: - fetch-depth: 0 # full git history for license check + distribution: 'zulu' # zulu as it supports a wide version range + java-version: ${{ matrix.java_version }} - name: Cache local Maven repository - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-maven- - # We can't cache Docker without using buildx because GH actions restricts /var/lib/docker - # That's ok because DOCKER_PARENT_IMAGE is always ghcr.io and local anyway. + key: ${{ runner.os }}-jdk-${{ matrix.java_version }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-jdk-${{ matrix.java_version }}-maven- + # Don't attempt to cache Docker. Sensitive information can be stolen + # via forks, and login session ends up in ~/.docker. This is ok because + # we publish DOCKER_PARENT_IMAGE to ghcr.io, hence local to the runner. - name: Test run: build-bin/configure_test && build-bin/test diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar index 2cc7d4a55c..cb28b0e37c 100644 Binary files a/.mvn/wrapper/maven-wrapper.jar and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 0c675e6e69..346d645fd0 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,18 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar \ No newline at end of file +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/RELEASE.md b/RELEASE.md index 84e84c544e..aecf4d753e 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -55,11 +55,19 @@ the following: Before you do the first release of the year, move the SNAPSHOT version back and forth from whatever the current is. In-between, re-apply the licenses. + +Note: the command below is more complex than a normal project because this +project has a bom. ```bash -$ ./mvnw versions:set -DnewVersion=1.3.3-SNAPSHOT -DgenerateBackupPoms=false -$ ./mvnw com.mycila:license-maven-plugin:format -$ ./mvnw versions:set -DnewVersion=1.3.2-SNAPSHOT -DgenerateBackupPoms=false -$ git commit -am"Adjusts copyright headers for this year" +$ mvn=$PWD/mvnw +$ for p in ./bom .; do + (cd $p + $mvn versions:set -DnewVersion=2.17.1-SNAPSHOT -DgenerateBackupPoms=false + $mvn -o clean install -DskipTests + $mvn com.mycila:license-maven-plugin:format + $mvn versions:set -DnewVersion=2.17.0-SNAPSHOT -DgenerateBackupPoms=false) + done +$ git commit -asm"Adjusts copyright headers for this year" ``` ## Manually releasing diff --git a/brave-bom/pom.xml b/brave-bom/pom.xml index 21b273e1ac..f5816d58b9 100644 --- a/brave-bom/pom.xml +++ b/brave-bom/pom.xml @@ -36,8 +36,6 @@ 2.23.2 2.16.3 - - 1.6.8 @@ -315,7 +313,7 @@ org.sonatype.plugins nexus-staging-maven-plugin - ${nexus-staging-maven-plugin.version} + 1.6.13 true ossrh @@ -326,12 +324,12 @@ maven-deploy-plugin - 3.0.0-M1 + 3.1.1 maven-gpg-plugin - 1.6 + 3.1.0 sign-artifacts diff --git a/brave-tests/pom.xml b/brave-tests/pom.xml index ef723de9cc..90bc537a68 100644 --- a/brave-tests/pom.xml +++ b/brave-tests/pom.xml @@ -27,8 +27,6 @@ ${project.basedir}/.. - 1.8 - java18 @@ -61,15 +59,6 @@ - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - diff --git a/brave-tests/src/main/java/brave/test/IntegrationTestSpanHandler.java b/brave-tests/src/main/java/brave/test/IntegrationTestSpanHandler.java index 18ea0a6877..37f6d3a877 100644 --- a/brave-tests/src/main/java/brave/test/IntegrationTestSpanHandler.java +++ b/brave-tests/src/main/java/brave/test/IntegrationTestSpanHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -128,7 +128,7 @@ public final class IntegrationTestSpanHandler extends SpanHandler implements Tes public IntegrationTestSpanHandler() { // OrphanTracker detects to see if it should add "brave.flushed" or not, as it is used in - // production some times and avoiding this could be helpful. This forces a failed match, + // production sometimes and avoiding this could be helpful. This forces a failed match, // so that we can detect orphans even when no data was added. MutableSpan intentionallyWrongDefaultSpan = new MutableSpan(); intentionallyWrongDefaultSpan.tag("not", "me"); diff --git a/brave-tests/src/test/java/brave/test/IntegrationTestSpanHandlerTest.java b/brave-tests/src/test/java/brave/test/IntegrationTestSpanHandlerTest.java index ad248e159c..62699357b8 100644 --- a/brave-tests/src/test/java/brave/test/IntegrationTestSpanHandlerTest.java +++ b/brave-tests/src/test/java/brave/test/IntegrationTestSpanHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -45,7 +45,7 @@ public class IntegrationTestSpanHandlerTest { assertThatThrownBy(spanHandler::takeLocalSpan) .hasMessageStartingWith("Orphaned span found") .hasMessageContaining("brave.flush") - .hasMessageEndingWith("Look for code missing span.flush() or span.finish()."); + .hasMessageContaining("Look for code missing span.flush() or span.finish()."); } @Test public void toString_includesSpans() { diff --git a/brave/pom.xml b/brave/pom.xml index 7d997df5c7..1c20b1875a 100644 --- a/brave/pom.xml +++ b/brave/pom.xml @@ -31,8 +31,6 @@ brave ${project.basedir}/.. - 1.6 - java16 -Xep:EqualsUnsafeCast:OFF @@ -61,19 +59,6 @@ 0.18 test - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - io.opentracing opentracing-api @@ -136,4 +121,40 @@ + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/brave/src/main/java/brave/Tracing.java b/brave/src/main/java/brave/Tracing.java index 291015fdc2..cad13e7127 100644 --- a/brave/src/main/java/brave/Tracing.java +++ b/brave/src/main/java/brave/Tracing.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -50,7 +50,7 @@ * for example via spring or when mocking. */ public abstract class Tracing implements Closeable { - static final AtomicReference CURRENT = new AtomicReference<>(); + static final AtomicReference CURRENT = new AtomicReference(); public static Builder newBuilder() { return new Builder(); @@ -148,7 +148,7 @@ public static final class Builder { boolean alwaysSampleLocal = false, alwaysReportSpans = false, trackOrphans = false; Propagation.Factory propagationFactory = B3Propagation.FACTORY; ErrorParser errorParser = new ErrorParser(); - Set spanHandlers = new LinkedHashSet<>(); // dupes not ok + Set spanHandlers = new LinkedHashSet(); // dupes not ok Builder() { defaultSpan.localServiceName("unknown"); @@ -162,7 +162,7 @@ public static final class Builder { * @since 5.12 */ public Set spanHandlers() { - return Collections.unmodifiableSet(new LinkedHashSet<>(spanHandlers)); + return Collections.unmodifiableSet(new LinkedHashSet(spanHandlers)); } /** @@ -480,7 +480,7 @@ static final class Default extends Tracing { defaultSpan.localIp(Platform.get().linkLocalIp()); } - Set spanHandlers = new LinkedHashSet<>(builder.spanHandlers); + Set spanHandlers = new LinkedHashSet(builder.spanHandlers); // When present, the Zipkin handler is invoked after the user-supplied ones. if (builder.zipkinSpanReporter != null) { spanHandlers.add( diff --git a/brave/src/main/java/brave/baggage/BaggagePropagation.java b/brave/src/main/java/brave/baggage/BaggagePropagation.java index 988774545a..5c7d990977 100644 --- a/brave/src/main/java/brave/baggage/BaggagePropagation.java +++ b/brave/src/main/java/brave/baggage/BaggagePropagation.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -99,8 +99,8 @@ public static FactoryBuilder newFactoryBuilder(Propagation.Factory delegate) { public static class FactoryBuilder { // not final to backport ExtraFieldPropagation final Propagation.Factory delegate; - final List extractKeyNames = new ArrayList<>(); - final Set configs = new LinkedHashSet<>(); + final List extractKeyNames = new ArrayList(); + final Set configs = new LinkedHashSet(); FactoryBuilder(Propagation.Factory delegate) { if (delegate == null) throw new NullPointerException("delegate == null"); @@ -115,7 +115,7 @@ public static class FactoryBuilder { // not final to backport ExtraFieldPropagat * @since 5.11 */ public Set configs() { - return Collections.unmodifiableSet(new LinkedHashSet<>(configs)); + return Collections.unmodifiableSet(new LinkedHashSet(configs)); } /** @@ -183,8 +183,8 @@ static final class Factory extends Propagation.Factory implements Propagation fields = new ArrayList<>(); - Set localFieldNames = new LinkedHashSet<>(); + List fields = new ArrayList(); + Set localFieldNames = new LinkedHashSet(); int maxDynamicFields = 0; for (BaggagePropagationConfig config : factoryBuilder.configs) { maxDynamicFields += config.maxDynamicFields; @@ -199,11 +199,11 @@ static final class Factory extends Propagation.Factory implements Propagation BaggagePropagation create(KeyFactory keyFactory) { - return new BaggagePropagation<>(StringPropagationAdapter.create(get(), keyFactory)); + return new BaggagePropagation(StringPropagationAdapter.create(get(), keyFactory)); } @Override public BaggagePropagation get() { - return new BaggagePropagation<>(this); + return new BaggagePropagation(this); } @Override public TraceContext decorate(TraceContext context) { @@ -224,11 +224,11 @@ static final class Factory extends Propagation.Factory implements Propagation Injector injector(Setter setter) { - return new BaggageInjector<>(this, setter); + return new BaggageInjector(this, setter); } @Override public Extractor extractor(Getter getter) { - return new BaggageExtractor<>(this, getter); + return new BaggageExtractor(this, getter); } } @@ -280,14 +280,12 @@ public static List allKeyNames(Propagation propagation) { List baggageKeyNames = getAllKeyNames(emptyExtraction); if (baggageKeyNames.isEmpty()) return propagation.keys(); - List result = new ArrayList<>(propagation.keys().size() + baggageKeyNames.size()); + List result = new ArrayList(propagation.keys().size() + baggageKeyNames.size()); result.addAll(propagation.keys()); result.addAll(baggageKeyNames); return Collections.unmodifiableList(result); } - // Not lambda as Retrolambda creates an OSGi dependency on jdk.internal.vm.annotation with JDK 14 - // See https://github.com/luontola/retrolambda/issues/160 enum NoopGetter implements Getter { INSTANCE; diff --git a/brave/src/main/java/brave/baggage/BaggagePropagationConfig.java b/brave/src/main/java/brave/baggage/BaggagePropagationConfig.java index 81b6ec0433..7c46e1daae 100644 --- a/brave/src/main/java/brave/baggage/BaggagePropagationConfig.java +++ b/brave/src/main/java/brave/baggage/BaggagePropagationConfig.java @@ -99,7 +99,7 @@ public Builder toBuilder() { /** @since 5.11 */ public static final class Builder { final BaggageField field; - List keyNames = new ArrayList<>(); + List keyNames = new ArrayList(); Builder(BaggageField field) { this.field = field; @@ -107,7 +107,7 @@ public static final class Builder { Builder(SingleBaggageField input) { this.field = input.field; - this.keyNames = new ArrayList<>(input.keyNames()); + this.keyNames = new ArrayList(input.keyNames()); } /** @@ -137,8 +137,11 @@ public SingleBaggageField build() { ? BaggageCodec.NOOP : SingleFieldBaggageCodec.single(builder.field, builder.keyNames), 0); field = builder.field; - keyNames = builder.keyNames.isEmpty() ? Collections.emptySet() - : Collections.unmodifiableSet(new LinkedHashSet<>(builder.keyNames)); + if (builder.keyNames.isEmpty()) { + keyNames = Collections.emptySet(); + } else { + keyNames = Collections.unmodifiableSet(new LinkedHashSet(builder.keyNames)); + } } public BaggageField field() { diff --git a/brave/src/main/java/brave/baggage/CorrelationFlushScope.java b/brave/src/main/java/brave/baggage/CorrelationFlushScope.java index 016c5cacfe..e84fb2212b 100644 --- a/brave/src/main/java/brave/baggage/CorrelationFlushScope.java +++ b/brave/src/main/java/brave/baggage/CorrelationFlushScope.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -46,7 +46,7 @@ final class CorrelationFlushScope extends AtomicBoolean implements Scope { * BaggageField#updateValue(String)}. */ static void flush(BaggageField field, String value) { - Set syncedContexts = new LinkedHashSet<>(); + Set syncedContexts = new LinkedHashSet(); for (Object o : updateScopeStack()) { CorrelationUpdateScope next = ((CorrelationUpdateScope) o); String name = next.name(field); @@ -66,12 +66,13 @@ static void flush(BaggageField field, String value) { } } - static final ThreadLocal> updateScopeStack = new ThreadLocal<>(); + static final ThreadLocal> updateScopeStack = + new ThreadLocal>(); static ArrayDeque updateScopeStack() { ArrayDeque stack = updateScopeStack.get(); if (stack == null) { - stack = new ArrayDeque<>(); + stack = new ArrayDeque(); updateScopeStack.set(stack); } return stack; diff --git a/brave/src/main/java/brave/baggage/CorrelationScopeDecorator.java b/brave/src/main/java/brave/baggage/CorrelationScopeDecorator.java index 89b2071a3a..f0bf68e6d4 100644 --- a/brave/src/main/java/brave/baggage/CorrelationScopeDecorator.java +++ b/brave/src/main/java/brave/baggage/CorrelationScopeDecorator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -72,8 +72,8 @@ public abstract class CorrelationScopeDecorator implements ScopeDecorator { public static abstract class Builder { final CorrelationContext context; // Don't allow mixed case of the same name! - final Set allNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); - final Set fields = new LinkedHashSet<>(); + final Set allNames = new TreeSet(String.CASE_INSENSITIVE_ORDER); + final Set fields = new LinkedHashSet(); /** Internal constructor used by subtypes. */ protected Builder(CorrelationContext context) { @@ -91,7 +91,7 @@ protected Builder(CorrelationContext context) { * @since 5.11 */ public Set configs() { - return Collections.unmodifiableSet(new LinkedHashSet<>(fields)); + return Collections.unmodifiableSet(new LinkedHashSet(fields)); } /** diff --git a/brave/src/main/java/brave/handler/MutableSpan.java b/brave/src/main/java/brave/handler/MutableSpan.java index 0aa10ec82f..6e6bbeb981 100644 --- a/brave/src/main/java/brave/handler/MutableSpan.java +++ b/brave/src/main/java/brave/handler/MutableSpan.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -609,7 +609,7 @@ public long annotationTimestampAt(int i) { // IndexOutOfBoundsException(i) is Java 9+ if (i < 0) throw new IndexOutOfBoundsException("i < 0"); if (i >= annotationCount) throw new IndexOutOfBoundsException("i >= annotationCount"); - return (long) annotations[i * 2]; + return (Long) annotations[i * 2]; } /** @@ -658,7 +658,7 @@ public Collection> annotations() { */ public void forEachAnnotation(AnnotationConsumer annotationConsumer, T target) { for (int i = 0, length = annotationCount * 2; i < length; i += 2) { - long timestamp = (long) annotations[i]; + long timestamp = (Long) annotations[i]; annotationConsumer.accept(target, timestamp, annotations[i + 1].toString()); } } @@ -682,7 +682,7 @@ public void forEachAnnotation(AnnotationConsumer annotationConsumer, T ta public void forEachAnnotation(AnnotationUpdater annotationUpdater) { for (int i = 0, length = annotationCount * 2; i < length; i += 2) { String value = annotations[i + 1].toString(); - String newValue = annotationUpdater.update((long) annotations[i], value); + String newValue = annotationUpdater.update((Long) annotations[i], value); if (newValue != null) { update(annotations, i, newValue); } else { diff --git a/brave/src/main/java/brave/internal/Platform.java b/brave/src/main/java/brave/internal/Platform.java index b4db6ce97b..2b610997ad 100644 --- a/brave/src/main/java/brave/internal/Platform.java +++ b/brave/src/main/java/brave/internal/Platform.java @@ -34,11 +34,15 @@ * *

Originally designed by OkHttp team, derived from {@code okhttp3.internal.platform.Platform} */ -public abstract class Platform { +public abstract class Platform implements Clock { private static final Platform PLATFORM = findPlatform(); volatile String linkLocalIp; + /** Returns the same value as {@link System#nanoTime()}. */ + @Nullable public abstract long nanoTime(); + + /** Guards {@link InetSocketAddress#getHostString()}, as it isn't available until Java 7 */ @Nullable public abstract String getHostString(InetSocketAddress socket); @@ -112,7 +116,7 @@ static Platform findPlatform() { try { Class zoneId = Class.forName("java.time.ZoneId"); Class.forName("java.time.Clock").getMethod("tickMillis", zoneId); - return new Jre9(); // intentionally doesn't not access the type prior to the above guard + return new Jre9(); // intentionally doesn't access the type prior to the above guard } catch (ClassNotFoundException e) { // pre JRE 8 } catch (NoSuchMethodException e) { @@ -122,7 +126,7 @@ static Platform findPlatform() { // Find JRE 7 new methods try { Class.forName("java.util.concurrent.ThreadLocalRandom"); - return new Jre7(); // intentionally doesn't not access the type prior to the above guard + return new Jre7(); // intentionally doesn't access the type prior to the above guard } catch (ClassNotFoundException e) { // pre JRE 7 } @@ -163,12 +167,16 @@ public Clock clock() { } static class Jre9 extends Jre7 { + @Override public long currentTimeMicroseconds() { + java.time.Instant instant = java.time.Clock.systemUTC().instant(); + return (instant.getEpochSecond() * 1000000) + (instant.getNano() / 1000); + } + @IgnoreJRERequirement @Override public Clock clock() { return new Clock() { // we could use jdk.internal.misc.VM to do this more efficiently, but it is internal @Override public long currentTimeMicroseconds() { - java.time.Instant instant = java.time.Clock.systemUTC().instant(); - return (instant.getEpochSecond() * 1000000) + (instant.getNano() / 1000); + return Jre9.this.currentTimeMicroseconds(); } @Override public String toString() { @@ -183,6 +191,14 @@ static class Jre9 extends Jre7 { } static class Jre7 extends Platform { + @Override public long currentTimeMicroseconds() { + return System.currentTimeMillis() * 1000; + } + + @Override public long nanoTime() { + return System.nanoTime(); + } + @IgnoreJRERequirement @Override public String getHostString(InetSocketAddress socket) { return socket.getHostString(); } @@ -192,7 +208,7 @@ static class Jre7 extends Platform { } @IgnoreJRERequirement @Override public long nextTraceIdHigh() { - return nextTraceIdHigh(java.util.concurrent.ThreadLocalRandom.current().nextInt()); + return nextTraceIdHigh(currentTimeMicroseconds(), java.util.concurrent.ThreadLocalRandom.current().nextInt()); } @IgnoreJRERequirement @Override @@ -205,13 +221,20 @@ public AssertionError assertionError(String message, Throwable cause) { } } - static long nextTraceIdHigh(int random) { - long epochSeconds = System.currentTimeMillis() / 1000; + static long nextTraceIdHigh(long currentTimeMicroseconds, int random) { + long epochSeconds = currentTimeMicroseconds / 1000000; return (epochSeconds & 0xffffffffL) << 32 | (random & 0xffffffffL); } static class Jre6 extends Platform { + @Override public long currentTimeMicroseconds() { + return System.currentTimeMillis() * 1000; + } + + @Override public long nanoTime() { + return System.nanoTime(); + } @Override public String getHostString(InetSocketAddress socket) { return socket.getAddress().getHostAddress(); @@ -222,13 +245,13 @@ static class Jre6 extends Platform { } @Override public long nextTraceIdHigh() { - return nextTraceIdHigh(prng.nextInt()); + return nextTraceIdHigh(currentTimeMicroseconds(), prng.nextInt()); } final Random prng; Jre6() { - this.prng = new Random(System.nanoTime()); + this.prng = new Random(nanoTime()); } @Override public String toString() { diff --git a/brave/src/main/java/brave/internal/RecyclableBuffers.java b/brave/src/main/java/brave/internal/RecyclableBuffers.java index 8bc940773a..9392c474b1 100644 --- a/brave/src/main/java/brave/internal/RecyclableBuffers.java +++ b/brave/src/main/java/brave/internal/RecyclableBuffers.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -15,7 +15,7 @@ public final class RecyclableBuffers { - private static final ThreadLocal PARSE_BUFFER = new ThreadLocal<>(); + private static final ThreadLocal PARSE_BUFFER = new ThreadLocal(); /** * Returns a {@link ThreadLocal} reused {@code char[]} for use when decoding bytes into an ID hex diff --git a/brave/src/main/java/brave/internal/WrappingExecutorService.java b/brave/src/main/java/brave/internal/WrappingExecutorService.java index 4f49641a9b..68c03ba013 100644 --- a/brave/src/main/java/brave/internal/WrappingExecutorService.java +++ b/brave/src/main/java/brave/internal/WrappingExecutorService.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -104,7 +104,7 @@ public Future submit(Runnable task, T result) { } Collection> wrap(Collection> tasks) { - ArrayList> result = new ArrayList<>(tasks.size()); + ArrayList> result = new ArrayList>(tasks.size()); for (Callable task : tasks) { result.add(wrap(task)); } diff --git a/brave/src/main/java/brave/internal/baggage/BaggageFields.java b/brave/src/main/java/brave/internal/baggage/BaggageFields.java index eac0881368..536257cafd 100644 --- a/brave/src/main/java/brave/internal/baggage/BaggageFields.java +++ b/brave/src/main/java/brave/internal/baggage/BaggageFields.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -88,7 +88,7 @@ Object[] state() { * #isDynamic()}. */ public List getAllFields() { - return Collections.unmodifiableList(new ArrayList<>(keySet())); + return Collections.unmodifiableList(new ArrayList(keySet())); } /** Returns a read-only view of the non-null baggage field values */ diff --git a/brave/src/main/java/brave/internal/baggage/SingleFieldBaggageCodec.java b/brave/src/main/java/brave/internal/baggage/SingleFieldBaggageCodec.java index 54e8051918..8918ebe01e 100644 --- a/brave/src/main/java/brave/internal/baggage/SingleFieldBaggageCodec.java +++ b/brave/src/main/java/brave/internal/baggage/SingleFieldBaggageCodec.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -33,7 +33,7 @@ public static SingleFieldBaggageCodec single(BaggageField field, Collection keyNames) { this.field = field; - this.keyNamesList = Collections.unmodifiableList(new ArrayList<>(keyNames)); + this.keyNamesList = Collections.unmodifiableList(new ArrayList(keyNames)); } @Override public List extractKeyNames() { diff --git a/brave/src/main/java/brave/internal/collect/Lists.java b/brave/src/main/java/brave/internal/collect/Lists.java index b75e5d1871..dc85c68904 100644 --- a/brave/src/main/java/brave/internal/collect/Lists.java +++ b/brave/src/main/java/brave/internal/collect/Lists.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -23,7 +23,7 @@ public final class Lists { public static List ensureMutable(List list) { if (list instanceof ArrayList) return list; int size = list.size(); - ArrayList mutable = new ArrayList<>(size); + ArrayList mutable = new ArrayList(size); for (int i = 0; i < size; i++) { mutable.add(list.get(i)); } @@ -36,12 +36,12 @@ public static List ensureImmutable(List list) { if (list.size() == 1) return Collections.singletonList(list.get(0)); if (isImmutable(list)) return list; - return Collections.unmodifiableList(new ArrayList<>(list)); + return Collections.unmodifiableList(new ArrayList(list)); } static boolean isImmutable(List extra) { assert extra.size() > 1; // Handled by caller. - // avoid copying datastructure by trusting certain names. + // avoid copying data structure by trusting certain names. String simpleName = extra.getClass().getSimpleName(); // We don't need to check EMPTY_LIST or SingletonList here since our only caller handles them // without type-checking. diff --git a/brave/src/main/java/brave/internal/collect/UnsafeArrayMap.java b/brave/src/main/java/brave/internal/collect/UnsafeArrayMap.java index 232973d906..7aecf06cb4 100644 --- a/brave/src/main/java/brave/internal/collect/UnsafeArrayMap.java +++ b/brave/src/main/java/brave/internal/collect/UnsafeArrayMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -46,7 +46,7 @@ public interface Mapper { } public static Builder newBuilder() { - return new Builder<>(); + return new Builder(); } public static final class Builder { @@ -94,8 +94,8 @@ public Map build(Object[] array) { } } if (numFiltered == i / 2) return Collections.emptyMap(); - if (keyMapper == null) return new UnsafeArrayMap<>(array, i, filteredBitSet); - return new KeyMapping<>(this, array, i, filteredBitSet); + if (keyMapper == null) return new UnsafeArrayMap(array, i, filteredBitSet); + return new KeyMapping(this, array, i, filteredBitSet); } } @@ -217,7 +217,7 @@ final class ValuesView extends SetView { final class EntrySetView extends SetView> { @Override Map.Entry elementAtArrayIndex(int i) { - return new SimpleImmutableEntry<>(key(i), value(i + 1)); + return new SimpleImmutableEntry(key(i), value(i + 1)); } @Override public boolean contains(Object o) { diff --git a/brave/src/main/java/brave/internal/collect/WeakConcurrentMap.java b/brave/src/main/java/brave/internal/collect/WeakConcurrentMap.java index bd9186bbb2..5233821f88 100644 --- a/brave/src/main/java/brave/internal/collect/WeakConcurrentMap.java +++ b/brave/src/main/java/brave/internal/collect/WeakConcurrentMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -43,7 +43,7 @@ *

See https://github.com/raphw/weak-lock-free */ public class WeakConcurrentMap extends ReferenceQueue implements Iterable> { - final ConcurrentMap, V> target = new ConcurrentHashMap<>(); + final ConcurrentMap, V> target = new ConcurrentHashMap, V>(); @Nullable public V getIfPresent(K key) { if (key == null) throw new NullPointerException("key == null"); @@ -58,7 +58,7 @@ public class WeakConcurrentMap extends ReferenceQueue implements Iterab if (value == null) throw new NullPointerException("value == null"); expungeStaleEntries(); - return target.putIfAbsent(new WeakKey<>(key, this), value); + return target.putIfAbsent(new WeakKey(key, this), value); } /** Removes the entry with the indicated key and returns the old value or {@code null}. */ diff --git a/brave/src/main/java/brave/internal/extra/MapExtra.java b/brave/src/main/java/brave/internal/extra/MapExtra.java index 17157d5df4..6244678d3b 100644 --- a/brave/src/main/java/brave/internal/extra/MapExtra.java +++ b/brave/src/main/java/brave/internal/extra/MapExtra.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -55,7 +55,7 @@ protected boolean isEmpty() { protected Set keySet() { if (!isDynamic()) return factory.initialFieldIndices.keySet(); Object[] state = state(); - Set result = new LinkedHashSet<>(state.length / 2); + Set result = new LinkedHashSet(state.length / 2); for (int i = 0; i < state.length; i += 2) { result.add((K) state[i]); } diff --git a/brave/src/main/java/brave/internal/extra/MapExtraFactory.java b/brave/src/main/java/brave/internal/extra/MapExtraFactory.java index 731c970f4b..5bd9df1e78 100644 --- a/brave/src/main/java/brave/internal/extra/MapExtraFactory.java +++ b/brave/src/main/java/brave/internal/extra/MapExtraFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -29,7 +29,7 @@ public abstract class MapExtraFactory, public static abstract class Builder, F extends MapExtraFactory, B extends Builder> { - List initialState = new ArrayList<>(); + List initialState = new ArrayList(); int maxDynamicEntries; public final B addInitialKey(K key) { @@ -56,7 +56,7 @@ public final B maxDynamicEntries(int maxDynamicEntries) { protected MapExtraFactory(Builder builder) { super(builder.initialState.toArray()); - Map initialFieldIndices = new LinkedHashMap<>(); + Map initialFieldIndices = new LinkedHashMap(); Object[] initialStateArray = (Object[]) initialState; this.initialArrayLength = initialStateArray.length; for (int i = 0; i < initialArrayLength; i += 2) { diff --git a/brave/src/main/java/brave/internal/handler/OrphanTracker.java b/brave/src/main/java/brave/internal/handler/OrphanTracker.java index f338b68f31..23c4740434 100644 --- a/brave/src/main/java/brave/internal/handler/OrphanTracker.java +++ b/brave/src/main/java/brave/internal/handler/OrphanTracker.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -87,7 +87,8 @@ public SpanHandler build() { final MutableSpan defaultSpan; final Clock clock; - final WeakConcurrentMap spanToCaller = new WeakConcurrentMap<>(); + final WeakConcurrentMap spanToCaller = + new WeakConcurrentMap(); final Level logLevel; OrphanTracker(Builder builder) { diff --git a/brave/src/main/java/brave/internal/propagation/InjectorFactory.java b/brave/src/main/java/brave/internal/propagation/InjectorFactory.java index 916a8836ca..4b9803bb2b 100644 --- a/brave/src/main/java/brave/internal/propagation/InjectorFactory.java +++ b/brave/src/main/java/brave/internal/propagation/InjectorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -152,13 +152,13 @@ public InjectorFactory build() { clientInjectorFunction = builder.clientInjectorFunction; producerInjectorFunction = builder.producerInjectorFunction; consumerInjectorFunction = builder.consumerInjectorFunction; - Set keyNames = new LinkedHashSet<>(); + Set keyNames = new LinkedHashSet(); // Add messaging first as their formats are likely the cheapest to extract keyNames.addAll(builder.consumerInjectorFunction.keyNames()); keyNames.addAll(builder.producerInjectorFunction.keyNames()); keyNames.addAll(builder.clientInjectorFunction.keyNames()); keyNames.addAll(builder.injectorFunction.keyNames()); - this.keyNames = Collections.unmodifiableList(new ArrayList<>(keyNames)); + this.keyNames = Collections.unmodifiableList(new ArrayList(keyNames)); } /** @@ -181,15 +181,15 @@ public TraceContext.Injector newInjector(Setter setter) { RemoteSetter remoteSetter = (RemoteSetter) setter; switch (remoteSetter.spanKind()) { case CLIENT: - return new RemoteInjector<>(setter, clientInjectorFunction); + return new RemoteInjector(setter, clientInjectorFunction); case PRODUCER: - return new RemoteInjector<>(setter, producerInjectorFunction); + return new RemoteInjector(setter, producerInjectorFunction); case CONSUMER: - return new RemoteInjector<>(setter, consumerInjectorFunction); + return new RemoteInjector(setter, consumerInjectorFunction); default: // SERVER is nonsense as it cannot be injected } } - return new DeferredInjector<>(setter, this); + return new DeferredInjector(setter, this); } @Override public int hashCode() { @@ -305,7 +305,7 @@ static final class RemoteInjector implements TraceContext.Injector { static InjectorFunction injectorFunction(InjectorFunction existing, InjectorFunction... update) { if (update == null) throw new NullPointerException("injectorFunctions == null"); LinkedHashSet injectorFunctionSet = - new LinkedHashSet<>(Arrays.asList(update)); + new LinkedHashSet(Arrays.asList(update)); if (injectorFunctionSet.contains(null)) { throw new NullPointerException("injectorFunction == null"); } @@ -321,11 +321,11 @@ static final class CompositeInjectorFunction implements InjectorFunction { CompositeInjectorFunction(InjectorFunction[] injectorFunctions) { this.injectorFunctions = injectorFunctions; - Set keyNames = new LinkedHashSet<>(); + Set keyNames = new LinkedHashSet(); for (InjectorFunction injectorFunction : injectorFunctions) { keyNames.addAll(injectorFunction.keyNames()); } - this.keyNames = Collections.unmodifiableList(new ArrayList<>(keyNames)); + this.keyNames = Collections.unmodifiableList(new ArrayList(keyNames)); } @Override public List keyNames() { diff --git a/brave/src/main/java/brave/internal/propagation/StringPropagationAdapter.java b/brave/src/main/java/brave/internal/propagation/StringPropagationAdapter.java index be08e2464e..0d090db150 100644 --- a/brave/src/main/java/brave/internal/propagation/StringPropagationAdapter.java +++ b/brave/src/main/java/brave/internal/propagation/StringPropagationAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -76,7 +76,7 @@ public static Propagation create(Propagation delegate, KeyFactory if (delegate == null) throw new NullPointerException("delegate == null"); if (keyFactory == null) throw new NullPointerException("keyFactory == null"); if (keyFactory == KeyFactory.STRING) return (Propagation) delegate; - return new StringPropagationAdapter<>(delegate, keyFactory); + return new StringPropagationAdapter(delegate, keyFactory); } final Propagation delegate; @@ -87,7 +87,7 @@ public static Propagation create(Propagation delegate, KeyFactory StringPropagationAdapter(Propagation delegate, KeyFactory keyFactory) { this.delegate = delegate; this.keyFactory = keyFactory; - this.map = new LinkedHashMap<>(); + this.map = new LinkedHashMap(); this.keysList = toKeyList(delegate.keys(), keyFactory); } @@ -110,13 +110,13 @@ List toKeyList(List keyNames, KeyFactory keyFactory) { @Override public Injector injector(Setter setter) { // No check if Setter is a RemoteSetter because this instance cannot have String keys while // RemoteSetter must have String keys - return delegate.injector(new SetterAdapter<>(setter, map)); + return delegate.injector(new SetterAdapter(setter, map)); } @Override public Extractor extractor(Getter getter) { // No check if Setter is a RemoteGetter because this instance cannot have String keys while // RemoteGetter must have String keys - return delegate.extractor(new GetterAdapter<>(getter, map)); + return delegate.extractor(new GetterAdapter(getter, map)); } @Override public int hashCode() { diff --git a/brave/src/main/java/brave/internal/recorder/PendingSpans.java b/brave/src/main/java/brave/internal/recorder/PendingSpans.java index c13a9ed592..c76ba82d5c 100644 --- a/brave/src/main/java/brave/internal/recorder/PendingSpans.java +++ b/brave/src/main/java/brave/internal/recorder/PendingSpans.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -19,6 +19,7 @@ import brave.handler.SpanHandler; import brave.handler.SpanHandler.Cause; import brave.internal.Nullable; +import brave.internal.Platform; import brave.internal.collect.WeakConcurrentMap; import brave.propagation.TraceContext; import java.lang.ref.Reference; @@ -36,12 +37,14 @@ */ public final class PendingSpans extends WeakConcurrentMap { final MutableSpan defaultSpan; + final Platform platform; final Clock clock; final SpanHandler spanHandler; final AtomicBoolean noop; public PendingSpans(MutableSpan defaultSpan, Clock clock, SpanHandler spanHandler, AtomicBoolean noop) { + this.platform = Platform.get(); this.defaultSpan = defaultSpan; this.clock = clock; this.spanHandler = spanHandler; @@ -76,7 +79,7 @@ public PendingSpan getOrCreate( if (start) span.startTimestamp(clock.currentTimeMicroseconds()); } else { long currentTimeMicroseconds = this.clock.currentTimeMicroseconds(); - clock = new TickClock(currentTimeMicroseconds, System.nanoTime()); + clock = new TickClock(platform, currentTimeMicroseconds, platform.nanoTime()); if (start) span.startTimestamp(currentTimeMicroseconds); } diff --git a/brave/src/main/java/brave/internal/recorder/TickClock.java b/brave/src/main/java/brave/internal/recorder/TickClock.java index 9b08a9a4fc..b6c0ad31ca 100644 --- a/brave/src/main/java/brave/internal/recorder/TickClock.java +++ b/brave/src/main/java/brave/internal/recorder/TickClock.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -14,18 +14,21 @@ package brave.internal.recorder; import brave.Clock; +import brave.internal.Platform; final class TickClock implements Clock { + final Platform platform; final long baseEpochMicros; final long baseTickNanos; - TickClock(long baseEpochMicros, long baseTickNanos) { + TickClock(Platform platform, long baseEpochMicros, long baseTickNanos) { + this.platform = platform; this.baseEpochMicros = baseEpochMicros; this.baseTickNanos = baseTickNanos; } @Override public long currentTimeMicroseconds() { - return ((System.nanoTime() - baseTickNanos) / 1000) + baseEpochMicros; + return ((platform.nanoTime() - baseTickNanos) / 1000) + baseEpochMicros; } @Override public String toString() { diff --git a/brave/src/main/java/brave/propagation/B3Propagation.java b/brave/src/main/java/brave/propagation/B3Propagation.java index 751f6ae63a..04ad6a5262 100644 --- a/brave/src/main/java/brave/propagation/B3Propagation.java +++ b/brave/src/main/java/brave/propagation/B3Propagation.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -236,7 +236,7 @@ static final class Factory extends Propagation.Factory implements Propagation Extractor extractor(Getter getter) { if (getter == null) throw new NullPointerException("getter == null"); - return new B3Extractor<>(this, getter); + return new B3Extractor(this, getter); } @Override public int hashCode() { diff --git a/brave/src/main/java/brave/propagation/CurrentTraceContext.java b/brave/src/main/java/brave/propagation/CurrentTraceContext.java index 6bb8265ede..2baef9ab62 100644 --- a/brave/src/main/java/brave/propagation/CurrentTraceContext.java +++ b/brave/src/main/java/brave/propagation/CurrentTraceContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -42,7 +42,7 @@ public abstract class CurrentTraceContext { /** Implementations of this allow standardized configuration, for example scope decoration. */ public abstract static class Builder { - ArrayList scopeDecorators = new ArrayList<>(); + ArrayList scopeDecorators = new ArrayList(); /** * Implementations call decorators in order to add features like log correlation to a scope. @@ -217,7 +217,8 @@ public interface ScopeDecorator { */ public static final class Default extends ThreadLocalCurrentTraceContext { // Inheritable as Brave 3's ThreadLocalServerClientAndLocalSpanState was inheritable - static final InheritableThreadLocal INHERITABLE = new InheritableThreadLocal<>(); + static final InheritableThreadLocal INHERITABLE = + new InheritableThreadLocal(); /** Uses a non-inheritable static thread local */ public static CurrentTraceContext create() { @@ -243,12 +244,15 @@ public static CurrentTraceContext inheritable() { } /** Wraps the input so that it executes with the same context as now. */ - public Callable wrap(Callable task) { + public Callable wrap(final Callable task) { final TraceContext invocationContext = get(); class CurrentTraceContextCallable implements Callable { @Override public C call() throws Exception { - try (Scope scope = maybeScope(invocationContext)) { + Scope scope = maybeScope(invocationContext); + try { return task.call(); + } finally { + scope.close(); } } } @@ -256,12 +260,15 @@ class CurrentTraceContextCallable implements Callable { } /** Wraps the input so that it executes with the same context as now. */ - public Runnable wrap(Runnable task) { + public Runnable wrap(final Runnable task) { final TraceContext invocationContext = get(); class CurrentTraceContextRunnable implements Runnable { @Override public void run() { - try (Scope scope = maybeScope(invocationContext)) { + Scope scope = maybeScope(invocationContext); + try { task.run(); + } finally { + scope.close(); } } } @@ -272,7 +279,7 @@ class CurrentTraceContextRunnable implements Runnable { * Decorates the input such that the {@link #get() current trace context} at the time a task is * scheduled is made current when the task is executed. */ - public Executor executor(Executor delegate) { + public Executor executor(final Executor delegate) { class CurrentTraceContextExecutor implements Executor { @Override public void execute(Runnable task) { delegate.execute(CurrentTraceContext.this.wrap(task)); @@ -285,7 +292,7 @@ class CurrentTraceContextExecutor implements Executor { * Decorates the input such that the {@link #get() current trace context} at the time a task is * scheduled is made current when the task is executed. */ - public ExecutorService executorService(ExecutorService delegate) { + public ExecutorService executorService(final ExecutorService delegate) { class CurrentTraceContextExecutorService extends brave.internal.WrappingExecutorService { @Override protected ExecutorService delegate() { diff --git a/brave/src/main/java/brave/propagation/ExtraFieldPropagation.java b/brave/src/main/java/brave/propagation/ExtraFieldPropagation.java index dd7e28c505..64d411c2e6 100644 --- a/brave/src/main/java/brave/propagation/ExtraFieldPropagation.java +++ b/brave/src/main/java/brave/propagation/ExtraFieldPropagation.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -61,9 +61,9 @@ @Deprecated public static final class FactoryBuilder { final Propagation.Factory delegate; final BaggagePropagation.FactoryBuilder baggageFactory; - // Updates could be out-of-order in the old impl so we track everything until build() - final Set redactedNames = new LinkedHashSet<>(); - final Map> nameToKeyNames = new LinkedHashMap<>(); + // Updates could be out-of-order in the old impl, so we track everything until build() + final Set redactedNames = new LinkedHashSet(); + final Map> nameToKeyNames = new LinkedHashMap>(); FactoryBuilder(Propagation.Factory delegate) { this.delegate = delegate; @@ -74,7 +74,7 @@ @Deprecated public FactoryBuilder addRedactedField(String fieldName) { fieldName = validateFieldName(fieldName); redactedNames.add(fieldName); - nameToKeyNames.put(fieldName, Collections.emptySet()); + nameToKeyNames.put(fieldName, Collections.emptySet()); return this; } @@ -99,13 +99,13 @@ void addKeyName(String name, String keyName) { Set keyNames = nameToKeyNames.get(name); - if (keyNames == null) nameToKeyNames.put(name, keyNames = new LinkedHashSet<>()); + if (keyNames == null) nameToKeyNames.put(name, keyNames = new LinkedHashSet()); keyNames.add(keyName); } /** Returns a wrapper of the delegate if there are no fields to propagate. */ public Factory build() { - Set extraKeyNames = new LinkedHashSet<>(); + Set extraKeyNames = new LinkedHashSet(); for (Map.Entry> entry : nameToKeyNames.entrySet()) { BaggageField field = BaggageField.create(entry.getKey()); if (redactedNames.contains(field.name())) { @@ -205,9 +205,9 @@ public static class Factory extends Propagation.Factory { /** {@inheritDoc} */ @Deprecated @Override public ExtraFieldPropagation create(Propagation.KeyFactory keyFactory) { - List extraKeys = new ArrayList<>(); + List extraKeys = new ArrayList(); for (String extraKeyName : extraKeyNames) extraKeys.add(keyFactory.create(extraKeyName)); - return new ExtraFieldPropagation<>(delegate.create(keyFactory), unmodifiableList(extraKeys)); + return new ExtraFieldPropagation(delegate.create(keyFactory), unmodifiableList(extraKeys)); } @Override public boolean supportsJoin() { diff --git a/brave/src/main/java/brave/propagation/Propagation.java b/brave/src/main/java/brave/propagation/Propagation.java index c770a0798b..5cc76041ae 100644 --- a/brave/src/main/java/brave/propagation/Propagation.java +++ b/brave/src/main/java/brave/propagation/Propagation.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -130,7 +130,7 @@ public TraceContext decorate(TraceContext context) { */ @Deprecated interface KeyFactory { - KeyFactory STRING = new KeyFactory() { // retrolambda no likey + KeyFactory STRING = new KeyFactory() { @Override public String create(String name) { return name; } diff --git a/brave/src/main/java/brave/propagation/StrictCurrentTraceContext.java b/brave/src/main/java/brave/propagation/StrictCurrentTraceContext.java index bff62ffe03..7e08514f5d 100644 --- a/brave/src/main/java/brave/propagation/StrictCurrentTraceContext.java +++ b/brave/src/main/java/brave/propagation/StrictCurrentTraceContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -38,7 +38,7 @@ public static Builder newBuilder() { public static final class Builder extends CurrentTraceContext.Builder { // intentionally not inheritable to ensure instrumentation propagation doesn't accidentally work // intentionally not static to make explicit when instrumentation need per thread semantics - final ThreadLocal local = new ThreadLocal<>(); + final ThreadLocal local = new ThreadLocal(); CurrentTraceContext delegate = new ThreadLocalCurrentTraceContext.Builder(local).build(); StrictScopeDecorator strictScopeDecorator = new StrictScopeDecorator(); diff --git a/brave/src/main/java/brave/propagation/StrictScopeDecorator.java b/brave/src/main/java/brave/propagation/StrictScopeDecorator.java index c18d7968b0..68d68767aa 100644 --- a/brave/src/main/java/brave/propagation/StrictScopeDecorator.java +++ b/brave/src/main/java/brave/propagation/StrictScopeDecorator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at diff --git a/brave/src/main/java/brave/propagation/ThreadLocalCurrentTraceContext.java b/brave/src/main/java/brave/propagation/ThreadLocalCurrentTraceContext.java index 441cba9408..28b91bbb85 100644 --- a/brave/src/main/java/brave/propagation/ThreadLocalCurrentTraceContext.java +++ b/brave/src/main/java/brave/propagation/ThreadLocalCurrentTraceContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -74,7 +74,7 @@ public static final class Builder extends CurrentTraceContext.Builder { } } - static final ThreadLocal DEFAULT = new ThreadLocal<>(); + static final ThreadLocal DEFAULT = new ThreadLocal(); @SuppressWarnings("ThreadLocalUsage") // intentional: to support multiple Tracer instances final ThreadLocal local; diff --git a/brave/src/main/java/brave/propagation/ThreadLocalSpan.java b/brave/src/main/java/brave/propagation/ThreadLocalSpan.java index 782f9c5dbe..4b74657104 100644 --- a/brave/src/main/java/brave/propagation/ThreadLocalSpan.java +++ b/brave/src/main/java/brave/propagation/ThreadLocalSpan.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -171,12 +171,13 @@ static final class SpanAndScope { * not possible because there is no api to place an arbitrary span in scope using this api. */ @SuppressWarnings("ThreadLocalUsage") // intentional: to support multiple Tracer instances - final ThreadLocal> currentSpanInScopeStack = new ThreadLocal<>(); + final ThreadLocal> currentSpanInScopeStack = + new ThreadLocal>(); ArrayDeque getCurrentSpanInScopeStack() { ArrayDeque stack = currentSpanInScopeStack.get(); if (stack == null) { - stack = new ArrayDeque<>(); + stack = new ArrayDeque(); currentSpanInScopeStack.set(stack); } return stack; diff --git a/brave/src/main/java/brave/propagation/TraceContextOrSamplingFlags.java b/brave/src/main/java/brave/propagation/TraceContextOrSamplingFlags.java index da56a1def6..b2316c08db 100644 --- a/brave/src/main/java/brave/propagation/TraceContextOrSamplingFlags.java +++ b/brave/src/main/java/brave/propagation/TraceContextOrSamplingFlags.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -362,7 +362,7 @@ public Builder sampledLocal() { /** @deprecated Since 5.12, use {@link #addExtra(Object)} */ @Deprecated public Builder extra(List extraList) { if (extraList == null) throw new NullPointerException("extraList == null"); - this.extraList = new ArrayList<>(); + this.extraList = new ArrayList(); for (Object extra : extraList) addExtra(extra); return this; } diff --git a/brave/src/main/java/brave/sampler/DeclarativeSampler.java b/brave/src/main/java/brave/sampler/DeclarativeSampler.java index b938cbfeac..249da0afb1 100644 --- a/brave/src/main/java/brave/sampler/DeclarativeSampler.java +++ b/brave/src/main/java/brave/sampler/DeclarativeSampler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -61,17 +61,17 @@ public interface RateOfMethod { public static DeclarativeSampler createWithProbability( ProbabilityOfMethod probabilityOfMethod) { if (probabilityOfMethod == null) throw new NullPointerException("probabilityOfMethod == null"); - return new DeclarativeCountingSampler<>(probabilityOfMethod); + return new DeclarativeCountingSampler(probabilityOfMethod); } /* @since 5.8 */ public static DeclarativeSampler createWithRate(RateOfMethod rateOfMethod) { if (rateOfMethod == null) throw new NullPointerException("rateOfMethod == null"); - return new DeclarativeRateLimitingSampler<>(rateOfMethod); + return new DeclarativeRateLimitingSampler(rateOfMethod); } // this assumes input are compared by identity as typically annotations do not override hashCode - final ConcurrentMap methodToSamplers = new ConcurrentHashMap<>(); + final ConcurrentMap methodToSamplers = new ConcurrentHashMap(); /** * {@inheritDoc} @@ -170,7 +170,7 @@ public interface RateForMethod extends ProbabilityOfMethod { * @since 4.19 * @deprecated Since 5.8, use {@link Tracer#startScopedSpan(String, SamplerFunction, Object)} */ - @Deprecated public Sampler toSampler(M method, Sampler fallback) { + @Deprecated public Sampler toSampler(final M method, final Sampler fallback) { if (fallback == null) throw new NullPointerException("fallback == null"); if (method == null) return fallback; return new Sampler() { diff --git a/brave/src/main/java/brave/sampler/Matchers.java b/brave/src/main/java/brave/sampler/Matchers.java index 66f6b679e7..b43343f9c7 100644 --- a/brave/src/main/java/brave/sampler/Matchers.java +++ b/brave/src/main/java/brave/sampler/Matchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -83,7 +83,7 @@ static

Matcher[] toArray(Iterable> matchers) { if (matchers instanceof Collection) { return (Matcher[]) ((Collection) matchers).toArray(new Matcher[0]); } - List> result = new ArrayList<>(); + List> result = new ArrayList>(); for (Matcher

matcher : matchers) result.add(matcher); return result.toArray(new Matcher[0]); } @@ -95,7 +95,7 @@ static

Matcher

composite(Matcher

[] matchers, boolean and) { if (matchers[i] == null) throw new NullPointerException("matchers[" + i + "] == null"); } if (matchers.length == 1) return matchers[0]; - return and ? new And<>(matchers) : new Or<>(matchers); + return and ? new And

(matchers) : new Or

(matchers); } static class And

implements Matcher

{ diff --git a/brave/src/main/java/brave/sampler/ParameterizedSampler.java b/brave/src/main/java/brave/sampler/ParameterizedSampler.java index e41742fce6..0206adb540 100644 --- a/brave/src/main/java/brave/sampler/ParameterizedSampler.java +++ b/brave/src/main/java/brave/sampler/ParameterizedSampler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -36,12 +36,12 @@ public final class ParameterizedSampler

implements SamplerFunction

{ /** @since 5.8 */ public static

Builder

newBuilder() { - return new Builder<>(); + return new Builder

(); } /** @since 5.8 */ public static final class Builder

{ - final Map, Sampler> rules = new LinkedHashMap<>(); + final Map, Sampler> rules = new LinkedHashMap, Sampler>(); /** * Adds or replaces all rules in this sampler with those of the input. @@ -67,7 +67,7 @@ public Builder

putRule(Matcher

matcher, Sampler sampler) { } public ParameterizedSampler

build() { - return new ParameterizedSampler<>(this); + return new ParameterizedSampler

(this); } Builder() { @@ -90,7 +90,7 @@ static class R

{ this.rules = new R[builder.rules.size()]; int i = 0; for (Map.Entry, Sampler> rule : builder.rules.entrySet()) { - rules[i++] = new R<>(rule.getKey(), rule.getValue()); + rules[i++] = new R

(rule.getKey(), rule.getValue()); } } diff --git a/brave/src/main/java/brave/sampler/RateLimitingSampler.java b/brave/src/main/java/brave/sampler/RateLimitingSampler.java index d6876ebff5..dd70d42ac8 100644 --- a/brave/src/main/java/brave/sampler/RateLimitingSampler.java +++ b/brave/src/main/java/brave/sampler/RateLimitingSampler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -13,6 +13,7 @@ */ package brave.sampler; +import brave.internal.Platform; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -46,25 +47,27 @@ public class RateLimitingSampler extends Sampler { public static Sampler create(int tracesPerSecond) { if (tracesPerSecond < 0) throw new IllegalArgumentException("tracesPerSecond < 0"); if (tracesPerSecond == 0) return Sampler.NEVER_SAMPLE; - return new RateLimitingSampler(tracesPerSecond); + return new RateLimitingSampler(Platform.get(), tracesPerSecond); } static final long NANOS_PER_SECOND = TimeUnit.SECONDS.toNanos(1); static final long NANOS_PER_DECISECOND = NANOS_PER_SECOND / 10; + final Platform platform; final MaxFunction maxFunction; final AtomicInteger usage = new AtomicInteger(0); final AtomicLong nextReset; - RateLimitingSampler(int tracesPerSecond) { + RateLimitingSampler(Platform platform, int tracesPerSecond) { + this.platform = platform; this.maxFunction = tracesPerSecond < 10 ? new LessThan10(tracesPerSecond) : new AtLeast10(tracesPerSecond); - long now = System.nanoTime(); + long now = platform.nanoTime(); this.nextReset = new AtomicLong(now + NANOS_PER_SECOND); } @Override public boolean isSampled(long ignoredTraceId) { - long now = System.nanoTime(), updateAt = nextReset.get(); + long now = platform.nanoTime(), updateAt = nextReset.get(); // First task is to determine if this request is later than the one second sampling window long nanosUntilReset = -(now - updateAt); // because nanoTime can be negative diff --git a/brave/src/main/java/brave/sampler/SamplerFunctions.java b/brave/src/main/java/brave/sampler/SamplerFunctions.java index fed02d251d..e8b1e7d84a 100644 --- a/brave/src/main/java/brave/sampler/SamplerFunctions.java +++ b/brave/src/main/java/brave/sampler/SamplerFunctions.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -30,7 +30,7 @@ public final class SamplerFunctions { public static SamplerFunction nullSafe(SamplerFunction delegate) { if (delegate == null) throw new NullPointerException("delegate == null"); if (delegate instanceof Constants || delegate instanceof NullSafe) return delegate; - return new NullSafe<>(delegate); + return new NullSafe(delegate); } static final class NullSafe implements SamplerFunction { diff --git a/brave/src/test/java/brave/TracerTest.java b/brave/src/test/java/brave/TracerTest.java index 098a0359c8..239f8eb0d8 100644 --- a/brave/src/test/java/brave/TracerTest.java +++ b/brave/src/test/java/brave/TracerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2022 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at diff --git a/brave/src/test/java/brave/internal/PlatformTest.java b/brave/src/test/java/brave/internal/PlatformTest.java index 23daf32cf7..9f9d6e6f86 100644 --- a/brave/src/test/java/brave/internal/PlatformTest.java +++ b/brave/src/test/java/brave/internal/PlatformTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -20,6 +20,7 @@ import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; +import java.util.Enumeration; import java.util.List; import java.util.Set; import java.util.Vector; @@ -27,145 +28,157 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -@RunWith(PowerMockRunner.class) -// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing -@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"}) -@PrepareForTest({Platform.class, NetworkInterface.class}) -public class PlatformTest { - Platform platform = new Platform.Jre7(); - - @Test public void clock_hasNiceToString_jre7() { - assertThat(platform.clock()) - .hasToString("System.currentTimeMillis()"); +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PlatformTest { + @Test void clock_hasNiceToString_jre7() { + Platform platform = new Platform.Jre7(); + + assertThat(platform.clock()).hasToString("System.currentTimeMillis()"); } - @Test public void clock_hasNiceToString_jre9() { + @Test void clock_hasNiceToString_jre9() { Platform platform = new Platform.Jre9(); - assertThat(platform.clock()) - .hasToString("Clock.systemUTC().instant()"); + assertThat(platform.clock()).hasToString("Clock.systemUTC().instant()"); } // example from X-Amzn-Trace-Id: Root=1-5759e988-bd862e3fe1be46a994272793;Sampled=1 - @Test public void randomLong_epochSecondsPlusRandom() { - mockStatic(System.class); - when(System.currentTimeMillis()) - .thenReturn(1465510280_000L); // Thursday, June 9, 2016 10:11:20 PM + @Test void randomLong_epochSecondsPlusRandom() { + Platform platform = new Platform.Jre7() { + @Override public long currentTimeMicroseconds() { + return 1465510280000000L; // Thursday, June 9, 2016 10:11:20 PM + } + }; long traceIdHigh = platform.nextTraceIdHigh(); assertThat(HexCodec.toLowerHex(traceIdHigh)).startsWith("5759e988"); } - @Test public void randomLong_whenRandomIsMostNegative() { - mockStatic(System.class); - when(System.currentTimeMillis()).thenReturn(1465510280_000L); + @Test void randomLong_whenRandomIsMostNegative() { + long traceIdHigh = Platform.nextTraceIdHigh(1465510280000000L, 0xffffffff); - long traceIdHigh = Platform.nextTraceIdHigh(0xffffffff); - - assertThat(HexCodec.toLowerHex(traceIdHigh)) - .isEqualTo("5759e988ffffffff"); + assertThat(HexCodec.toLowerHex(traceIdHigh)).isEqualTo("5759e988ffffffff"); } - @Test public void linkLocalIp_lazySet() { + @Test void linkLocalIp_lazySet() { + Platform platform = Platform.findPlatform(); // not get as it caches nics. assertThat(platform.linkLocalIp).isNull(); // sanity check setup // cannot test as the there is no link local IP if (platform.produceLinkLocalIp() == null) return; - assertThat(platform.linkLocalIp()) - .isNotNull(); + assertThat(platform.linkLocalIp()).isNotNull(); } - @Test public void linkLocalIp_sameInstance() { - assertThat(platform.linkLocalIp()) - .isSameAs(platform.linkLocalIp()); + @Test void linkLocalIp_sameInstance() { + Platform platform = new Platform.Jre7(); + + assertThat(platform.linkLocalIp()).isSameAs(platform.linkLocalIp()); } - @Test public void produceLinkLocalIp_exceptionReadingNics() throws Exception { - mockStatic(NetworkInterface.class); - when(NetworkInterface.getNetworkInterfaces()).thenThrow(SocketException.class); + @Test void produceLinkLocalIp_exceptionReadingNics() { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + mb.when(NetworkInterface::getNetworkInterfaces).thenThrow(SocketException.class); - assertThat(platform.produceLinkLocalIp()) - .isNull(); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.produceLinkLocalIp()).isNull(); + } } /** possible albeit very unlikely */ - @Test public void produceLinkLocalIp_noNics() throws Exception { - mockStatic(NetworkInterface.class); - - when(NetworkInterface.getNetworkInterfaces()) - .thenReturn(null); + @Test void produceLinkLocalIp_noNics() { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + mb.when(NetworkInterface::getNetworkInterfaces).thenReturn(null); - assertThat(platform.linkLocalIp()) - .isNull(); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.linkLocalIp()).isNull(); - when(NetworkInterface.getNetworkInterfaces()) - .thenReturn(new Vector().elements()); + mb.when(NetworkInterface::getNetworkInterfaces) + .thenReturn(new Vector().elements()); - assertThat(platform.produceLinkLocalIp()) - .isNull(); + assertThat(platform.produceLinkLocalIp()).isNull(); + } } /** also possible albeit unlikely */ - @Test public void produceLinkLocalIp_noAddresses() throws Exception { - nicWithAddress(null); + @Test void produceLinkLocalIp_noAddresses() { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + Enumeration nics = nicsWithAddress(null); + mb.when(NetworkInterface::getNetworkInterfaces).thenReturn(nics); - assertThat(platform.produceLinkLocalIp()) - .isNull(); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.produceLinkLocalIp()).isNull(); + } } - @Test public void produceLinkLocalIp_siteLocal_ipv4() throws Exception { - nicWithAddress(InetAddress.getByAddress("local", new byte[] {(byte) 192, (byte) 168, 0, 1})); + @Test void produceLinkLocalIp_siteLocal_ipv4() throws Exception { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + InetAddress local = + InetAddress.getByAddress("local", new byte[] {(byte) 192, (byte) 168, 0, 1}); + Enumeration nics = nicsWithAddress(local); + mb.when(NetworkInterface::getNetworkInterfaces).thenReturn(nics); - assertThat(platform.produceLinkLocalIp()) - .isEqualTo("192.168.0.1"); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.produceLinkLocalIp()).isEqualTo("192.168.0.1"); + } } - @Test public void produceLinkLocalIp_siteLocal_ipv6() throws Exception { - InetAddress ipv6 = Inet6Address.getByName("fec0:db8::c001"); - nicWithAddress(ipv6); + @Test void produceLinkLocalIp_siteLocal_ipv6() throws Exception { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + InetAddress ipv6 = Inet6Address.getByName("fec0:db8::c001"); + Enumeration nics = nicsWithAddress(ipv6); + mb.when(NetworkInterface::getNetworkInterfaces).thenReturn(nics); - assertThat(platform.produceLinkLocalIp()) - .isEqualTo(ipv6.getHostAddress()); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.produceLinkLocalIp()).isEqualTo(ipv6.getHostAddress()); + } } - @Test public void produceLinkLocalIp_notSiteLocal_ipv4() throws Exception { - nicWithAddress(InetAddress.getByAddress("external", new byte[] {1, 2, 3, 4})); + @Test void produceLinkLocalIp_notSiteLocal_ipv4() throws Exception { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + InetAddress external = InetAddress.getByAddress("external", new byte[] {1, 2, 3, 4}); + Enumeration nics = nicsWithAddress(external); + mb.when(NetworkInterface::getNetworkInterfaces).thenReturn(nics); - assertThat(platform.produceLinkLocalIp()) - .isNull(); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.produceLinkLocalIp()).isNull(); + } } - @Test public void produceLinkLocalIp_notSiteLocal_ipv6() throws Exception { - nicWithAddress(Inet6Address.getByName("2001:db8::c001")); + @Test void produceLinkLocalIp_notSiteLocal_ipv6() throws Exception { + try (MockedStatic mb = mockStatic(NetworkInterface.class)) { + InetAddress addr = Inet6Address.getByName("2001:db8::c001"); + Enumeration nics = nicsWithAddress(addr); + mb.when(NetworkInterface::getNetworkInterfaces).thenReturn(nics); - assertThat(platform.produceLinkLocalIp()) - .isNull(); + Platform platform = Platform.findPlatform(); // not get as it caches nics. + assertThat(platform.produceLinkLocalIp()).isNull(); + } } /** * Getting an endpoint is expensive. This tests it is provisioned only once. - * + *

* test inspired by dagger.internal.DoubleCheckTest */ - @Test - public void linkLocalIp_provisionsOnce() throws Exception { + @Test void linkLocalIp_provisionsOnce() throws Exception { + Platform platform = Platform.findPlatform(); // not get as it caches nics. + // create all the tasks up front so that they are executed with no delay List> tasks = new ArrayList<>(); for (int i = 0; i < 10; i++) { - tasks.add(() -> platform.linkLocalIp()); + tasks.add(platform::linkLocalIp); } ExecutorService executor = Executors.newFixedThreadPool(tasks.size()); @@ -181,14 +194,13 @@ public void linkLocalIp_provisionsOnce() throws Exception { executor.shutdownNow(); } - static void nicWithAddress(@Nullable InetAddress address) throws SocketException { - mockStatic(NetworkInterface.class); + static Enumeration nicsWithAddress(@Nullable InetAddress address) { Vector addresses = new Vector<>(); if (address != null) addresses.add(address); NetworkInterface nic = mock(NetworkInterface.class); Vector nics = new Vector<>(); nics.add(nic); - when(NetworkInterface.getNetworkInterfaces()).thenReturn(nics.elements()); when(nic.getInetAddresses()).thenReturn(addresses.elements()); + return nics.elements(); } } diff --git a/brave/src/test/java/brave/internal/recorder/TickClockTest.java b/brave/src/test/java/brave/internal/recorder/TickClockTest.java index b09bbde59f..094d01607c 100644 --- a/brave/src/test/java/brave/internal/recorder/TickClockTest.java +++ b/brave/src/test/java/brave/internal/recorder/TickClockTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -13,27 +13,23 @@ */ package brave.internal.recorder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import brave.internal.Platform; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) -// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing -@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"}) -@PrepareForTest(TickClock.class) -public class TickClockTest { +@ExtendWith(MockitoExtension.class) +class TickClockTest { + @Mock Platform platform; - @Test public void relativeTimestamp_incrementsAccordingToNanoTick() { - mockStatic(System.class); - TickClock clock = new TickClock(1000L /* 1ms */, 0L /* 0ns */); + @Test void relativeTimestamp_incrementsAccordingToNanoTick() { + TickClock clock = new TickClock(platform, 1000L /* 1ms */, 0L /* 0ns */); - when(System.nanoTime()).thenReturn(1000L); // 1 microsecond = 1000 nanoseconds + when(platform.nanoTime()).thenReturn(1000L); // 1 microsecond = 1000 nanoseconds assertThat(clock.currentTimeMicroseconds()).isEqualTo(1001L); // 1ms + 1us } diff --git a/brave/src/test/java/brave/propagation/B3PropagationTest.java b/brave/src/test/java/brave/propagation/B3PropagationTest.java index ea0dbcbd0b..c8844ad85d 100644 --- a/brave/src/test/java/brave/propagation/B3PropagationTest.java +++ b/brave/src/test/java/brave/propagation/B3PropagationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -23,27 +23,22 @@ import java.util.Map; import java.util.stream.Stream; import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -@RunWith(PowerMockRunner.class) -// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing -@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"}) -@PrepareForTest({Platform.class, B3Propagation.class}) -public class B3PropagationTest { + +@ExtendWith(MockitoExtension.class) +class B3PropagationTest { String traceIdHigh = "0000000000000009"; String traceId = "0000000000000001"; String parentId = "0000000000000002"; @@ -52,34 +47,24 @@ public class B3PropagationTest { TraceContext context = TraceContext.newBuilder().traceId(1).parentId(2).spanId(3).build(); Propagation propagation = B3Propagation.B3_STRING; - Platform platform = mock(Platform.class); - - @Before public void setupLogger() { - mockStatic(Platform.class); - when(Platform.get()).thenReturn(platform); + @Mock Platform platform; + + @Test void keys_defaultToAll() { + propagation = B3Propagation.newFactoryBuilder() + .build().get(); + + assertThat(propagation.keys()).containsExactly( + "b3", + "X-B3-TraceId", + "X-B3-SpanId", + "X-B3-ParentSpanId", + "X-B3-Sampled", + "X-B3-Flags" + ); } - /** Either we asserted on the log messages or there weren't any */ - @After public void ensureNothingLogged() { - verifyNoMoreInteractions(platform); - } - - @Test public void keys_defaultToAll() { - propagation = B3Propagation.newFactoryBuilder() - .build().get(); - - assertThat(propagation.keys()).containsExactly( - "b3", - "X-B3-TraceId", - "X-B3-SpanId", - "X-B3-ParentSpanId", - "X-B3-Sampled", - "X-B3-Flags" - ); - } - - @Test public void keys_withoutB3Single() { - propagation = B3Propagation.newFactoryBuilder() + @Test void keys_withoutB3Single() { + propagation = B3Propagation.newFactoryBuilder() .injectFormat(Span.Kind.PRODUCER, Format.MULTI) .injectFormat(Span.Kind.CONSUMER, Format.MULTI) .build().get(); @@ -93,7 +78,7 @@ public class B3PropagationTest { ); } - @Test public void keys_onlyB3Single() { + @Test void keys_onlyB3Single() { propagation = B3Propagation.newFactoryBuilder() .injectFormat(Format.SINGLE) .injectFormat(Span.Kind.CLIENT, Format.SINGLE) @@ -103,7 +88,7 @@ public class B3PropagationTest { assertThat(propagation.keys()).containsOnly("b3"); } - @Test public void injectFormat() { + @Test void injectFormat() { B3Propagation.Factory factory = (B3Propagation.Factory) B3Propagation.newFactoryBuilder() .injectFormat(Format.SINGLE) .build(); @@ -112,7 +97,7 @@ public class B3PropagationTest { .isEqualTo(Format.SINGLE); } - @Test public void injectKindFormat() { + @Test void injectKindFormat() { B3Propagation.Factory factory = (B3Propagation.Factory) B3Propagation.newFactoryBuilder() .injectFormat(Span.Kind.CLIENT, Format.SINGLE) .build(); @@ -121,7 +106,7 @@ public class B3PropagationTest { .isEqualTo(Format.SINGLE); } - @Test public void injectKindFormats() { + @Test void injectKindFormats() { B3Propagation.Factory factory = (B3Propagation.Factory) B3Propagation.newFactoryBuilder() .injectFormats(Span.Kind.CLIENT, Format.SINGLE, Format.MULTI) .build(); @@ -131,13 +116,13 @@ public class B3PropagationTest { .containsExactly(Format.SINGLE, Format.MULTI); } - @Test public void injectKindFormats_cantBeSame() { + @Test void injectKindFormats_cantBeSame() { assertThatThrownBy(() -> B3Propagation.newFactoryBuilder() .injectFormats(Span.Kind.CLIENT, Format.MULTI, Format.MULTI)) .isInstanceOf(IllegalArgumentException.class); } - @Test public void injectKindFormats_cantBeBothSingle() { + @Test void injectKindFormats_cantBeBothSingle() { assertThatThrownBy(() -> B3Propagation.newFactoryBuilder() .injectFormats(Span.Kind.CLIENT, Format.SINGLE, Format.SINGLE_NO_PARENT)) .isInstanceOf(IllegalArgumentException.class); @@ -159,7 +144,7 @@ void header(String key, String value) { } } - @Test public void clientUsesB3Multi() { + @Test void clientUsesB3Multi() { ClientRequest request = new ClientRequest(); Propagation.B3_STRING.injector(ClientRequest::header).inject(context, request); @@ -186,7 +171,7 @@ void header(String key, String value) { } } - @Test public void producerUsesB3SingleNoParent_deferred() { + @Test void producerUsesB3SingleNoParent_deferred() { // This injector won't know the type it is injecting until the call to inject() Injector injector = Propagation.B3_STRING.injector(ProducerRequest::header); @@ -208,7 +193,7 @@ static class ProducerSetter implements RemoteSetter { } } - @Test public void producerUsesB3SingleNoParent() { + @Test void producerUsesB3SingleNoParent() { // This injector needs no instanceof checks during inject() Injector injector = Propagation.B3_STRING.injector(new ProducerSetter()); @@ -220,7 +205,7 @@ static class ProducerSetter implements RemoteSetter { .containsEntry("b3", "0000000000000001-0000000000000003"); } - @Test public void canConfigureSingle() { + @Test void canConfigureSingle() { propagation = B3Propagation.newFactoryBuilder() .injectFormat(Format.SINGLE_NO_PARENT) .build().get(); @@ -233,7 +218,7 @@ static class ProducerSetter implements RemoteSetter { .containsEntry("b3", "0000000000000001-0000000000000003"); } - @Test public void canConfigureBasedOnKind() { + @Test void canConfigureBasedOnKind() { propagation = B3Propagation.newFactoryBuilder() .injectFormats(Span.Kind.CLIENT, Format.SINGLE, Format.MULTI) .build().get(); @@ -249,7 +234,7 @@ static class ProducerSetter implements RemoteSetter { .containsEntry("b3", traceId + "-" + spanId + "-" + parentId); } - @Test public void extract_notYetSampled() { + @Test void extract_notYetSampled() { Map headers = new LinkedHashMap<>(); headers.put("X-B3-TraceId", traceId); headers.put("X-B3-SpanId", spanId); @@ -257,7 +242,7 @@ static class ProducerSetter implements RemoteSetter { assertThat(extract(headers).sampled()).isNull(); } - @Test public void extract_sampled() { + @Test void extract_sampled() { Map headers = new LinkedHashMap<>(); headers.put("X-B3-TraceId", traceId); headers.put("X-B3-SpanId", spanId); @@ -271,7 +256,7 @@ static class ProducerSetter implements RemoteSetter { assertThat(extract(headers).sampled()).isTrue(); } - @Test public void extract_128Bit() { + @Test void extract_128Bit() { Map headers = new LinkedHashMap<>(); headers.put("X-B3-TraceId", traceIdHigh + traceId); headers.put("X-B3-SpanId", spanId); @@ -283,7 +268,7 @@ static class ProducerSetter implements RemoteSetter { ); } - @Test public void extract_padded() { + @Test void extract_padded() { Map headers = new LinkedHashMap<>(); headers.put("X-B3-TraceId", "0000000000000000" + traceId); headers.put("X-B3-SpanId", spanId); @@ -294,7 +279,7 @@ static class ProducerSetter implements RemoteSetter { ); } - @Test public void extract_padded_right() { + @Test void extract_padded_right() { Map headers = new LinkedHashMap<>(); headers.put("X-B3-TraceId", traceIdHigh + "0000000000000000"); headers.put("X-B3-SpanId", spanId); @@ -305,37 +290,49 @@ static class ProducerSetter implements RemoteSetter { ); } - @Test public void extract_zeros_traceId() { - Map headers = new LinkedHashMap<>(); - headers.put("X-B3-TraceId", "0000000000000000"); - headers.put("X-B3-SpanId", spanId); + @Test void extract_zeros_traceId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + Map headers = new LinkedHashMap<>(); + headers.put("X-B3-TraceId", "0000000000000000"); + headers.put("X-B3-SpanId", spanId); - assertThat(extract(headers).context()).isNull(); + assertThat(extract(headers).context()).isNull(); - verify(platform).log("Invalid input: traceId was all zeros", null); + verify(platform).log("Invalid input: traceId was all zeros", null); + } } - @Test public void extract_zeros_traceId_128() { - Map headers = new LinkedHashMap<>(); - headers.put("X-B3-TraceId", "00000000000000000000000000000000"); - headers.put("X-B3-SpanId", spanId); + @Test void extract_zeros_traceId_128() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + Map headers = new LinkedHashMap<>(); + headers.put("X-B3-TraceId", "00000000000000000000000000000000"); + headers.put("X-B3-SpanId", spanId); - assertThat(extract(headers).context()).isNull(); + assertThat(extract(headers).context()).isNull(); - verify(platform).log("Invalid input: traceId was all zeros", null); + verify(platform).log("Invalid input: traceId was all zeros", null); + } } - @Test public void extract_zeros_spanId() { - Map headers = new LinkedHashMap<>(); - headers.put("X-B3-TraceId", traceId); - headers.put("X-B3-SpanId", "0000000000000000"); + @Test void extract_zeros_spanId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + Map headers = new LinkedHashMap<>(); + headers.put("X-B3-TraceId", traceId); + headers.put("X-B3-SpanId", "0000000000000000"); - assertThat(extract(headers).context()).isNull(); + assertThat(extract(headers).context()).isNull(); - verify(platform).log("Invalid input: spanId was all zeros", null); + verify(platform).log("Invalid input: spanId was all zeros", null); + } } - @Test public void extract_sampled_false() { + @Test void extract_sampled_false() { Map headers = new LinkedHashMap<>(); headers.put("X-B3-TraceId", traceId); headers.put("X-B3-SpanId", spanId); @@ -349,26 +346,30 @@ static class ProducerSetter implements RemoteSetter { assertThat(extract(headers).sampled()).isFalse(); } - @Test public void extract_sampledCorrupt() { - Map headers = new LinkedHashMap<>(); - headers.put("X-B3-TraceId", traceId); - headers.put("X-B3-SpanId", spanId); + @Test void extract_sampledCorrupt() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - Stream.of("", "d", "💩", "hello").forEach(sampled -> { - headers.put("X-B3-Sampled", sampled); - assertThat(extract(headers)).isSameAs(TraceContextOrSamplingFlags.EMPTY); + Map headers = new LinkedHashMap<>(); + headers.put("X-B3-TraceId", traceId); + headers.put("X-B3-SpanId", spanId); - verify(platform).log("Invalid input: expected 0 or 1 for X-B3-Sampled, but found '{0}'", - sampled, null); - }); + Stream.of("", "d", "💩", "hello").forEach(sampled -> { + headers.put("X-B3-Sampled", sampled); + assertThat(extract(headers)).isSameAs(TraceContextOrSamplingFlags.EMPTY); + + verify(platform).log("Invalid input: expected 0 or 1 for X-B3-Sampled, but found '{0}'", + sampled, null); + }); + } } - @Test public void build_defaultIsSingleton() { + @Test void build_defaultIsSingleton() { assertThat(B3Propagation.newFactoryBuilder().build()) .isSameAs(B3Propagation.FACTORY); } - @Test public void equalsAndHashCode() { + @Test void equalsAndHashCode() { // same instance are equivalent Propagation.Factory factory = B3Propagation.newFactoryBuilder() .injectFormat(Span.Kind.CLIENT, Format.SINGLE_NO_PARENT) diff --git a/brave/src/test/java/brave/propagation/B3SingleFormatTest.java b/brave/src/test/java/brave/propagation/B3SingleFormatTest.java index 3aad2f2c80..9815e60f58 100644 --- a/brave/src/test/java/brave/propagation/B3SingleFormatTest.java +++ b/brave/src/test/java/brave/propagation/B3SingleFormatTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -14,13 +14,11 @@ package brave.propagation; import brave.internal.Platform; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; import static brave.propagation.B3SingleFormat.parseB3SingleFormat; import static brave.propagation.B3SingleFormat.writeB3SingleFormat; @@ -29,35 +27,25 @@ import static brave.propagation.B3SingleFormat.writeB3SingleFormatWithoutParentIdAsBytes; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -@RunWith(PowerMockRunner.class) -// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing -@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"}) -@PrepareForTest({Platform.class, B3SingleFormat.class}) -public class B3SingleFormatTest { + +@ExtendWith(MockitoExtension.class) +class B3SingleFormatTest { String traceIdHigh = "1234567890123459"; String traceId = "1234567890123451"; String parentId = "1234567890123452"; String spanId = "1234567890123453"; - Platform platform = mock(Platform.class); - @Before public void setupLogger() { - mockStatic(Platform.class); - when(Platform.get()).thenReturn(platform); - } - /** Either we asserted on the log messages or there weren't any */ - @After public void ensureNothingLogged() { + @AfterEach void ensureNothingLogged() { verifyNoMoreInteractions(platform); } - @Test public void writeB3SingleFormat_notYetSampled() { + @Test void writeB3SingleFormat_notYetSampled() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .spanId(Long.parseUnsignedLong(spanId, 16)).build(); @@ -67,7 +55,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormat_notYetSampled_128() { + @Test void writeB3SingleFormat_notYetSampled_128() { TraceContext context = TraceContext.newBuilder() .traceIdHigh(Long.parseUnsignedLong(traceIdHigh, 16)) .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -78,7 +66,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormat_unsampled() { + @Test void writeB3SingleFormat_unsampled() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .spanId(Long.parseUnsignedLong(spanId, 16)) @@ -89,7 +77,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormat_sampled() { + @Test void writeB3SingleFormat_sampled() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .spanId(Long.parseUnsignedLong(spanId, 16)) @@ -100,7 +88,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormat_debug() { + @Test void writeB3SingleFormat_debug() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .spanId(Long.parseUnsignedLong(spanId, 16)) @@ -111,7 +99,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormat_parent() { + @Test void writeB3SingleFormat_parent() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .parentId(Long.parseUnsignedLong(parentId, 16)) @@ -123,7 +111,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormat_largest() { + @Test void writeB3SingleFormat_largest() { TraceContext context = TraceContext.newBuilder() .traceIdHigh(Long.parseUnsignedLong(traceIdHigh, 16)) .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -136,7 +124,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatAsBytes(context), UTF_8)); } - @Test public void parseB3SingleFormat_largest() { + @Test void parseB3SingleFormat_largest() { assertThat( parseB3SingleFormat(traceIdHigh + traceId + "-" + spanId + "-1-" + parentId).context() ).isEqualToComparingFieldByField(TraceContext.newBuilder() @@ -148,7 +136,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_padded() { + @Test void parseB3SingleFormat_padded() { assertThat( parseB3SingleFormat("0000000000000000" + traceId + "-" + spanId + "-1-" + parentId).context() ).isEqualToComparingFieldByField(TraceContext.newBuilder() @@ -159,7 +147,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseTraceparentFormat_padded_right() { + @Test void parseTraceparentFormat_padded_right() { assertThat( parseB3SingleFormat(traceIdHigh + "0000000000000000-" + spanId + "-1-" + parentId).context() ).isEqualToComparingFieldByField(TraceContext.newBuilder() @@ -170,7 +158,7 @@ public class B3SingleFormatTest { ); } - @Test public void writeB3SingleFormatWithoutParent_notYetSampled() { + @Test void writeB3SingleFormatWithoutParent_notYetSampled() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .spanId(Long.parseUnsignedLong(spanId, 16)).build(); @@ -180,7 +168,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatWithoutParentIdAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormatWithoutParent_unsampled() { + @Test void writeB3SingleFormatWithoutParent_unsampled() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .parentId(Long.parseUnsignedLong(parentId, 16)) @@ -192,7 +180,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatWithoutParentIdAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormatWithoutParent_sampled() { + @Test void writeB3SingleFormatWithoutParent_sampled() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .parentId(Long.parseUnsignedLong(parentId, 16)) @@ -204,7 +192,7 @@ public class B3SingleFormatTest { .isEqualTo(new String(writeB3SingleFormatWithoutParentIdAsBytes(context), UTF_8)); } - @Test public void writeB3SingleFormatWithoutParent_debug() { + @Test void writeB3SingleFormatWithoutParent_debug() { TraceContext context = TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) .parentId(Long.parseUnsignedLong(parentId, 16)) @@ -217,7 +205,7 @@ public class B3SingleFormatTest { } /** for example, parsing a w3c context */ - @Test public void parseB3SingleFormat_middleOfString() { + @Test void parseB3SingleFormat_middleOfString() { String input = "b3=" + traceIdHigh + traceId + "-" + spanId + ","; assertThat(parseB3SingleFormat(input, 3, input.length() - 1).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() @@ -228,22 +216,26 @@ public class B3SingleFormatTest { } /** for example, parsing a w3c context */ - @Test public void parseB3SingleFormat_middleOfString_debugOnly() { + @Test void parseB3SingleFormat_middleOfString_debugOnly() { String input = "b2=foo,b3=d,b4=bar"; assertThat(parseB3SingleFormat(input, 10, 11).samplingFlags()) .isSameAs(SamplingFlags.DEBUG); } - @Test public void parseB3SingleFormat_middleOfString_incorrectIndex() { - String input = "b2=foo,b3=d,b4=bar"; - assertThat(parseB3SingleFormat(input, 10, 12)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_middleOfString_incorrectIndex() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform) - .log("Invalid input: only valid characters are lower-hex for {0}", "trace ID", null); + String input = "b2=foo,b3=d,b4=bar"; + assertThat(parseB3SingleFormat(input, 10, 12)) + .isNull(); // instead of raising exception + + verify(platform) + .log("Invalid input: only valid characters are lower-hex for {0}", "trace ID", null); + } } - @Test public void parseB3SingleFormat_spanIdsNotYetSampled() { + @Test void parseB3SingleFormat_spanIdsNotYetSampled() { assertThat(parseB3SingleFormat(traceId + "-" + spanId).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -251,7 +243,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_spanIdsNotYetSampled128() { + @Test void parseB3SingleFormat_spanIdsNotYetSampled128() { assertThat(parseB3SingleFormat(traceIdHigh + traceId + "-" + spanId).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceIdHigh(Long.parseUnsignedLong(traceIdHigh, 16)) @@ -260,7 +252,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_spanIdsUnsampled() { + @Test void parseB3SingleFormat_spanIdsUnsampled() { assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-0").context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -269,7 +261,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_parent_unsampled() { + @Test void parseB3SingleFormat_parent_unsampled() { assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-0-" + parentId).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -279,7 +271,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_parent_debug() { + @Test void parseB3SingleFormat_parent_debug() { assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-d-" + parentId).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -290,7 +282,7 @@ public class B3SingleFormatTest { } // odd but possible to not yet sample a child - @Test public void parseB3SingleFormat_parentid_notYetSampled() { + @Test void parseB3SingleFormat_parentid_notYetSampled() { assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-" + parentId).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -299,7 +291,7 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_spanIdsWithDebug() { + @Test void parseB3SingleFormat_spanIdsWithDebug() { assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-d").context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceId(Long.parseUnsignedLong(traceId, 16)) @@ -308,214 +300,314 @@ public class B3SingleFormatTest { ); } - @Test public void parseB3SingleFormat_sampledFalse() { + @Test void parseB3SingleFormat_sampledFalse() { assertThat(parseB3SingleFormat("0")) .isEqualTo(TraceContextOrSamplingFlags.NOT_SAMPLED); } - @Test public void parseB3SingleFormat_sampled() { + @Test void parseB3SingleFormat_sampled() { assertThat(parseB3SingleFormat("1")) .isEqualTo(TraceContextOrSamplingFlags.SAMPLED); } - @Test public void parseB3SingleFormat_debug() { + @Test void parseB3SingleFormat_debug() { assertThat(parseB3SingleFormat("d")) .isEqualTo(TraceContextOrSamplingFlags.DEBUG); } /** This tests that the being index is inclusive and the end index is exclusive */ - @Test public void parseB3SingleFormat_ignoresBeforeAndAfter() { + @Test void parseB3SingleFormat_ignoresBeforeAndAfter() { String encoded = traceId + "-" + spanId; String sequence = "??" + encoded + "??"; assertThat(parseB3SingleFormat(sequence, 2, 2 + encoded.length())) .isEqualToComparingFieldByField(parseB3SingleFormat(encoded)); } - @Test public void parseB3SingleFormat_malformed() { - assertThat(parseB3SingleFormat("not-a-tumor")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_malformed() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat("not-a-tumor")) + .isNull(); // instead of raising exception - verify(platform) - .log("Invalid input: only valid characters are lower-hex for {0}", "trace ID", null); + verify(platform) + .log("Invalid input: only valid characters are lower-hex for {0}", "trace ID", null); + } } - @Test public void parseB3SingleFormat_malformed_notAscii() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId.substring(0, 15) + "💩")) - .isNull(); // instead of crashing + @Test void parseB3SingleFormat_malformed_notAscii() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform) - .log("Invalid input: only valid characters are lower-hex for {0}", "span ID", null); + assertThat(parseB3SingleFormat(traceId + "-" + spanId.substring(0, 15) + "💩")) + .isNull(); // instead of crashing + + verify(platform) + .log("Invalid input: only valid characters are lower-hex for {0}", "span ID", null); + } } - @Test public void parseB3SingleFormat_malformed_uuid() { - assertThat(parseB3SingleFormat("b970dafd-0d95-40aa-95d8-1d8725aebe40")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_malformed_uuid() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat("b970dafd-0d95-40aa-95d8-1d8725aebe40")) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: {0} is too short", "trace ID", null); + verify(platform).log("Invalid input: {0} is too short", "trace ID", null); + } } - @Test public void parseB3SingleFormat_malformed_hyphenForSampled() { - assertThat(parseB3SingleFormat("-")).isNull(); + @Test void parseB3SingleFormat_malformed_hyphenForSampled() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: expected 0, 1 or d for {0}", "sampled", null); + assertThat(parseB3SingleFormat("-")).isNull(); + + verify(platform).log("Invalid input: expected 0, 1 or d for {0}", "sampled", null); + } } - @Test public void parseB3SingleFormat_zero_traceId() { - assertThat( - parseB3SingleFormat("0000000000000000-" + spanId + "-1-" + parentId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_zero_traceId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: read all zeros {0}", "trace ID", null); + assertThat( + parseB3SingleFormat("0000000000000000-" + spanId + "-1-" + parentId)) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: read all zeros {0}", "trace ID", null); + } } - @Test public void parseB3SingleFormat_zero_spanId() { - assertThat( - parseB3SingleFormat(traceId + "-0000000000000000-1-" + parentId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_zero_spanId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: read all zeros {0}", "span ID", null); + assertThat( + parseB3SingleFormat(traceId + "-0000000000000000-1-" + parentId)) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: read all zeros {0}", "span ID", null); + } } /** Serializing parent ID as zero is the same as none. */ - @Test public void parseB3SingleFormat_zero_parentId() { + @Test void parseB3SingleFormat_zero_parentId() { assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-1-0000000000000000").context()) .isEqualToComparingFieldByField( parseB3SingleFormat(traceId + "-" + spanId + "-1").context() ); } - @Test public void parseB3SingleFormat_too_many_fields() { - assertThat( - parseB3SingleFormat(traceId + "-" + spanId + "-1-" + parentId + "-")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_too_many_fields() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: more than 4 fields exist", null); + assertThat( + parseB3SingleFormat(traceId + "-" + spanId + "-1-" + parentId + "-")) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: more than 4 fields exist", null); + } } - @Test public void parseB3SingleFormat_sampledCorrupt() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-f")) - .isNull(); // instead of crashing + @Test void parseB3SingleFormat_sampledCorrupt() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-f")) + .isNull(); // instead of crashing - verify(platform).log("Invalid input: expected 0, 1 or d for {0}", "sampled", null); + verify(platform).log("Invalid input: expected 0, 1 or d for {0}", "sampled", null); + } } - @Test public void parseB3SingleFormat_empty() { - assertThat(parseB3SingleFormat("")).isNull(); + @Test void parseB3SingleFormat_empty() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: empty", null); + assertThat(parseB3SingleFormat("")).isNull(); + + verify(platform).log("Invalid input: empty", null); + } } - @Test public void parseB3SingleFormat_empty_traceId() { - assertThat(parseB3SingleFormat("-234567812345678-" + spanId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_empty_traceId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat("-234567812345678-" + spanId)) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: empty {0}", "trace ID", null); + verify(platform).log("Invalid input: empty {0}", "trace ID", null); + } } - @Test public void parseB3SingleFormat_empty_spanId() { - assertThat(parseB3SingleFormat(traceId + "--")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_empty_spanId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "--")) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: empty {0}", "span ID", null); + verify(platform).log("Invalid input: empty {0}", "span ID", null); + } } - @Test public void parseB3SingleFormat_empty_spanId_with_parent() { - assertThat(parseB3SingleFormat(traceId + "--" + parentId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_empty_spanId_with_parent() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: empty {0}", "span ID", null); + assertThat(parseB3SingleFormat(traceId + "--" + parentId)) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: empty {0}", "span ID", null); + } } /** We don't know if the intent was a sampled flag or a parent ID, but less logic to pick one. */ - @Test public void parseB3SingleFormat_empty_after_spanId() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_empty_after_spanId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-")) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: empty {0}", "sampled", null); + verify(platform).log("Invalid input: empty {0}", "sampled", null); + } } - @Test public void parseB3SingleFormat_empty_sampled_with_parentId() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "--" + parentId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_empty_sampled_with_parentId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: empty {0}", "sampled", null); + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "--" + parentId)) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: empty {0}", "sampled", null); + } } - @Test public void parseB3SingleFormat_empty_parent_after_sampled() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-d-")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_empty_parent_after_sampled() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-d-")) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: empty {0}", "parent ID", null); + verify(platform).log("Invalid input: empty {0}", "parent ID", null); + } } - @Test public void parseB3SingleFormat_truncated_traceId() { - assertThat(parseB3SingleFormat("1-" + spanId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_truncated_traceId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: {0} is too short", "trace ID", null); + assertThat(parseB3SingleFormat("1-" + spanId)) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: {0} is too short", "trace ID", null); + } } - @Test public void parseB3SingleFormat_truncated_traceId128() { - assertThat(parseB3SingleFormat(traceIdHigh.substring(0, 15) + traceId + "-" + spanId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_truncated_traceId128() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceIdHigh.substring(0, 15) + traceId + "-" + spanId)) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: {0} is too short", "trace ID", null); + verify(platform).log("Invalid input: {0} is too short", "trace ID", null); + } } - @Test public void parseB3SingleFormat_truncated_spanId() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId.substring(0, 15))) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_truncated_spanId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: {0} is too short", "span ID", null); + assertThat(parseB3SingleFormat(traceId + "-" + spanId.substring(0, 15))) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: {0} is too short", "span ID", null); + } } - @Test public void parseB3SingleFormat_truncated_parentId() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-" + parentId.substring(0, 15))) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_truncated_parentId() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-" + parentId.substring(0, 15))) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: {0} is too short", "parent ID", null); + verify(platform).log("Invalid input: {0} is too short", "parent ID", null); + } } - @Test public void parseB3SingleFormat_truncated_parentId_after_sampled() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-1-" + parentId.substring(0, 15))) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_truncated_parentId_after_sampled() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: {0} is too short", "parent ID", null); + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-1-" + parentId.substring(0, 15))) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: {0} is too short", "parent ID", null); + } } - @Test public void parseB3SingleFormat_traceIdTooLong() { - assertThat(parseB3SingleFormat(traceId + traceId + "a" + "-" + spanId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_traceIdTooLong() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + traceId + "a" + "-" + spanId)) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: {0} is too long", "trace ID", null); + verify(platform).log("Invalid input: {0} is too long", "trace ID", null); + } } - @Test public void parseB3SingleFormat_spanIdTooLong() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "a")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_spanIdTooLong() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: {0} is too long", "span ID", null); + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "a")) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: {0} is too long", "span ID", null); + } } /** Sampled too long without parent looks the same as a truncated parent ID */ - @Test public void parseB3SingleFormat_sampledTooLong() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-11-" + parentId)) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_sampledTooLong() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-11-" + parentId)) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: {0} is too long", "sampled", null); + verify(platform).log("Invalid input: {0} is too long", "sampled", null); + } } - @Test public void parseB3SingleFormat_parentIdTooLong() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-" + parentId + "a")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_parentIdTooLong() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - verify(platform).log("Invalid input: {0} is too long", "parent ID", null); + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-" + parentId + "a")) + .isNull(); // instead of raising exception + + verify(platform).log("Invalid input: {0} is too long", "parent ID", null); + } } - @Test public void parseB3SingleFormat_parentIdTooLong_afterSampled() { - assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-1-" + parentId + "a")) - .isNull(); // instead of raising exception + @Test void parseB3SingleFormat_parentIdTooLong_afterSampled() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-1-" + parentId + "a")) + .isNull(); // instead of raising exception - verify(platform).log("Invalid input: {0} is too long", "parent ID", null); + verify(platform).log("Invalid input: {0} is too long", "parent ID", null); + } } } diff --git a/brave/src/test/java/brave/sampler/RateLimitingSamplerTest.java b/brave/src/test/java/brave/sampler/RateLimitingSamplerTest.java index 2321702f99..4825416817 100644 --- a/brave/src/test/java/brave/sampler/RateLimitingSamplerTest.java +++ b/brave/src/test/java/brave/sampler/RateLimitingSamplerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -13,165 +13,182 @@ */ package brave.sampler; +import brave.internal.Platform; import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; import static brave.sampler.RateLimitingSampler.NANOS_PER_DECISECOND; import static brave.sampler.RateLimitingSampler.NANOS_PER_SECOND; import static org.assertj.core.api.Assertions.assertThat; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -@RunWith(PowerMockRunner.class) -// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing -@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"}) -@PrepareForTest(RateLimitingSampler.class) -public class RateLimitingSamplerTest { - - @Test public void samplesOnlySpecifiedNumber() { - mockStatic(System.class); - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND); - Sampler sampler = RateLimitingSampler.create(2); - - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + 1); - assertThat(sampler.isSampled(0L)).isTrue(); - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + 2); - assertThat(sampler.isSampled(0L)).isTrue(); - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + 2); - assertThat(sampler.isSampled(0L)).isFalse(); +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RateLimitingSamplerTest { + @Mock Platform platform; + + @Test void samplesOnlySpecifiedNumber() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND); + Sampler sampler = RateLimitingSampler.create(2); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + 1); + assertThat(sampler.isSampled(0L)).isTrue(); + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + 2); + assertThat(sampler.isSampled(0L)).isTrue(); + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + 2); + assertThat(sampler.isSampled(0L)).isFalse(); + } } - @Test public void edgeCases() { - mockStatic(System.class); - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND); - Sampler sampler = RateLimitingSampler.create(2); + @Test void edgeCases() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND); + Sampler sampler = RateLimitingSampler.create(2); - // exact moment of reset - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND); - assertThat(sampler.isSampled(0L)).isTrue(); + // exact moment of reset + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND); + assertThat(sampler.isSampled(0L)).isTrue(); - // right before next interval - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND - 1); - assertThat(sampler.isSampled(0L)).isTrue(); - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND - 1); - assertThat(sampler.isSampled(0L)).isFalse(); + // right before next interval + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND - 1); + assertThat(sampler.isSampled(0L)).isTrue(); + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND - 1); + assertThat(sampler.isSampled(0L)).isFalse(); + } } - @Test public void resetsAfterASecond() { - mockStatic(System.class); - - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND); - Sampler sampler = RateLimitingSampler.create(10); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isFalse(); - - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isFalse(); - - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND * 9); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isFalse(); - - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND); - assertThat(sampler.isSampled(0L)).isTrue(); + @Test void resetsAfterASecond() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND); + Sampler sampler = RateLimitingSampler.create(10); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isFalse(); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isFalse(); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND * 9); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isFalse(); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_SECOND); + assertThat(sampler.isSampled(0L)).isTrue(); + } } - @Test public void resetsAfterALongGap() { - mockStatic(System.class); + @Test void resetsAfterALongGap() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - when(System.nanoTime()).thenReturn(0L); - Sampler sampler = RateLimitingSampler.create(10); + when(platform.nanoTime()).thenReturn(0L); + Sampler sampler = RateLimitingSampler.create(10); - // Try a really long time later. Makes sure extra credit isn't given, and no recursion errors - when(System.nanoTime()).thenReturn(TimeUnit.DAYS.toNanos(365)); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isFalse(); // we took the credit of the 1st decisecond + // Try a really long time later. Makes sure extra credit isn't given, and no recursion errors + when(platform.nanoTime()).thenReturn(TimeUnit.DAYS.toNanos(365)); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isFalse(); // we took the credit of the 1st decisecond + } } - @Test public void worksWithEdgeCases() { - mockStatic(System.class); - - when(System.nanoTime()).thenReturn(0L); - Sampler sampler = RateLimitingSampler.create(10); - - // try exact same nanosecond, however unlikely - assertThat(sampler.isSampled(0L)).isTrue(); // 1 - - // Try a value smaller than a decisecond, to ensure edge cases are covered - when(System.nanoTime()).thenReturn(1L); - assertThat(sampler.isSampled(0L)).isFalse(); // credit used - - // Try exactly a decisecond later, which should be a reset condition - when(System.nanoTime()).thenReturn(NANOS_PER_DECISECOND); - assertThat(sampler.isSampled(0L)).isTrue(); // 2 - assertThat(sampler.isSampled(0L)).isFalse(); // credit used - - // Try almost a second later - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND - 1); - assertThat(sampler.isSampled(0L)).isTrue(); // 3 - assertThat(sampler.isSampled(0L)).isTrue(); // 4 - assertThat(sampler.isSampled(0L)).isTrue(); // 5 - assertThat(sampler.isSampled(0L)).isTrue(); // 6 - assertThat(sampler.isSampled(0L)).isTrue(); // 7 - assertThat(sampler.isSampled(0L)).isTrue(); // 8 - assertThat(sampler.isSampled(0L)).isTrue(); // 9 - assertThat(sampler.isSampled(0L)).isTrue(); // 10 - assertThat(sampler.isSampled(0L)).isFalse(); // credit used - - // Try exactly a second later, which should be a reset condition - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND); - assertThat(sampler.isSampled(0L)).isTrue(); - assertThat(sampler.isSampled(0L)).isFalse(); // credit used + @Test void worksWithEdgeCases() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + when(platform.nanoTime()).thenReturn(0L); + Sampler sampler = RateLimitingSampler.create(10); + + // try exact same nanosecond, however unlikely + assertThat(sampler.isSampled(0L)).isTrue(); // 1 + + // Try a value smaller than a decisecond, to ensure edge cases are covered + when(platform.nanoTime()).thenReturn(1L); + assertThat(sampler.isSampled(0L)).isFalse(); // credit used + + // Try exactly a decisecond later, which should be a reset condition + when(platform.nanoTime()).thenReturn(NANOS_PER_DECISECOND); + assertThat(sampler.isSampled(0L)).isTrue(); // 2 + assertThat(sampler.isSampled(0L)).isFalse(); // credit used + + // Try almost a second later + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND - 1); + assertThat(sampler.isSampled(0L)).isTrue(); // 3 + assertThat(sampler.isSampled(0L)).isTrue(); // 4 + assertThat(sampler.isSampled(0L)).isTrue(); // 5 + assertThat(sampler.isSampled(0L)).isTrue(); // 6 + assertThat(sampler.isSampled(0L)).isTrue(); // 7 + assertThat(sampler.isSampled(0L)).isTrue(); // 8 + assertThat(sampler.isSampled(0L)).isTrue(); // 9 + assertThat(sampler.isSampled(0L)).isTrue(); // 10 + assertThat(sampler.isSampled(0L)).isFalse(); // credit used + + // Try exactly a second later, which should be a reset condition + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND); + assertThat(sampler.isSampled(0L)).isTrue(); + assertThat(sampler.isSampled(0L)).isFalse(); // credit used + } } - @Test public void allowsOddRates() { - mockStatic(System.class); - - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND); - Sampler sampler = RateLimitingSampler.create(11); - when(System.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND * 9); - for (int i = 0; i < 11; i++) { - assertThat(sampler.isSampled(0L)) - .withFailMessage("failed after " + (i + 1)) - .isTrue(); + @Test void allowsOddRates() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); + + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND); + Sampler sampler = RateLimitingSampler.create(11); + when(platform.nanoTime()).thenReturn(NANOS_PER_SECOND + NANOS_PER_DECISECOND * 9); + for (int i = 0; i < 11; i++) { + assertThat(sampler.isSampled(0L)) + .withFailMessage("failed after " + (i + 1)) + .isTrue(); + } + assertThat(sampler.isSampled(0L)).isFalse(); } - assertThat(sampler.isSampled(0L)).isFalse(); } - @Test public void worksOnRollover() { - mockStatic(System.class); - when(System.nanoTime()).thenReturn(-NANOS_PER_SECOND); - Sampler sampler = RateLimitingSampler.create(2); - assertThat(sampler.isSampled(0L)).isTrue(); + @Test void worksOnRollover() { + try (MockedStatic mb = mockStatic(Platform.class)) { + mb.when(Platform::get).thenReturn(platform); - when(System.nanoTime()).thenReturn(-NANOS_PER_SECOND / 2); - assertThat(sampler.isSampled(0L)).isTrue(); // second request + when(platform.nanoTime()).thenReturn(-NANOS_PER_SECOND); + Sampler sampler = RateLimitingSampler.create(2); + assertThat(sampler.isSampled(0L)).isTrue(); - when(System.nanoTime()).thenReturn(-NANOS_PER_SECOND / 4); - assertThat(sampler.isSampled(0L)).isFalse(); + when(platform.nanoTime()).thenReturn(-NANOS_PER_SECOND / 2); + assertThat(sampler.isSampled(0L)).isTrue(); // second request - when(System.nanoTime()).thenReturn(0L); // reset - assertThat(sampler.isSampled(0L)).isTrue(); + when(platform.nanoTime()).thenReturn(-NANOS_PER_SECOND / 4); + assertThat(sampler.isSampled(0L)).isFalse(); + + when(platform.nanoTime()).thenReturn(0L); // reset + assertThat(sampler.isSampled(0L)).isTrue(); + } } - @Test public void zeroMeansDropAllTraces() { + @Test void zeroMeansDropAllTraces() { assertThat(RateLimitingSampler.create(0)).isSameAs(Sampler.NEVER_SAMPLE); } - @Test(expected = IllegalArgumentException.class) - public void tracesPerSecond_cantBeNegative() { - RateLimitingSampler.create(-1); + @Test void tracesPerSecond_cantBeNegative() { + assertThatThrownBy(() -> RateLimitingSampler.create(-1)) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/build-bin/README.md b/build-bin/README.md index d2a245939a..363b6f7c0f 100755 --- a/build-bin/README.md +++ b/build-bin/README.md @@ -15,7 +15,7 @@ On deploy: `build-bin` holds portable scripts used in CI to test and deploy the project. The scripts here are portable. They do not include any CI provider-specific logic or ENV variables. -This helps `.travis.yml` and `test.yml` (GitHub Actions) contain nearly the same contents, even if +This helps `test.yml` (GitHub Actions) and alternatives contain nearly the same contents, even if certain OpenZipkin projects need slight adjustments here. Portability has proven necessary, as OpenZipkin has had to transition CI providers many times due to feature and quota constraints. @@ -41,8 +41,8 @@ blank. Tests should not run on documentation-only commits. Tests must not depend resources, as running tests can leak credentials. Git checkouts should include the full history so that license headers or other git analysis can take place. - * [configure_test] - Sets up build environment for tests. - * [test] - Builds and runs tests for this project. +* [configure_test] - Sets up build environment for tests. +* [test] - Builds and runs tests for this project. ### Example GitHub Actions setup @@ -53,9 +53,6 @@ the scripts it uses. The `on:` section obviates job creation and resource usage for irrelevant events. Notably, GitHub Actions includes the ability to skip documentation-only jobs. -Combine [configure_test] and [test] into the same `run:` when `configure_test` primes file system -cache. - Here's a partial `test.yml` including only the aspects mentioned above. ```yaml on: @@ -71,54 +68,13 @@ jobs: test: steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: - fetch-depth: 0 # full git history + fetch-depth: 0 # full git history for license check - name: Test - run: build-bin/configure_test && build-bin/test -``` - -### Example Travis setup -`.travis.yml` is a monolithic configuration file broken into stages, of which the default is "test". -A simplest Travis `test` job configures tests in `install` and runs them as `script`, but only on -relevant event conditions. - -The `if:` section obviates job creation and resource usage for irrelevant events. Travis does not -support file conditions. A `before_install` step to skip documentation-only commits will likely -complete in less than a minute (10 credit cost). - -Here's a partial `.travis.yml` including only the aspects mentioned above. -```yaml -git: - depth: false # TRAVIS_COMMIT_RANGE requires full commit history. - -jobs: - include: - - stage: test - if: branch = master AND tag IS blank AND type IN (push, pull_request) - name: Run unit and integration tests - before_install: | # Prevent test build of a documentation-only change. - if [ -n "${TRAVIS_COMMIT_RANGE}" ] && ! git diff --name-only "${TRAVIS_COMMIT_RANGE}" -- | grep -qv '\.md$'; then - echo "Stopping job as changes only affect documentation (ex. README.md)" - travis_terminate 0 - fi - install: ./build-bin/configure_test - script: ./build-bin/test -``` - -When Travis only runs tests (something else does deploy), there's no need to use stages: -```yaml -git: - depth: false # TRAVIS_COMMIT_RANGE requires full commit history. - -if: branch = master AND tag IS blank AND type IN (push, pull_request) -before_install: | # Prevent test build of a documentation-only change. - if [ -n "${TRAVIS_COMMIT_RANGE}" ] && ! git diff --name-only "${TRAVIS_COMMIT_RANGE}" -- | grep -qv '\.md$'; then - echo "Stopping job as changes only affect documentation (ex. README.md)" - travis_terminate 0 - fi -install: ./build-bin/configure_test -script: ./build-bin/test + run: | + build-bin/configure_test + build-bin/test ``` ## Deploy @@ -128,8 +84,8 @@ providers deploy pushes to master on when the tag is blank, but not on documenta Releases should deploy on version tags (ex `/^[0-9]+\.[0-9]+\.[0-9]+/`), without consideration of if the commit is documentation only or not. - * [configure_deploy] - Sets up environment and logs in, assuming [configure_test] was not called. - * [deploy] - deploys the project, with arg0 being "master" or a release commit like "1.2.3" +* [configure_deploy] - Sets up environment and logs in, assuming [configure_test] was not called. +* [deploy] - deploys the project, with arg0 being "master" or a release commit like "1.2.3" ### Example GitHub Actions setup @@ -141,77 +97,28 @@ The `on:` section obviates job creation and resource usage for irrelevant events cannot implement "master, except documentation only-commits" in the same file. Hence, deployments of master will happen even on README change. -Combine [configure_deploy] and [deploy] into the same `run:` when `configure_deploy` primes file -system cache. - Here's a partial `deploy.yml` including only the aspects mentioned above. Notice env variables are explicitly defined and `on.tags` is a [glob pattern](https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet). + ```yaml on: push: - tags: '[0-9]+.[0-9]+.[0-9]+**' # Ex. 8.272.10 or 15.0.1_p9 + tags: '[0-9]+.[0-9]+.[0-9]+**' # e.g. 8.272.10 or 15.0.1_p9 branches: master jobs: deploy: steps: - name: Checkout Repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: fetch-depth: 1 # only needed to get the sha label - - name: Deploy + - name: Configure Deploy + run: build-bin/configure_deploy env: GH_USER: ${{ secrets.GH_USER }} GH_TOKEN: ${{ secrets.GH_TOKEN }} - run: | # GITHUB_REF will be refs/heads/master or refs/tags/MAJOR.MINOR.PATCH - build-bin/configure_deploy && - build-bin/deploy $(echo ${GITHUB_REF} | cut -d/ -f 3) -``` - -### Example Travis setup -`.travis.yml` is a monolithic configuration file broken into stages. This means `test` and `deploy` -are in the same file. A simplest Travis `deploy` stage has two jobs: one for master pushes and -another for version tags. These jobs are controlled by event conditions. - -The `if:` section obviates job creation and resource usage for irrelevant events. Travis does not -support file conditions. A `before_install` step to skip documentation-only commits will likely -complete in less than a minute (10 credit cost). - -As billing is by the minute, it is most cost effective to combine test and deploy on master push. - -Here's a partial `.travis.yml` including only the aspects mentioned above. Notice YAML anchors work -in Travis and `tag =~` [condition](https://github.com/travis-ci/travis-conditions) is a regular -expression. -```yaml -git: - depth: false # full git history for license check, and doc-only skipping - -_terminate_if_only_docs: &terminate_if_only_docs | - if [ -n "${TRAVIS_COMMIT_RANGE}" ] && ! git diff --name-only "${TRAVIS_COMMIT_RANGE}" -- | grep -qv '\.md$'; then - echo "Stopping job as changes only affect documentation (ex. README.md)" - travis_terminate 0 - fi - -jobs: - include: - - stage: test - if: branch = master AND tag IS blank AND type IN (push, pull_request) - before_install: *terminate_if_only_docs - install: | - if [ "${TRAVIS_SECURE_ENV_VARS}" = "true" ] && [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then - export SHOULD_DEPLOY=true - ./build-bin/configure_deploy - else - export SHOULD_DEPLOY=false - ./build-bin/configure_test - fi - script: - - ./build-bin/test || travis_terminate 1 - - if [ "${SHOULD_DEPLOY}" != "true" ]; then travis_terminate 0; fi - - travis_wait ./build-bin/deploy master - - stage: deploy - # Ex. 8.272.10 or 15.0.1_p9 - if: tag =~ /^[0-9]+\.[0-9]+\.[0-9]+/ AND type = push AND env(GH_TOKEN) IS present - install: ./build-bin/configure_deploy - script: ./build-bin/deploy ${TRAVIS_TAG} + - name: Deploy + # GITHUB_REF will be refs/heads/master or refs/tags/1.2.3 + run: build-bin/deploy $(echo ${GITHUB_REF} | cut -d/ -f 3) ``` diff --git a/build-bin/docker/configure_docker b/build-bin/docker/configure_docker index 6168e889f3..2e09e33432 100755 --- a/build-bin/docker/configure_docker +++ b/build-bin/docker/configure_docker @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at @@ -25,13 +25,8 @@ set -ue # * checks.disable=true - saves time and a docker.io pull of alpine # * ryuk doesn't count against docker.io rate limits because Docker approved testcontainers as OSS echo checks.disable=true >> ~/.testcontainers.properties -# * upgrade ryuk until https://github.com/testcontainers/testcontainers-java/pull/3630 -echo ryuk.container.image=testcontainers/ryuk:0.3.1 >> ~/.testcontainers.properties # We don't use any docker.io images, but add a Google's mirror in case something implicitly does # * See https://cloud.google.com/container-registry/docs/pulling-cached-images echo '{ "registry-mirrors": ["https://mirror.gcr.io"] }' | sudo tee /etc/docker/daemon.json sudo service docker restart - -# * Ensure buildx and related features are disabled -mkdir -p ${HOME}/.docker && echo '{"experimental":"disabled"}' > ${HOME}/.docker/config.json diff --git a/build-bin/git/login_git b/build-bin/git/login_git index e168e7f98b..ebde366f8b 100755 --- a/build-bin/git/login_git +++ b/build-bin/git/login_git @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at diff --git a/build-bin/git/version_from_trigger_tag b/build-bin/git/version_from_trigger_tag index b6bdea2ab5..a1baf54fec 100755 --- a/build-bin/git/version_from_trigger_tag +++ b/build-bin/git/version_from_trigger_tag @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at @@ -15,9 +15,9 @@ set -ue -# This script echos a `N.M.L` version tag based on.. +# This script echos a `MAJOR.MINOR.PATCH` version tag based on.. # * arg1: XXXXX- prefix -# * arg2: XXXXX-N.M.L git trigger tag +# * arg2: XXXXX-MAJOR.MINOR.PATCH git trigger tag # # The script exits 1 if the prefix doesn't match. On success, the tag is deleted if it exists. # diff --git a/build-bin/gpg/configure_gpg b/build-bin/gpg/configure_gpg index 2ac150c2a5..ca347a8f76 100755 --- a/build-bin/gpg/configure_gpg +++ b/build-bin/gpg/configure_gpg @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at diff --git a/build-bin/maven/maven_deploy b/build-bin/maven/maven_deploy index c111e8157e..8fdd34fe2d 100755 --- a/build-bin/maven/maven_deploy +++ b/build-bin/maven/maven_deploy @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at diff --git a/build-bin/maven/maven_go_offline b/build-bin/maven/maven_go_offline index 57a41c48d5..ad78fac75f 100755 --- a/build-bin/maven/maven_go_offline +++ b/build-bin/maven/maven_go_offline @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at diff --git a/build-bin/maven/maven_opts b/build-bin/maven/maven_opts index 7d3eb67d7e..2432a1b9d1 100755 --- a/build-bin/maven/maven_opts +++ b/build-bin/maven/maven_opts @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at diff --git a/build-bin/maven/maven_release b/build-bin/maven/maven_release index 1a475325c0..d320da20c1 100755 --- a/build-bin/maven/maven_release +++ b/build-bin/maven/maven_release @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright 2013-2020 The OpenZipkin Authors +# Copyright 2013-2023 The OpenZipkin Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at diff --git a/build-bin/test b/build-bin/test index 134760b0e5..1ed3bfe35b 100755 --- a/build-bin/test +++ b/build-bin/test @@ -4,5 +4,9 @@ # # See [README.md] for an explanation of this and how CI should use it. -# Don't use `-T1C ` because this project uses RetroLambda which is not threadsafe -./mvnw verify -nsu "$@" +# We use install, not verify, because maven-invoker-tests need brave-tests +# installed into the local repository before it can run. +# +# We avoid -T1C because some plugins don't work in parallel and also ITs are +# difficult to debug when failures are in parallel. +./mvnw install -nsu "$@" diff --git a/context/jfr/pom.xml b/context/jfr/pom.xml index efc2638c8c..3ff46662bf 100644 --- a/context/jfr/pom.xml +++ b/context/jfr/pom.xml @@ -45,15 +45,6 @@ - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - org.codehaus.mojo animal-sniffer-maven-plugin diff --git a/context/log4j12/pom.xml b/context/log4j12/pom.xml index c6dfd8c003..7e64d2e13c 100644 --- a/context/log4j12/pom.xml +++ b/context/log4j12/pom.xml @@ -30,8 +30,6 @@ brave.context.log4j12 ${project.basedir}/../.. - 1.6 - java16 @@ -42,4 +40,40 @@ provided + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/context/log4j2/pom.xml b/context/log4j2/pom.xml index 5a79ab03c0..282a99cdb2 100644 --- a/context/log4j2/pom.xml +++ b/context/log4j2/pom.xml @@ -30,8 +30,6 @@ brave.context.log4j2 ${project.basedir}/../.. - 1.6 - java16 @@ -42,4 +40,40 @@ provided + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/context/rxjava2/pom.xml b/context/rxjava2/pom.xml index aa77e351f9..2583d6b73f 100644 --- a/context/rxjava2/pom.xml +++ b/context/rxjava2/pom.xml @@ -30,9 +30,6 @@ brave.context.rxjava2 ${project.basedir}/../.. - - 1.6 - java16 @@ -62,4 +59,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextCompletableObserver.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextCompletableObserver.java index 9be59d061a..ce8a550918 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextCompletableObserver.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextCompletableObserver.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -40,7 +40,7 @@ final class TraceContextCompletableObserver implements CompletableObserver, Disp @Override public void onError(Throwable t) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onError(t); } finally { scope.close(); @@ -49,7 +49,7 @@ final class TraceContextCompletableObserver implements CompletableObserver, Disp @Override public void onComplete() { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onComplete(); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableFlowable.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableFlowable.java index cdba236ce4..e92268f3f2 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableFlowable.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableFlowable.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -43,7 +43,7 @@ final class TraceContextConnectableFlowable extends ConnectableFlowable { @Override public void connect(Consumer connection) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { source.connect(connection); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableObservable.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableObservable.java index 5a616a6dc5..eaddfd461a 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableObservable.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextConnectableObservable.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -38,12 +38,12 @@ final class TraceContextConnectableObservable extends ConnectableObservable o) { - source.subscribe(new TraceContextObserver<>(o, contextScoper, assembled)); + source.subscribe(new TraceContextObserver(o, contextScoper, assembled)); } @Override public void connect(Consumer connection) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { source.connect(connection); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybe.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybe.java index 0d29fe1b61..cf6580dc07 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybe.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybe.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -36,6 +36,6 @@ final class TraceContextMaybe extends Maybe { * subscription callbacks. */ @Override protected void subscribeActual(MaybeObserver o) { - source.subscribe(new TraceContextMaybeObserver<>(o, contextScoper, assembled)); + source.subscribe(new TraceContextMaybeObserver(o, contextScoper, assembled)); } } diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybeObserver.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybeObserver.java index e1d93de8b1..6cee2ebd23 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybeObserver.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextMaybeObserver.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -43,7 +43,7 @@ final class TraceContextMaybeObserver implements MaybeObserver, Disposable @Override public void onError(Throwable t) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onError(t); } finally { scope.close(); @@ -52,7 +52,7 @@ final class TraceContextMaybeObserver implements MaybeObserver, Disposable @Override public void onSuccess(T value) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onSuccess(value); } finally { scope.close(); @@ -61,7 +61,7 @@ final class TraceContextMaybeObserver implements MaybeObserver, Disposable @Override public void onComplete() { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onComplete(); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObservable.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObservable.java index d83f8a2976..fd1332754f 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObservable.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObservable.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -36,6 +36,6 @@ final class TraceContextObservable extends Observable { * subscription callbacks. */ @Override protected void subscribeActual(Observer o) { - source.subscribe(new TraceContextObserver<>(o, contextScoper, assembled)); + source.subscribe(new TraceContextObserver(o, contextScoper, assembled)); } } diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObserver.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObserver.java index bdf13e6def..3c45feab08 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObserver.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextObserver.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -45,7 +45,7 @@ final class TraceContextObserver implements Observer, Disposable { @Override public void onNext(T t) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onNext(t); } finally { scope.close(); @@ -60,7 +60,7 @@ final class TraceContextObserver implements Observer, Disposable { done = true; Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onError(t); } finally { scope.close(); @@ -72,7 +72,7 @@ final class TraceContextObserver implements Observer, Disposable { done = true; Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onComplete(); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingle.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingle.java index 12cc69058d..c03e440773 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingle.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingle.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -36,6 +36,6 @@ final class TraceContextSingle extends Single { * subscription callbacks. */ @Override protected void subscribeActual(SingleObserver o) { - source.subscribe(new TraceContextSingleObserver<>(o, contextScoper, assembled)); + source.subscribe(new TraceContextSingleObserver(o, contextScoper, assembled)); } } diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingleObserver.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingleObserver.java index 616a536b39..d06eb9e4d8 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingleObserver.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSingleObserver.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -43,7 +43,7 @@ final class TraceContextSingleObserver implements SingleObserver, Disposab @Override public void onError(Throwable t) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onError(t); } finally { scope.close(); @@ -52,7 +52,7 @@ final class TraceContextSingleObserver implements SingleObserver, Disposab @Override public void onSuccess(T value) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onSuccess(value); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSubscriber.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSubscriber.java index 934e36f40d..721503f372 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSubscriber.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/TraceContextSubscriber.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -46,7 +46,7 @@ class TraceContextSubscriber implements Subscriber { @Override public void onNext(T t) { Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onNext(t); } finally { scope.close(); @@ -61,7 +61,7 @@ class TraceContextSubscriber implements Subscriber { done = true; Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onError(t); } finally { scope.close(); @@ -73,7 +73,7 @@ class TraceContextSubscriber implements Subscriber { done = true; Scope scope = contextScoper.maybeScope(assembled); - try { // retrolambda can't resolve this try/finally + try { downstream.onComplete(); } finally { scope.close(); diff --git a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/Wrappers.java b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/Wrappers.java index 696cbb9b22..0fa6f9c260 100644 --- a/context/rxjava2/src/main/java/brave/context/rxjava2/internal/Wrappers.java +++ b/context/rxjava2/src/main/java/brave/context/rxjava2/internal/Wrappers.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -41,16 +41,16 @@ public class Wrappers { public static Subscriber wrap( Subscriber downstream, CurrentTraceContext contextScoper, TraceContext assembled) { if (downstream instanceof FlowableSubscriber) { - return new TraceContextFlowableSubscriber<>((FlowableSubscriber) downstream, + return new TraceContextFlowableSubscriber((FlowableSubscriber) downstream, contextScoper, assembled); } - return new TraceContextSubscriber<>(downstream, contextScoper, assembled); + return new TraceContextSubscriber(downstream, contextScoper, assembled); } public static Completable wrap( CompletableSource source, CurrentTraceContext contextScoper, TraceContext assembled) { if (source instanceof Callable) { - return new TraceContextCallableCompletable<>(source, contextScoper, assembled); + return new TraceContextCallableCompletable(source, contextScoper, assembled); } return new TraceContextCompletable(source, contextScoper, assembled); } @@ -58,63 +58,63 @@ public static Completable wrap( public static Maybe wrap( MaybeSource source, CurrentTraceContext contextScoper, TraceContext assembled) { if (source instanceof Callable) { - return new TraceContextCallableMaybe<>(source, contextScoper, assembled); + return new TraceContextCallableMaybe(source, contextScoper, assembled); } - return new TraceContextMaybe<>(source, contextScoper, assembled); + return new TraceContextMaybe(source, contextScoper, assembled); } public static Single wrap( SingleSource source, CurrentTraceContext contextScoper, TraceContext assembled) { if (source instanceof Callable) { - return new TraceContextCallableSingle<>(source, contextScoper, assembled); + return new TraceContextCallableSingle(source, contextScoper, assembled); } - return new TraceContextSingle<>(source, contextScoper, assembled); + return new TraceContextSingle(source, contextScoper, assembled); } public static Observable wrap( ObservableSource source, CurrentTraceContext contextScoper, TraceContext assembled) { if (source instanceof Callable) { - return new TraceContextCallableObservable<>(source, contextScoper, assembled); + return new TraceContextCallableObservable(source, contextScoper, assembled); } - return new TraceContextObservable<>(source, contextScoper, assembled); + return new TraceContextObservable(source, contextScoper, assembled); } public static ConnectableObservable wrap( ConnectableObservable source, CurrentTraceContext contextScoper, TraceContext assembled) { - return new TraceContextConnectableObservable<>(source, contextScoper, assembled); + return new TraceContextConnectableObservable(source, contextScoper, assembled); } public static Flowable wrap( Publisher source, CurrentTraceContext contextScoper, TraceContext assembled) { if (source instanceof Callable) { - return new TraceContextCallableFlowable<>(source, contextScoper, assembled); + return new TraceContextCallableFlowable(source, contextScoper, assembled); } - return new TraceContextFlowable<>(source, contextScoper, assembled); + return new TraceContextFlowable(source, contextScoper, assembled); } public static ConnectableFlowable wrap( ConnectableFlowable source, CurrentTraceContext contextScoper, TraceContext assembled) { - return new TraceContextConnectableFlowable<>(source, contextScoper, assembled); + return new TraceContextConnectableFlowable(source, contextScoper, assembled); } public static ParallelFlowable wrap( ParallelFlowable source, CurrentTraceContext contextScoper, TraceContext assembled) { - return new TraceContextParallelFlowable<>(source, contextScoper, assembled); + return new TraceContextParallelFlowable(source, contextScoper, assembled); } public static Observer wrap(Observer downstream, CurrentTraceContext contextScoper, TraceContext assembled) { - return new TraceContextObserver<>(downstream, contextScoper, assembled); + return new TraceContextObserver(downstream, contextScoper, assembled); } public static SingleObserver wrap(SingleObserver downstream, CurrentTraceContext contextScoper, TraceContext assembled) { - return new TraceContextSingleObserver<>(downstream, contextScoper, assembled); + return new TraceContextSingleObserver(downstream, contextScoper, assembled); } public static MaybeObserver wrap(MaybeObserver downstream, CurrentTraceContext contextScoper, TraceContext assembled) { - return new TraceContextMaybeObserver<>(downstream, contextScoper, assembled); + return new TraceContextMaybeObserver(downstream, contextScoper, assembled); } public static CompletableObserver wrap(CompletableObserver downstream, diff --git a/context/slf4j/pom.xml b/context/slf4j/pom.xml index 4e27a3bf51..fa3a69aa58 100644 --- a/context/slf4j/pom.xml +++ b/context/slf4j/pom.xml @@ -30,8 +30,6 @@ brave.context.slf4j ${project.basedir}/../.. - 1.6 - java16 @@ -42,4 +40,40 @@ provided + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/benchmarks/pom.xml b/instrumentation/benchmarks/pom.xml index ab64c24865..47992ebead 100644 --- a/instrumentation/benchmarks/pom.xml +++ b/instrumentation/benchmarks/pom.xml @@ -250,15 +250,6 @@ - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - maven-shade-plugin diff --git a/instrumentation/dubbo-rpc/pom.xml b/instrumentation/dubbo-rpc/pom.xml index 5a12c8acfc..99035474d6 100644 --- a/instrumentation/dubbo-rpc/pom.xml +++ b/instrumentation/dubbo-rpc/pom.xml @@ -29,8 +29,6 @@ brave.dubbo.rpc ${project.basedir}/../.. - 1.6 - java16 2.6.9 @@ -62,4 +60,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingFilter.java b/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingFilter.java index c4870f274a..7213b9e0e1 100644 --- a/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingFilter.java +++ b/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -140,10 +140,13 @@ public void setRpcTracing(RpcTracing rpcTracing) { TraceContext callbackContext = kind == Kind.CLIENT ? invocationContext : span.context(); ResponseFuture wrapped = new FinishSpanResponseFuture(original, this, request, result, span, callbackContext); - RpcContext.getContext().setFuture(new FutureAdapter<>(wrapped)); + RpcContext.getContext().setFuture(new FutureAdapter(wrapped)); } return result; - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { propagateIfFatal(e); error = e; throw e; diff --git a/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingResponseCallback.java b/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingResponseCallback.java index bcd3b1e42f..4363b679c4 100644 --- a/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingResponseCallback.java +++ b/instrumentation/dubbo-rpc/src/main/java/brave/dubbo/rpc/TracingResponseCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -60,18 +60,22 @@ static final class DelegateAndFinishSpan extends TracingResponseCallback { } @Override public void done(Object response) { - try (Scope ws = current.maybeScope(context)) { + Scope ws = current.maybeScope(context); + try { delegate.done(response); } finally { super.done(response); + ws.close(); } } @Override public void caught(Throwable exception) { - try (Scope ws = current.maybeScope(context)) { + Scope ws = current.maybeScope(context); + try { delegate.caught(exception); } finally { super.caught(exception); + ws.close(); } } } diff --git a/instrumentation/grpc/pom.xml b/instrumentation/grpc/pom.xml index 598aba3122..0fdc796ff7 100644 --- a/instrumentation/grpc/pom.xml +++ b/instrumentation/grpc/pom.xml @@ -29,9 +29,6 @@ brave.grpc ${project.basedir}/../.. - - 1.6 - java16 1.6.2 0.6.1 @@ -114,7 +111,42 @@ + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + include-invoker @@ -146,6 +178,7 @@ grpc-all ${old-grpc.version} MAIN + jar org.codehaus.mojo diff --git a/instrumentation/grpc/src/it/grpc12/pom.xml b/instrumentation/grpc/src/it/grpc12/pom.xml index 9942dec9f9..2110ef643c 100644 --- a/instrumentation/grpc/src/it/grpc12/pom.xml +++ b/instrumentation/grpc/src/it/grpc12/pom.xml @@ -1,7 +1,7 @@ false + us to change scope and format via log4j2.properties --> org.apache.logging.log4j.jul.LogManager false + + + --add-opens java.base/java.lang=ALL-UNNAMED + --add-opens java.base/java.nio=ALL-UNNAMED + diff --git a/instrumentation/grpc/src/main/java/brave/grpc/GrpcPropagation.java b/instrumentation/grpc/src/main/java/brave/grpc/GrpcPropagation.java index 448a331be6..253c6e7a40 100644 --- a/instrumentation/grpc/src/main/java/brave/grpc/GrpcPropagation.java +++ b/instrumentation/grpc/src/main/java/brave/grpc/GrpcPropagation.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -48,7 +48,7 @@ final class GrpcPropagation implements Propagation { /** Creates constant keys for use in propagating trace identifiers or baggage. */ static Map> nameToKey(Propagation propagation) { - Map> result = new LinkedHashMap<>(); + Map> result = new LinkedHashMap>(); for (String keyName : propagation.keys()) { result.put(keyName, Key.of(keyName, Metadata.ASCII_STRING_MARSHALLER)); } @@ -83,11 +83,11 @@ static Propagation create(Propagation delegate) { } @Override public Injector injector(Setter setter) { - return new GrpcInjector<>(this, setter); + return new GrpcInjector(this, setter); } @Override public Extractor extractor(Getter getter) { - return new GrpcExtractor<>(this, getter); + return new GrpcExtractor(this, getter); } static final class GrpcInjector implements Injector { diff --git a/instrumentation/grpc/src/main/java/brave/grpc/TraceContextBinaryFormat.java b/instrumentation/grpc/src/main/java/brave/grpc/TraceContextBinaryFormat.java index 905d8c141a..5563c0fbc6 100644 --- a/instrumentation/grpc/src/main/java/brave/grpc/TraceContextBinaryFormat.java +++ b/instrumentation/grpc/src/main/java/brave/grpc/TraceContextBinaryFormat.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -97,7 +97,7 @@ static byte[] toBytes(TraceContext traceContext) { .traceId(traceId) .spanId(spanId); if (sampled != null) builder.sampled(sampled.booleanValue()); - if (tags != null) builder.extra(Collections.singletonList(tags)); + if (tags != null) builder.extra(Collections.singletonList(tags)); return builder.build(); } diff --git a/instrumentation/grpc/src/main/java/brave/grpc/TracingClientInterceptor.java b/instrumentation/grpc/src/main/java/brave/grpc/TracingClientInterceptor.java index 81fbb897df..905f199bb6 100644 --- a/instrumentation/grpc/src/main/java/brave/grpc/TracingClientInterceptor.java +++ b/instrumentation/grpc/src/main/java/brave/grpc/TracingClientInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -42,7 +42,6 @@ final class TracingClientInterceptor implements ClientInterceptor { final Map> nameToKey; final CurrentTraceContext currentTraceContext; final RpcClientHandler handler; - final MessageProcessor messageProcessor; TracingClientInterceptor(GrpcTracing grpcTracing) { @@ -55,7 +54,7 @@ final class TracingClientInterceptor implements ClientInterceptor { @Override public ClientCall interceptCall(MethodDescriptor method, CallOptions callOptions, Channel next) { - return new TracingClientCall<>( + return new TracingClientCall( method, callOptions, currentTraceContext.get(), next.newCall(method, callOptions)); } @@ -63,7 +62,7 @@ final class TracingClientCall extends SimpleForwardingClientCall method; final CallOptions callOptions; final TraceContext invocationContext; - final AtomicReference spanRef = new AtomicReference<>(); + final AtomicReference spanRef = new AtomicReference(); TracingClientCall(MethodDescriptor method, CallOptions callOptions, TraceContext invocationContext, ClientCall call) { @@ -80,62 +79,89 @@ final class TracingClientCall extends SimpleForwardingClientCall( + responseListener = new TracingClientCallListener( responseListener, invocationContext, spanRef, request ); - try (Scope scope = currentTraceContext.maybeScope(span.context())) { + Scope scope = currentTraceContext.maybeScope(span.context()); + Throwable error = null; + try { super.start(responseListener, headers); - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { propagateIfFatal(e); - - // Another interceptor may throw an exception during start, in which case no other - // callbacks are called, so go ahead and close the span here. - // - // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here - spanRef.set(null); - if (span != null) span.error(e).finish(); + error = e; throw e; + } finally { + if (error != null) { + // Another interceptor may throw an exception during start, in which case no other + // callbacks are called, so go ahead and close the span here. + // + // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here + spanRef.set(null); + if (span != null) span.error(error).finish(); + } + scope.close(); } } @Override public void cancel(@Nullable String message, @Nullable Throwable cause) { - try (Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext)) { + Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext); + try { delegate().cancel(message, cause); + } finally { + scope.close(); } } @Override public void halfClose() { - try (Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext)) { + Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext); + Throwable error = null; + try { delegate().halfClose(); - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { propagateIfFatal(e); - - // If there was an exception executing onHalfClose, we don't expect other lifecycle - // commands to succeed. Accordingly, we close the span - // - // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here - Span span = spanRef.getAndSet(null); - if (span != null) span.error(e).finish(); + error = e; throw e; + } finally { + if (error != null) { + // If there was an exception executing onHalfClose, we don't expect other lifecycle + // commands to succeed. Accordingly, we close the span + // + // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here + Span span = spanRef.getAndSet(null); + if (span != null) span.error(error).finish(); + } + scope.close(); } } @Override public void request(int numMessages) { - try (Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext)) { + Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext); + try { delegate().request(numMessages); + } finally { + scope.close(); } } @Override public void sendMessage(ReqT message) { - try (Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext)) { + Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext); + try { delegate().sendMessage(message); Span span = spanRef.get(); // could be an error SpanCustomizer customizer = span != null ? span.customizer() : NoopSpanCustomizer.INSTANCE; messageProcessor.onMessageSent(message, customizer); + } finally { + scope.close(); } } } @@ -169,8 +195,11 @@ final class TracingClientCallListener extends SimpleForwardingClientCallL } @Override public void onReady() { - try (Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext)) { + Scope scope = maybeScopeClientOrInvocationContext(spanRef, invocationContext); + try { delegate().onReady(); + } finally { + scope.close(); } } @@ -178,17 +207,23 @@ final class TracingClientCallListener extends SimpleForwardingClientCallL @Override public void onHeaders(Metadata headers) { // onHeaders() JavaDoc mentions headers are not thread-safe, so we make a safe copy here. this.headers.merge(headers); - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate().onHeaders(headers); + } finally { + scope.close(); } } @Override public void onMessage(RespT message) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { Span span = spanRef.get(); // could be an error SpanCustomizer customizer = span != null ? span.customizer() : NoopSpanCustomizer.INSTANCE; messageProcessor.onMessageReceived(message, customizer); delegate().onMessage(message); + } finally { + scope.close(); } } @@ -198,8 +233,11 @@ final class TracingClientCallListener extends SimpleForwardingClientCallL Span span = spanRef.getAndSet(null); if (span != null) handler.handleReceive(response, span); - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate().onClose(status, trailers); + } finally { + scope.close(); } } } diff --git a/instrumentation/grpc/src/main/java/brave/grpc/TracingServerInterceptor.java b/instrumentation/grpc/src/main/java/brave/grpc/TracingServerInterceptor.java index 5f57b10167..98319a052f 100644 --- a/instrumentation/grpc/src/main/java/brave/grpc/TracingServerInterceptor.java +++ b/instrumentation/grpc/src/main/java/brave/grpc/TracingServerInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -32,6 +32,8 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import static brave.internal.Throwables.propagateIfFatal; + // not exposed directly as implementation notably changes between versions 1.2 and 1.3 final class TracingServerInterceptor implements ServerInterceptor { final Map> nameToKey; @@ -54,23 +56,35 @@ public Listener interceptCall(ServerCall call, GrpcServerRequest request = new GrpcServerRequest(nameToKey, call, headers); Span span = handler.handleReceive(request); - AtomicReference spanRef = new AtomicReference<>(span); + AtomicReference spanRef = new AtomicReference(span); // startCall invokes user interceptors, so we place the span in scope here Listener result; - try (Scope scope = currentTraceContext.maybeScope(span.context())) { - result = next.startCall(new TracingServerCall<>(call, span, spanRef, request), headers); - } catch (Throwable e) { - // Another interceptor may throw an exception during startCall, in which case no other - // callbacks are called, so go ahead and close the span here. - // - // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here - spanRef.set(null); - if (span != null) span.error(e).finish(); + Throwable error = null; + Scope scope = currentTraceContext.maybeScope(span.context()); + try { + result = + next.startCall(new TracingServerCall(call, span, spanRef, request), headers); + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; throw e; + } finally { + if (error != null) { + // Another interceptor may throw an exception during startCall, in which case no other + // callbacks are called, so go ahead and close the span here. + // + // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here + spanRef.set(null); + if (span != null) span.error(error).finish(); + } + scope.close(); } - return new TracingServerCallListener<>(result, span, spanRef, request); + return new TracingServerCallListener(result, span, spanRef, request); } final class TracingServerCall extends SimpleForwardingServerCall { @@ -88,25 +102,34 @@ final class TracingServerCall extends SimpleForwardingServerCall extends SimpleForwardingServerCall extends SimpleForwardingServerCallL } @Override public void onMessage(RespT message) { - try (Scope scope = currentTraceContext.maybeScope(context)) { + Scope scope = currentTraceContext.maybeScope(context); + try { delegate().onMessage(message); Span span = spanRef.get(); // could be an error SpanCustomizer customizer = span != null ? span.customizer() : NoopSpanCustomizer.INSTANCE; messageProcessor.onMessageReceived(message, customizer); + } finally { + scope.close(); } } @Override public void onHalfClose() { - try (Scope scope = currentTraceContext.maybeScope(context)) { + Scope scope = currentTraceContext.maybeScope(context); + Throwable error = null; + try { delegate().onHalfClose(); - } catch (Throwable e) { - // If there was an exception executing onHalfClose, we don't expect other lifecycle - // commands to succeed. Accordingly, we close the span - // - // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here - Span span = spanRef.getAndSet(null); - if (span != null) span.error(e).finish(); - + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; throw e; + } finally { + if (error != null) { + // If there was an exception executing onHalfClose, we don't expect other lifecycle + // commands to succeed. Accordingly, we close the span + // + // See instrumentation/grpc/RATIONALE.md for why we don't use the handler here + Span span = spanRef.getAndSet(null); + if (span != null) span.error(error).finish(); + } + scope.close(); } } @Override public void onCancel() { - try (Scope scope = currentTraceContext.maybeScope(context)) { + Scope scope = currentTraceContext.maybeScope(context); + try { delegate().onCancel(); + } finally { + scope.close(); } } @Override public void onComplete() { - try (Scope scope = currentTraceContext.maybeScope(context)) { + Scope scope = currentTraceContext.maybeScope(context); + try { delegate().onComplete(); + } finally { + scope.close(); } } @Override public void onReady() { - try (Scope scope = currentTraceContext.maybeScope(context)) { + Scope scope = currentTraceContext.maybeScope(context); + try { delegate().onReady(); + } finally { + scope.close(); } } } diff --git a/instrumentation/http-tests-jakarta/pom.xml b/instrumentation/http-tests-jakarta/pom.xml index 3c7889b23a..adfa8bbc62 100644 --- a/instrumentation/http-tests-jakarta/pom.xml +++ b/instrumentation/http-tests-jakarta/pom.xml @@ -87,15 +87,6 @@ - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - org.codehaus.mojo animal-sniffer-maven-plugin diff --git a/instrumentation/http-tests/pom.xml b/instrumentation/http-tests/pom.xml index 6053d2f912..5aa5e4890e 100644 --- a/instrumentation/http-tests/pom.xml +++ b/instrumentation/http-tests/pom.xml @@ -85,15 +85,6 @@ - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - diff --git a/instrumentation/http/pom.xml b/instrumentation/http/pom.xml index 91dbd7cb00..492a1fca59 100644 --- a/instrumentation/http/pom.xml +++ b/instrumentation/http/pom.xml @@ -30,8 +30,6 @@ brave.http ${project.basedir}/../.. - 1.6 - java16 @@ -50,4 +48,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/http/src/main/java/brave/http/HttpClientHandler.java b/instrumentation/http/src/main/java/brave/http/HttpClientHandler.java index d8017ed710..aca15b88ca 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpClientHandler.java +++ b/instrumentation/http/src/main/java/brave/http/HttpClientHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -69,7 +69,7 @@ public final class HttpClientHandler extends HttpHandler { public static HttpClientHandler create( HttpTracing httpTracing) { if (httpTracing == null) throw new NullPointerException("httpTracing == null"); - return new HttpClientHandler<>(httpTracing, null); + return new HttpClientHandler(httpTracing, null); } /** @@ -81,7 +81,7 @@ public static HttpClientHandler create(HttpTracing httpTr HttpClientAdapter adapter) { if (httpTracing == null) throw new NullPointerException("httpTracing == null"); if (adapter == null) throw new NullPointerException("adapter == null"); - return new HttpClientHandler<>(httpTracing, adapter); + return new HttpClientHandler(httpTracing, adapter); } final Tracer tracer; @@ -190,7 +190,7 @@ public Span handleSend(HttpClientRequest request, Span span) { if (request instanceof HttpClientRequest) { clientRequest = (HttpClientRequest) request; } else { - clientRequest = new HttpClientAdapters.FromRequestAdapter<>(adapter, request); + clientRequest = new HttpClientAdapters.FromRequestAdapter(adapter, request); } return handleStart(clientRequest, span); @@ -207,7 +207,7 @@ public Span handleSend(HttpClientRequest request, Span span) { if (request instanceof HttpClientRequest) { clientRequest = (HttpClientRequest) request; } else { - clientRequest = new FromRequestAdapter<>(adapter, request); + clientRequest = new FromRequestAdapter(adapter, request); } return tracer.nextSpan(httpSampler, clientRequest); } @@ -236,7 +236,7 @@ public void handleReceive(@Nullable Resp response, @Nullable Throwable error, Sp span.error(error); } } else { - clientResponse = new FromResponseAdapter<>(adapter, response, error); + clientResponse = new FromResponseAdapter(adapter, response, error); } handleFinish(clientResponse, span); } diff --git a/instrumentation/http/src/main/java/brave/http/HttpClientParserAdapter.java b/instrumentation/http/src/main/java/brave/http/HttpClientParserAdapter.java index 2936dc1bb2..20e2c7c297 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpClientParserAdapter.java +++ b/instrumentation/http/src/main/java/brave/http/HttpClientParserAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -44,7 +44,7 @@ public void request(HttpAdapter adapter, Req req, SpanCustomizer customizer) { HttpRequest request; if (req instanceof HttpClientRequest) { - request = new HttpClientAdapters.FromRequestAdapter<>((HttpClientAdapter) adapter, req); + request = new HttpClientAdapters.FromRequestAdapter((HttpClientAdapter) adapter, req); } else if (adapter instanceof HttpClientAdapters.ToRequestAdapter) { request = ((HttpClientAdapters.ToRequestAdapter) adapter).delegate; } else { @@ -58,7 +58,7 @@ public void request(HttpAdapter adapter, Req req, SpanCustomizer c HttpResponse response; if (res instanceof HttpClientResponse) { response = - new HttpClientAdapters.FromResponseAdapter<>((HttpClientAdapter) adapter, res, error); + new HttpClientAdapters.FromResponseAdapter((HttpClientAdapter) adapter, res, error); } else if (adapter instanceof HttpClientAdapters.ToResponseAdapter) { response = ((HttpClientAdapters.ToResponseAdapter) adapter).delegate; } else { diff --git a/instrumentation/http/src/main/java/brave/http/HttpRuleSampler.java b/instrumentation/http/src/main/java/brave/http/HttpRuleSampler.java index 2efb4e149e..3d54892774 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpRuleSampler.java +++ b/instrumentation/http/src/main/java/brave/http/HttpRuleSampler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -136,6 +136,6 @@ public HttpRuleSampler build() { @Override @Deprecated public Boolean trySample(HttpAdapter adapter, Req request) { if (request == null) return null; - return trySample(new FromHttpAdapter<>(adapter, request)); + return trySample(new FromHttpAdapter(adapter, request)); } } diff --git a/instrumentation/http/src/main/java/brave/http/HttpSampler.java b/instrumentation/http/src/main/java/brave/http/HttpSampler.java index 01f11fde26..ed04d36ee0 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpSampler.java +++ b/instrumentation/http/src/main/java/brave/http/HttpSampler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -129,7 +129,7 @@ static final class HttpRequestSamplerAdapter extends HttpSampler { if (request instanceof HttpRequest) { return delegate.trySample((HttpRequest) request); } - return delegate.trySample(new FromHttpAdapter<>(adapter, request)); + return delegate.trySample(new FromHttpAdapter(adapter, request)); } @Override public String toString() { diff --git a/instrumentation/http/src/main/java/brave/http/HttpServerHandler.java b/instrumentation/http/src/main/java/brave/http/HttpServerHandler.java index 9ec2adc32f..99ba5c2aac 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpServerHandler.java +++ b/instrumentation/http/src/main/java/brave/http/HttpServerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -67,7 +67,7 @@ public final class HttpServerHandler extends HttpHandler { public static HttpServerHandler create( HttpTracing httpTracing) { if (httpTracing == null) throw new NullPointerException("httpTracing == null"); - return new HttpServerHandler<>(httpTracing, null); + return new HttpServerHandler(httpTracing, null); } /** @@ -79,7 +79,7 @@ public static HttpServerHandler create(HttpTracing httpTr HttpServerAdapter adapter) { if (httpTracing == null) throw new NullPointerException("httpTracing == null"); if (adapter == null) throw new NullPointerException("adapter == null"); - return new HttpServerHandler<>(httpTracing, adapter); + return new HttpServerHandler(httpTracing, adapter); } final Tracer tracer; @@ -131,7 +131,7 @@ public Span handleReceive(HttpServerRequest request) { if (request instanceof HttpServerRequest) { serverRequest = (HttpServerRequest) request; } else { - serverRequest = new HttpServerAdapters.FromRequestAdapter<>(adapter, request); + serverRequest = new HttpServerAdapters.FromRequestAdapter(adapter, request); } Span span = nextSpan(extractor.extract(carrier), serverRequest); @@ -178,7 +178,7 @@ public void handleSend(@Nullable Resp response, @Nullable Throwable error, Span span.error(error); } } else { - serverResponse = new FromResponseAdapter<>(adapter, response, error); + serverResponse = new FromResponseAdapter(adapter, response, error); } handleFinish(serverResponse, span); } diff --git a/instrumentation/http/src/main/java/brave/http/HttpServerParserAdapter.java b/instrumentation/http/src/main/java/brave/http/HttpServerParserAdapter.java index 4e7ae572bc..534dd65cfc 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpServerParserAdapter.java +++ b/instrumentation/http/src/main/java/brave/http/HttpServerParserAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -44,7 +44,7 @@ public void request(HttpAdapter adapter, Req req, SpanCustomizer customizer) { HttpRequest request; if (req instanceof HttpServerRequest) { - request = new HttpServerAdapters.FromRequestAdapter<>((HttpServerAdapter) adapter, req); + request = new HttpServerAdapters.FromRequestAdapter((HttpServerAdapter) adapter, req); } else if (adapter instanceof HttpServerAdapters.ToRequestAdapter) { request = ((HttpServerAdapters.ToRequestAdapter) adapter).delegate; } else { @@ -58,7 +58,7 @@ public void request(HttpAdapter adapter, Req req, SpanCustomizer c HttpResponse response; if (res instanceof HttpServerResponse) { response = - new HttpServerAdapters.FromResponseAdapter<>((HttpServerAdapter) adapter, res, error); + new HttpServerAdapters.FromResponseAdapter((HttpServerAdapter) adapter, res, error); } else if (adapter instanceof HttpServerAdapters.ToResponseAdapter) { response = ((HttpServerAdapters.ToResponseAdapter) adapter).delegate; } else { diff --git a/instrumentation/http/src/main/java/brave/http/HttpTags.java b/instrumentation/http/src/main/java/brave/http/HttpTags.java index 771e7bd7e0..1c96094c62 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpTags.java +++ b/instrumentation/http/src/main/java/brave/http/HttpTags.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -29,7 +29,7 @@ */ public final class HttpTags { /** In worst case, holds 500 strings corresponding to all valid status codes. */ - static final Map CACHED_STATUS_CODES = new ConcurrentHashMap<>(); + static final Map CACHED_STATUS_CODES = new ConcurrentHashMap(); /** * This tags "http.method" as the value of {@link HttpRequest#method()}, such as "GET" or @@ -142,7 +142,7 @@ public static Tag requestHeader(String headerName) { * @see HttpResponse#request() * @since 5.11 */ - public static Tag requestHeader(String key, String headerName) { + public static Tag requestHeader(String key, final String headerName) { return new Tag(key) { String name = validateNonEmpty("headerName", headerName); diff --git a/instrumentation/http/src/main/java/brave/http/HttpTracing.java b/instrumentation/http/src/main/java/brave/http/HttpTracing.java index 77aefdaf66..2b7ccd9d47 100644 --- a/instrumentation/http/src/main/java/brave/http/HttpTracing.java +++ b/instrumentation/http/src/main/java/brave/http/HttpTracing.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -34,7 +34,7 @@ */ // Not final as it previously was not. This allows mocks and similar. public class HttpTracing implements Closeable { - static final AtomicReference CURRENT = new AtomicReference<>(); + static final AtomicReference CURRENT = new AtomicReference(); public static HttpTracing create(Tracing tracing) { return newBuilder(tracing).build(); diff --git a/instrumentation/httpasyncclient/pom.xml b/instrumentation/httpasyncclient/pom.xml index 6f81ee789b..1027031f2b 100644 --- a/instrumentation/httpasyncclient/pom.xml +++ b/instrumentation/httpasyncclient/pom.xml @@ -30,8 +30,6 @@ brave.httpasyncclient ${project.basedir}/../.. - 1.6 - java16 @@ -54,4 +52,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/httpasyncclient/src/main/java/brave/httpasyncclient/TracingHttpAsyncClientBuilder.java b/instrumentation/httpasyncclient/src/main/java/brave/httpasyncclient/TracingHttpAsyncClientBuilder.java index 9c702fdc0a..e1f688c266 100644 --- a/instrumentation/httpasyncclient/src/main/java/brave/httpasyncclient/TracingHttpAsyncClientBuilder.java +++ b/instrumentation/httpasyncclient/src/main/java/brave/httpasyncclient/TracingHttpAsyncClientBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -136,10 +136,10 @@ final class TracingHttpAsyncClient extends CloseableHttpAsyncClient { return delegate.execute( new TracingAsyncRequestProducer(requestProducer, httpContext), - new TracingAsyncResponseConsumer<>(responseConsumer, httpContext), + new TracingAsyncResponseConsumer(responseConsumer, httpContext), httpContext, callback != null && invocationContext != null - ? new TraceContextFutureCallback<>(callback, currentTraceContext, invocationContext) + ? new TraceContextFutureCallback(callback, currentTraceContext, invocationContext) : callback ); } @@ -174,20 +174,29 @@ static final class TraceContextFutureCallback implements FutureCallback { } @Override public void completed(T t) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.completed(t); + } finally { + scope.close(); } } @Override public void failed(Exception e) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.failed(e); + } finally { + scope.close(); } } @Override public void cancelled() { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.cancelled(); + } finally { + scope.close(); } } diff --git a/instrumentation/httpclient/pom.xml b/instrumentation/httpclient/pom.xml index 4bc18d8645..f991fdb315 100644 --- a/instrumentation/httpclient/pom.xml +++ b/instrumentation/httpclient/pom.xml @@ -30,8 +30,6 @@ brave.httpclient ${project.basedir}/../.. - 1.6 - java16 4.3.6 @@ -86,16 +84,54 @@ httpclient ${old-httpclient.version} MAIN + jar org.apache.httpcomponents httpclient-cache ${old-httpclient.version} MAIN + jar + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/httpclient/src/main/java/brave/httpclient/TracingProtocolExec.java b/instrumentation/httpclient/src/main/java/brave/httpclient/TracingProtocolExec.java index eae62c2a24..0fefa5834c 100644 --- a/instrumentation/httpclient/src/main/java/brave/httpclient/TracingProtocolExec.java +++ b/instrumentation/httpclient/src/main/java/brave/httpclient/TracingProtocolExec.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -35,6 +35,8 @@ import org.apache.http.conn.routing.HttpRoute; import org.apache.http.impl.execchain.ClientExecChain; +import static brave.internal.Throwables.propagateIfFatal; + /** * protocol exec is the last in the execution chain, so first to execute. We eagerly create a span * here so that user interceptors can see it. @@ -62,13 +64,25 @@ final class TracingProtocolExec implements ClientExecChain { CloseableHttpResponse response = null; Throwable error = null; - try (SpanInScope ws = tracer.withSpanInScope(span)) { + SpanInScope ws = tracer.withSpanInScope(span); + try { return response = protocolExec.execute(route, req, context, execAware); - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (HttpException e) { + error = e; + throw e; + } catch (IOException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); error = e; throw e; } finally { handler.handleReceive(new HttpResponseWrapper(response, context, error), span); + ws.close(); } } diff --git a/instrumentation/httpclient5/pom.xml b/instrumentation/httpclient5/pom.xml index 65fb5b149b..2c726caf8c 100644 --- a/instrumentation/httpclient5/pom.xml +++ b/instrumentation/httpclient5/pom.xml @@ -31,8 +31,7 @@ brave.httpclient5 ${project.basedir}/../.. - 1.7 - java17 + 5.2 @@ -62,4 +61,40 @@ test + + + + release + + + 1.7 + java17 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/jaxrs2/pom.xml b/instrumentation/jaxrs2/pom.xml index 388badd41d..bc75bbbe97 100644 --- a/instrumentation/jaxrs2/pom.xml +++ b/instrumentation/jaxrs2/pom.xml @@ -30,8 +30,6 @@ brave.jaxrs2 ${project.basedir}/../.. - 1.6 - java16 @@ -99,4 +97,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/jms-jakarta/pom.xml b/instrumentation/jms-jakarta/pom.xml index c16b0360fe..8a9d56d991 100644 --- a/instrumentation/jms-jakarta/pom.xml +++ b/instrumentation/jms-jakarta/pom.xml @@ -30,8 +30,6 @@ brave.jakarta.jms ${project.basedir}/../.. - 1.6 - java16 -Xep:MissingOverride:OFF diff --git a/instrumentation/jms/pom.xml b/instrumentation/jms/pom.xml index 4afbb8ec2c..aa2231825c 100644 --- a/instrumentation/jms/pom.xml +++ b/instrumentation/jms/pom.xml @@ -30,8 +30,6 @@ brave.jms ${project.basedir}/../.. - 1.6 - java16 -Xep:MissingOverride:OFF @@ -108,4 +106,40 @@ + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/jms/src/main/java/brave/jms/JmsTracing.java b/instrumentation/jms/src/main/java/brave/jms/JmsTracing.java index 13ac3d43ee..ad62b0edfa 100644 --- a/instrumentation/jms/src/main/java/brave/jms/JmsTracing.java +++ b/instrumentation/jms/src/main/java/brave/jms/JmsTracing.java @@ -161,7 +161,7 @@ public JmsTracing build() { this.producerSampler = builder.messagingTracing.producerSampler(); this.consumerSampler = builder.messagingTracing.consumerSampler(); this.remoteServiceName = builder.remoteServiceName; - this.traceIdProperties = new LinkedHashSet<>(propagation.keys()); + this.traceIdProperties = new LinkedHashSet(propagation.keys()); } public Connection connection(Connection connection) { diff --git a/instrumentation/jms/src/main/java/brave/jms/PropertyFilter.java b/instrumentation/jms/src/main/java/brave/jms/PropertyFilter.java index 87c4001ded..3666385171 100644 --- a/instrumentation/jms/src/main/java/brave/jms/PropertyFilter.java +++ b/instrumentation/jms/src/main/java/brave/jms/PropertyFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -86,13 +86,14 @@ static void filterProperties(Message message, Set namesToClear, List> MESSAGE_PROPERTIES_BUFFER = new ThreadLocal<>(); + static final ThreadLocal> MESSAGE_PROPERTIES_BUFFER = + new ThreadLocal>(); /** Also use pair indexing for temporary message properties: (name, value). */ static ArrayList messagePropertiesBuffer() { ArrayList messagePropertiesBuffer = MESSAGE_PROPERTIES_BUFFER.get(); if (messagePropertiesBuffer == null) { - messagePropertiesBuffer = new ArrayList<>(); + messagePropertiesBuffer = new ArrayList(); MESSAGE_PROPERTIES_BUFFER.set(messagePropertiesBuffer); } return messagePropertiesBuffer; diff --git a/instrumentation/jms/src/main/java/brave/jms/TracingCompletionListener.java b/instrumentation/jms/src/main/java/brave/jms/TracingCompletionListener.java index c4e565d8cf..fc84d068d8 100644 --- a/instrumentation/jms/src/main/java/brave/jms/TracingCompletionListener.java +++ b/instrumentation/jms/src/main/java/brave/jms/TracingCompletionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -45,23 +45,27 @@ static CompletionListener create(CompletionListener delegate, } @Override public void onCompletion(Message message) { - try (Scope ws = current.maybeScope(span.context())) { + Scope ws = current.maybeScope(span.context()); + try { delegate.onCompletion(message); } finally { // TODO: in order to tag messageId // parse(new MessageConsumerRequest(message, destination)) span.finish(); + ws.close(); } } @Override public void onException(Message message, Exception exception) { - try (Scope ws = current.maybeScope(span.context())) { + Scope ws = current.maybeScope(span.context()); + try { // TODO: in order to tag messageId // parse(new MessageConsumerRequest(message, destination)) delegate.onException(message, exception); } finally { span.error(exception); span.finish(); + ws.close(); } } } diff --git a/instrumentation/jms/src/main/java/brave/jms/TracingExceptionListener.java b/instrumentation/jms/src/main/java/brave/jms/TracingExceptionListener.java index bd6f22c87e..cd57a71ca0 100644 --- a/instrumentation/jms/src/main/java/brave/jms/TracingExceptionListener.java +++ b/instrumentation/jms/src/main/java/brave/jms/TracingExceptionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -57,10 +57,12 @@ static final class DelegateAndTagError extends TagError { delegate.onException(exception); return; } - try (SpanInScope ws = tracer.withSpanInScope(span)) { + SpanInScope ws = tracer.withSpanInScope(span); + try { delegate.onException(exception); } finally { span.error(exception); + ws.close(); } } } diff --git a/instrumentation/jms/src/main/java/brave/jms/TracingJMSProducer.java b/instrumentation/jms/src/main/java/brave/jms/TracingJMSProducer.java index 4f5210b0fc..53d30d00e0 100644 --- a/instrumentation/jms/src/main/java/brave/jms/TracingJMSProducer.java +++ b/instrumentation/jms/src/main/java/brave/jms/TracingJMSProducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -107,10 +107,13 @@ void send(Send send, Destination destination, Object message) { Throwable error = null; try { send.apply(delegate, destination, message); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) { span.error(error).finish(); // An error can happen regardless of async. diff --git a/instrumentation/jms/src/main/java/brave/jms/TracingMessageListener.java b/instrumentation/jms/src/main/java/brave/jms/TracingMessageListener.java index e02c531d33..7c68f20312 100644 --- a/instrumentation/jms/src/main/java/brave/jms/TracingMessageListener.java +++ b/instrumentation/jms/src/main/java/brave/jms/TracingMessageListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -74,10 +74,13 @@ static MessageListener create(MessageListener delegate, JmsTracing jmsTracing) { Throwable error = null; try { delegate.onMessage(message); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) listenerSpan.error(error); listenerSpan.finish(); diff --git a/instrumentation/jms/src/main/java/brave/jms/TracingMessageProducer.java b/instrumentation/jms/src/main/java/brave/jms/TracingMessageProducer.java index d46ca52516..895fd41ba1 100644 --- a/instrumentation/jms/src/main/java/brave/jms/TracingMessageProducer.java +++ b/instrumentation/jms/src/main/java/brave/jms/TracingMessageProducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -120,10 +120,16 @@ Span createAndStartProducerSpan(Message message, Destination destination) { Throwable error = null; try { delegate.send(message); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -138,10 +144,16 @@ Span createAndStartProducerSpan(Message message, Destination destination) { Throwable error = null; try { delegate.send(message, deliveryMode, priority, timeToLive); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -184,10 +196,16 @@ void send(SendDestination sendDestination, Destination destination, Message mess Throwable error = null; try { sendDestination.apply(delegate, destination, message); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -203,10 +221,16 @@ public void send(Destination destination, Message message, int deliveryMode, int Throwable error = null; try { delegate.send(destination, message, deliveryMode, priority, timeToLive); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -223,10 +247,16 @@ public void send(Message message, CompletionListener completionListener) throws Throwable error = null; try { delegate.send(message, TracingCompletionListener.create(completionListener, destination, span, current)); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error).finish(); ws.close(); @@ -243,10 +273,16 @@ public void send(Message message, CompletionListener completionListener) throws Throwable error = null; try { delegate.send(message, deliveryMode, priority, timeToLive, completionListener); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error).finish(); ws.close(); @@ -262,10 +298,16 @@ public void send(Message message, CompletionListener completionListener) throws Throwable error = null; try { delegate.send(destination, message, completionListener); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error).finish(); ws.close(); @@ -281,10 +323,16 @@ public void send(Message message, CompletionListener completionListener) throws Throwable error = null; try { delegate.send(destination, message, deliveryMode, priority, timeToLive, completionListener); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error).finish(); ws.close(); @@ -313,10 +361,16 @@ public void send(Queue queue, Message message, int deliveryMode, int priority, l Throwable error = null; try { qs.send(queue, message, deliveryMode, priority, timeToLive); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -346,10 +400,16 @@ void checkQueueSender() { Throwable error = null; try { tp.publish(message); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -367,10 +427,16 @@ void checkQueueSender() { Throwable error = null; try { tp.publish(message, deliveryMode, priority, timeToLive); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); @@ -394,10 +460,16 @@ public void publish(Topic topic, Message message, int deliveryMode, int priority Throwable error = null; try { tp.publish(topic, message, deliveryMode, priority, timeToLive); - } catch (Throwable t) { - propagateIfFatal(t); - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (JMSException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { if (error != null) span.error(error); span.finish(); diff --git a/instrumentation/kafka-clients/pom.xml b/instrumentation/kafka-clients/pom.xml index a31d8f4982..3bdd1ad2fd 100644 --- a/instrumentation/kafka-clients/pom.xml +++ b/instrumentation/kafka-clients/pom.xml @@ -93,15 +93,6 @@ - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - maven-invoker-plugin @@ -124,12 +115,14 @@ kafka-clients ${old-kafka-clients.version} MAIN + jar com.github.charithe kafka-junit ${old-kafka-junit.version} MAIN + jar diff --git a/instrumentation/kafka-streams/pom.xml b/instrumentation/kafka-streams/pom.xml index 8da54c249f..5f78a7cc77 100644 --- a/instrumentation/kafka-streams/pom.xml +++ b/instrumentation/kafka-streams/pom.xml @@ -71,17 +71,4 @@ test - - - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - - - diff --git a/instrumentation/messaging/pom.xml b/instrumentation/messaging/pom.xml index 7cbdd13f50..33fd88056c 100644 --- a/instrumentation/messaging/pom.xml +++ b/instrumentation/messaging/pom.xml @@ -27,8 +27,6 @@ ${project.basedir}/../.. - 1.6 - java16 @@ -67,4 +65,40 @@ + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/messaging/src/main/java/brave/messaging/MessagingRequestMatchers.java b/instrumentation/messaging/src/main/java/brave/messaging/MessagingRequestMatchers.java index 1cdc6e8df0..0ac54e944e 100644 --- a/instrumentation/messaging/src/main/java/brave/messaging/MessagingRequestMatchers.java +++ b/instrumentation/messaging/src/main/java/brave/messaging/MessagingRequestMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -33,7 +33,7 @@ public final class MessagingRequestMatchers { public static Matcher operationEquals(String operation) { if (operation == null) throw new NullPointerException("operation == null"); if (operation.isEmpty()) throw new NullPointerException("operation is empty"); - return new MessagingOperationEquals<>(operation); + return new MessagingOperationEquals(operation); } static final class MessagingOperationEquals @@ -73,7 +73,7 @@ static final class MessagingOperationEquals public static Matcher channelKindEquals(String channelKind) { if (channelKind == null) throw new NullPointerException("channelKind == null"); if (channelKind.isEmpty()) throw new NullPointerException("channelKind is empty"); - return new MessagingChannelKindEquals<>(channelKind); + return new MessagingChannelKindEquals(channelKind); } static final class MessagingChannelKindEquals @@ -113,7 +113,7 @@ static final class MessagingChannelKindEquals public static Matcher channelNameEquals(String channelName) { if (channelName == null) throw new NullPointerException("channelName == null"); if (channelName.isEmpty()) throw new NullPointerException("channelName is empty"); - return new MessagingChannelNameEquals<>(channelName); + return new MessagingChannelNameEquals(channelName); } static final class MessagingChannelNameEquals diff --git a/instrumentation/messaging/src/main/java/brave/messaging/MessagingTracing.java b/instrumentation/messaging/src/main/java/brave/messaging/MessagingTracing.java index 991589d042..814921809a 100644 --- a/instrumentation/messaging/src/main/java/brave/messaging/MessagingTracing.java +++ b/instrumentation/messaging/src/main/java/brave/messaging/MessagingTracing.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -32,7 +32,7 @@ * @since 5.9 */ public class MessagingTracing implements Closeable { - static final AtomicReference CURRENT = new AtomicReference<>(); + static final AtomicReference CURRENT = new AtomicReference(); /** @since 5.9 */ public static MessagingTracing create(Tracing tracing) { diff --git a/instrumentation/mongodb/pom.xml b/instrumentation/mongodb/pom.xml index 29e5281277..bbc4acbc5e 100644 --- a/instrumentation/mongodb/pom.xml +++ b/instrumentation/mongodb/pom.xml @@ -30,9 +30,6 @@ brave.mongodb ${project.basedir}/../.. - - 1.6 - java16 3.12.7 @@ -57,4 +54,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/mongodb/src/main/java/brave/mongodb/TraceMongoCommandListener.java b/instrumentation/mongodb/src/main/java/brave/mongodb/TraceMongoCommandListener.java index 4bdc062270..51e6adfc0d 100644 --- a/instrumentation/mongodb/src/main/java/brave/mongodb/TraceMongoCommandListener.java +++ b/instrumentation/mongodb/src/main/java/brave/mongodb/TraceMongoCommandListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -41,7 +41,7 @@ */ final class TraceMongoCommandListener implements CommandListener { // See https://docs.mongodb.com/manual/reference/command for the command reference - static final Set COMMANDS_WITH_COLLECTION_NAME = new LinkedHashSet<>(Arrays.asList( + static final Set COMMANDS_WITH_COLLECTION_NAME = new LinkedHashSet(Arrays.asList( "aggregate", "count", "distinct", "mapReduce", "geoSearch", "delete", "find", "findAndModify", "insert", "update", "collMod", "compact", "convertToCapped", "create", "createIndexes", "drop", "dropIndexes", "killCursors", "listIndexes", "reIndex")); diff --git a/instrumentation/mysql/pom.xml b/instrumentation/mysql/pom.xml index 9fbeb2d7bc..b3060b39b9 100644 --- a/instrumentation/mysql/pom.xml +++ b/instrumentation/mysql/pom.xml @@ -30,9 +30,6 @@ brave.mysql ${project.basedir}/../.. - - 1.6 - java16 @@ -50,4 +47,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/netty-codec-http/pom.xml b/instrumentation/netty-codec-http/pom.xml index 95ec1e7b82..c32fe756da 100644 --- a/instrumentation/netty-codec-http/pom.xml +++ b/instrumentation/netty-codec-http/pom.xml @@ -30,9 +30,6 @@ brave.netty.http ${project.basedir}/../.. - - 1.6 - java16 @@ -54,4 +51,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/netty-codec-http/src/main/java/brave/netty/http/TracingHttpServerHandler.java b/instrumentation/netty-codec-http/src/main/java/brave/netty/http/TracingHttpServerHandler.java index d9b060db8e..31c4f93632 100644 --- a/instrumentation/netty-codec-http/src/main/java/brave/netty/http/TracingHttpServerHandler.java +++ b/instrumentation/netty-codec-http/src/main/java/brave/netty/http/TracingHttpServerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -32,6 +32,8 @@ import java.net.InetSocketAddress; import java.net.URI; +import static brave.internal.Throwables.propagateIfFatal; + final class TracingHttpServerHandler extends ChannelDuplexHandler { final CurrentTraceContext currentTraceContext; final HttpServerHandler handler; @@ -59,7 +61,11 @@ final class TracingHttpServerHandler extends ChannelDuplexHandler { Throwable error = null; try { ctx.fireChannelRead(msg); - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); error = e; throw e; } finally { @@ -83,9 +89,13 @@ final class TracingHttpServerHandler extends ChannelDuplexHandler { Throwable error = null; try { ctx.write(msg, prm); - } catch (Throwable t) { - error = t; - throw t; + } catch (RuntimeException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; + throw e; } finally { HttpServerRequest request = ctx.channel().attr(NettyHttpTracing.REQUEST_ATTRIBUTE).get(); handler.handleSend(new HttpResponseWrapper(request, response, error), span); diff --git a/instrumentation/okhttp3/pom.xml b/instrumentation/okhttp3/pom.xml index e6a44a6f43..b1de28b204 100644 --- a/instrumentation/okhttp3/pom.xml +++ b/instrumentation/okhttp3/pom.xml @@ -85,10 +85,47 @@ mockwebserver ${old-okhttp.version} MAIN + jar + + + + release + + + 1.7 + java17 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/p6spy/pom.xml b/instrumentation/p6spy/pom.xml index 83a5b0d9d3..47e73e56a7 100644 --- a/instrumentation/p6spy/pom.xml +++ b/instrumentation/p6spy/pom.xml @@ -30,8 +30,6 @@ brave.p6spy ${project.basedir}/../.. - 1.6 - java16 3.9.1 10.15.2.0 @@ -72,4 +70,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/p6spy/src/main/java/brave/p6spy/TracingP6SpyOptions.java b/instrumentation/p6spy/src/main/java/brave/p6spy/TracingP6SpyOptions.java index bcc5052e71..2177d9a181 100644 --- a/instrumentation/p6spy/src/main/java/brave/p6spy/TracingP6SpyOptions.java +++ b/instrumentation/p6spy/src/main/java/brave/p6spy/TracingP6SpyOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2022 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -48,7 +48,7 @@ public void load(Map options) { @Override public Map getDefaults() { - Map allDefaults = new LinkedHashMap<>(super.getDefaults()); + Map allDefaults = new LinkedHashMap(super.getDefaults()); allDefaults.putAll(logLoadableOptions.getDefaults()); allDefaults.put(INCLUDE_PARAMETER_VALUES, Boolean.FALSE.toString()); allDefaults.put(INCLUDE_AFFECTED_ROWS_COUNT, Boolean.FALSE.toString()); diff --git a/instrumentation/rpc/pom.xml b/instrumentation/rpc/pom.xml index f0711d40db..51eda335fb 100644 --- a/instrumentation/rpc/pom.xml +++ b/instrumentation/rpc/pom.xml @@ -30,8 +30,6 @@ brave.rpc ${project.basedir}/../.. - 1.6 - java16 @@ -42,4 +40,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/rpc/src/main/java/brave/rpc/RpcRequestMatchers.java b/instrumentation/rpc/src/main/java/brave/rpc/RpcRequestMatchers.java index e0638af2f6..718efe37cd 100644 --- a/instrumentation/rpc/src/main/java/brave/rpc/RpcRequestMatchers.java +++ b/instrumentation/rpc/src/main/java/brave/rpc/RpcRequestMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -33,7 +33,7 @@ public final class RpcRequestMatchers { public static Matcher methodEquals(String method) { if (method == null) throw new NullPointerException("method == null"); if (method.isEmpty()) throw new NullPointerException("method is empty"); - return new RpcMethodEquals<>(method); + return new RpcMethodEquals(method); } static final class RpcMethodEquals implements Matcher { @@ -72,7 +72,7 @@ static final class RpcMethodEquals implements Matcher Matcher serviceEquals(String service) { if (service == null) throw new NullPointerException("service == null"); if (service.isEmpty()) throw new NullPointerException("service is empty"); - return new RpcServiceEquals<>(service); + return new RpcServiceEquals(service); } static final class RpcServiceEquals implements Matcher { diff --git a/instrumentation/rpc/src/main/java/brave/rpc/RpcTracing.java b/instrumentation/rpc/src/main/java/brave/rpc/RpcTracing.java index abc39e8cb9..3d174daacf 100644 --- a/instrumentation/rpc/src/main/java/brave/rpc/RpcTracing.java +++ b/instrumentation/rpc/src/main/java/brave/rpc/RpcTracing.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -32,7 +32,7 @@ * @since 5.8 */ public class RpcTracing implements Closeable { - static final AtomicReference CURRENT = new AtomicReference<>(); + static final AtomicReference CURRENT = new AtomicReference(); /** @since 5.8 */ public static RpcTracing create(Tracing tracing) { diff --git a/instrumentation/servlet-jakarta/pom.xml b/instrumentation/servlet-jakarta/pom.xml index 83bb0ca7ab..22fbfd60fe 100644 --- a/instrumentation/servlet-jakarta/pom.xml +++ b/instrumentation/servlet-jakarta/pom.xml @@ -30,8 +30,6 @@ brave.jakarta.servlet ${project.basedir}/../.. - 1.6 - java16 diff --git a/instrumentation/servlet/pom.xml b/instrumentation/servlet/pom.xml index efc48183db..8f19d1fb65 100644 --- a/instrumentation/servlet/pom.xml +++ b/instrumentation/servlet/pom.xml @@ -30,8 +30,6 @@ brave.servlet ${project.basedir}/../.. - 1.6 - java16 @@ -86,16 +84,54 @@ servlet-api 2.5 MAIN + jar org.eclipse.jetty jetty-servlet ${jetty-servlet25.version} MAIN + jar + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/servlet/src/main/java/brave/servlet/TracingFilter.java b/instrumentation/servlet/src/main/java/brave/servlet/TracingFilter.java index a486cfbd16..4dd155abde 100644 --- a/instrumentation/servlet/src/main/java/brave/servlet/TracingFilter.java +++ b/instrumentation/servlet/src/main/java/brave/servlet/TracingFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -35,6 +35,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static brave.internal.Throwables.propagateIfFatal; + public final class TracingFilter implements Filter { public static Filter create(Tracing tracing) { return new TracingFilter(HttpTracing.create(tracing)); @@ -85,7 +87,17 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha try { // any downstream code can see Tracer.currentSpan() or use Tracer.currentSpanCustomizer() chain.doFilter(req, res); - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (IOException e) { + error = e; + throw e; + } catch (ServletException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); error = e; throw e; } finally { diff --git a/instrumentation/servlet/src/main/java/brave/servlet/internal/ServletRuntime.java b/instrumentation/servlet/src/main/java/brave/servlet/internal/ServletRuntime.java index a9a87dbbda..7fca26afad 100644 --- a/instrumentation/servlet/src/main/java/brave/servlet/internal/ServletRuntime.java +++ b/instrumentation/servlet/src/main/java/brave/servlet/internal/ServletRuntime.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -187,7 +187,7 @@ static final class Servlet25 extends ServletRuntime { // copy-on-write global reflection cache outperforms thread local copies final AtomicReference, Object>> classToGetStatus = - new AtomicReference<>(new LinkedHashMap<>()); + new AtomicReference, Object>>(new LinkedHashMap, Object>()); static final String RETURN_NULL = "RETURN_NULL"; /** @@ -213,14 +213,14 @@ static final class Servlet25 extends ServletRuntime { try { // we don't check for accessibility as isAccessible is deprecated: just fail later getStatusMethod = clazz.getMethod("getStatus"); - return (int) ((Method) getStatusMethod).invoke(response); + return (Integer) ((Method) getStatusMethod).invoke(response); } catch (Throwable throwable) { propagateIfFatal(throwable); getStatusMethod = RETURN_NULL; return 0; } finally { // regardless of success or fail, replace the cache - Map, Object> replacement = new LinkedHashMap<>(classesToCheck); + Map, Object> replacement = new LinkedHashMap, Object>(classesToCheck); replacement.put(clazz, getStatusMethod); classToGetStatus.set(replacement); // lost race will reset, but only up to size - 1 times } @@ -228,10 +228,10 @@ static final class Servlet25 extends ServletRuntime { // if we are here, we have a cached method, that "should" never fail, but we check anyway try { - return (int) ((Method) getStatusMethod).invoke(response); + return (Integer) ((Method) getStatusMethod).invoke(response); } catch (Throwable throwable) { propagateIfFatal(throwable); - Map, Object> replacement = new LinkedHashMap<>(classesToCheck); + Map, Object> replacement = new LinkedHashMap, Object>(classesToCheck); replacement.put(clazz, RETURN_NULL); classToGetStatus.set(replacement); // prefer overriding on failure return 0; diff --git a/instrumentation/sparkjava/pom.xml b/instrumentation/sparkjava/pom.xml index 7247902e56..ccd428d53d 100644 --- a/instrumentation/sparkjava/pom.xml +++ b/instrumentation/sparkjava/pom.xml @@ -55,17 +55,4 @@ - - - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - - - diff --git a/instrumentation/spring-rabbit/pom.xml b/instrumentation/spring-rabbit/pom.xml index 02bbe8eb05..f30ce9f4e2 100644 --- a/instrumentation/spring-rabbit/pom.xml +++ b/instrumentation/spring-rabbit/pom.xml @@ -30,8 +30,6 @@ brave.spring.rabbit ${project.basedir}/../.. - 1.6 - java16 @@ -82,4 +80,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/spring-web/pom.xml b/instrumentation/spring-web/pom.xml index 6fabe6786d..f9e7f656f3 100644 --- a/instrumentation/spring-web/pom.xml +++ b/instrumentation/spring-web/pom.xml @@ -30,8 +30,6 @@ brave.spring.web ${project.basedir}/../.. - 1.6 - java16 @@ -113,10 +111,47 @@ spring-web ${spring.version} MAIN + jar + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/spring-web/src/main/java/brave/spring/web/TraceContextListenableFuture.java b/instrumentation/spring-web/src/main/java/brave/spring/web/TraceContextListenableFuture.java index e90dd5195c..4e2da1591e 100644 --- a/instrumentation/spring-web/src/main/java/brave/spring/web/TraceContextListenableFuture.java +++ b/instrumentation/spring-web/src/main/java/brave/spring/web/TraceContextListenableFuture.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -44,7 +44,7 @@ final class TraceContextListenableFuture implements ListenableFuture { @Override public void addCallback(ListenableFutureCallback callback) { delegate.addCallback(callback != null - ? new TraceContextListenableFutureCallback<>(callback, this) + ? new TraceContextListenableFutureCallback(callback, this) : null ); } @@ -54,7 +54,7 @@ public void addCallback(SuccessCallback successCallback, FailureCallback failureCallback) { delegate.addCallback( successCallback != null - ? new TraceContextSuccessCallback<>(successCallback, this) + ? new TraceContextSuccessCallback(successCallback, this) : null, failureCallback != null ? new TraceContextFailureCallback(failureCallback, this) @@ -104,14 +104,20 @@ static final class TraceContextListenableFutureCallback } @Override public void onSuccess(T result) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.onSuccess(result); + } finally { + scope.close(); } } @Override public void onFailure(Throwable ex) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.onFailure(ex); + } finally { + scope.close(); } } @@ -133,8 +139,11 @@ static final class TraceContextSuccessCallback implements SuccessCallback } @Override public void onSuccess(T result) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.onSuccess(result); + } finally { + scope.close(); } } @@ -156,8 +165,11 @@ static final class TraceContextFailureCallback implements FailureCallback { } @Override public void onFailure(Throwable ex) { - try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { + Scope scope = currentTraceContext.maybeScope(invocationContext); + try { delegate.onFailure(ex); + } finally { + scope.close(); } } diff --git a/instrumentation/spring-web/src/main/java/brave/spring/web/TracingAsyncClientHttpRequestInterceptor.java b/instrumentation/spring-web/src/main/java/brave/spring/web/TracingAsyncClientHttpRequestInterceptor.java index 9f3c23a6f2..c33562851d 100644 --- a/instrumentation/spring-web/src/main/java/brave/spring/web/TracingAsyncClientHttpRequestInterceptor.java +++ b/instrumentation/spring-web/src/main/java/brave/spring/web/TracingAsyncClientHttpRequestInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -33,6 +33,8 @@ import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static brave.internal.Throwables.propagateIfFatal; + public final class TracingAsyncClientHttpRequestInterceptor implements AsyncClientHttpRequestInterceptor { @@ -62,15 +64,29 @@ public static AsyncClientHttpRequestInterceptor create(HttpTracing httpTracing) ? currentTraceContext.get() : null; - try (Scope ws = currentTraceContext.maybeScope(span.context())) { + Scope ws = currentTraceContext.maybeScope(span.context()); + Throwable error = null; + try { ListenableFuture result = execution.executeAsync(req, body); result.addCallback(new TraceListenableFutureCallback(request, span, handler)); return invocationContext != null - ? new TraceContextListenableFuture<>(result, currentTraceContext, invocationContext) + ? new TraceContextListenableFuture(result, currentTraceContext, invocationContext) : result; - } catch (Throwable e) { - handler.handleReceive(new ClientHttpResponseWrapper(request, null, e), span); + } catch (RuntimeException e) { + error = e; + throw e; + } catch (IOException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); + error = e; throw e; + } finally { + if (error != null) { + handler.handleReceive(new ClientHttpResponseWrapper(request, null, error), span); + } + ws.close(); } } diff --git a/instrumentation/spring-web/src/main/java/brave/spring/web/TracingClientHttpRequestInterceptor.java b/instrumentation/spring-web/src/main/java/brave/spring/web/TracingClientHttpRequestInterceptor.java index 03acadab3c..563110d6b1 100644 --- a/instrumentation/spring-web/src/main/java/brave/spring/web/TracingClientHttpRequestInterceptor.java +++ b/instrumentation/spring-web/src/main/java/brave/spring/web/TracingClientHttpRequestInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -29,6 +29,8 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.HttpStatusCodeException; +import static brave.internal.Throwables.propagateIfFatal; + public final class TracingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { public static ClientHttpRequestInterceptor create(Tracing tracing) { return create(HttpTracing.create(tracing)); @@ -51,14 +53,23 @@ public static ClientHttpRequestInterceptor create(HttpTracing httpTracing) { HttpRequestWrapper request = new HttpRequestWrapper(req); Span span = handler.handleSend(request); ClientHttpResponse response = null; + Scope ws = currentTraceContext.newScope(span.context()); Throwable error = null; - try (Scope ws = currentTraceContext.newScope(span.context())) { + try { return response = execution.execute(req, body); - } catch (Throwable e) { + } catch (RuntimeException e) { + error = e; + throw e; + } catch (IOException e) { + error = e; + throw e; + } catch (Error e) { + propagateIfFatal(e); error = e; throw e; } finally { handler.handleReceive(new ClientHttpResponseWrapper(request, response, error), span); + ws.close(); } } diff --git a/instrumentation/spring-webmvc/pom.xml b/instrumentation/spring-webmvc/pom.xml index 644f557fd0..4d9e68bb74 100644 --- a/instrumentation/spring-webmvc/pom.xml +++ b/instrumentation/spring-webmvc/pom.xml @@ -30,8 +30,6 @@ brave.spring.webmvc ${project.basedir}/../.. - 1.6 - java16 @@ -66,20 +64,6 @@ ${jetty.version} test - - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - @@ -89,4 +73,40 @@ + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/instrumentation/spring-webmvc/src/it/servlet25/pom.xml b/instrumentation/spring-webmvc/src/it/servlet25/pom.xml index bb78932c1c..2aa4abbede 100644 --- a/instrumentation/spring-webmvc/src/it/servlet25/pom.xml +++ b/instrumentation/spring-webmvc/src/it/servlet25/pom.xml @@ -1,7 +1,7 @@ false + + + --add-opens java.base/java.lang=ALL-UNNAMED + diff --git a/instrumentation/spring-webmvc/src/it/spring25/pom.xml b/instrumentation/spring-webmvc/src/it/spring25/pom.xml index 1733fc3ab2..c2332af014 100644 --- a/instrumentation/spring-webmvc/src/it/spring25/pom.xml +++ b/instrumentation/spring-webmvc/src/it/spring25/pom.xml @@ -1,7 +1,7 @@ false + + + --add-opens java.base/java.lang=ALL-UNNAMED + diff --git a/instrumentation/spring-webmvc/src/main/java/brave/spring/webmvc/WebMvcRuntime.java b/instrumentation/spring-webmvc/src/main/java/brave/spring/webmvc/WebMvcRuntime.java index be2ac8b506..38777f9b5f 100644 --- a/instrumentation/spring-webmvc/src/main/java/brave/spring/webmvc/WebMvcRuntime.java +++ b/instrumentation/spring-webmvc/src/main/java/brave/spring/webmvc/WebMvcRuntime.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -42,7 +42,7 @@ static WebMvcRuntime findWebMvcRuntime() { // Find spring-webmvc v3.1 new methods try { Class.forName("org.springframework.web.method.HandlerMethod"); - return new WebMvc31(); // intentionally doesn't not access the type prior to the above guard + return new WebMvc31(); // intentionally doesn't access the type prior to the above guard } catch (ClassNotFoundException e) { // pre spring-webmvc v3.1 } diff --git a/instrumentation/spring-webmvc/src/test/java/brave/spring/webmvc/WebMvcRuntimeTest.java b/instrumentation/spring-webmvc/src/test/java/brave/spring/webmvc/WebMvcRuntimeTest.java index bee2fffa50..5f2541d9ba 100644 --- a/instrumentation/spring-webmvc/src/test/java/brave/spring/webmvc/WebMvcRuntimeTest.java +++ b/instrumentation/spring-webmvc/src/test/java/brave/spring/webmvc/WebMvcRuntimeTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -16,43 +16,29 @@ import brave.http.HttpTracing; import brave.spring.webmvc.WebMvcRuntime.WebMvc25; import brave.spring.webmvc.WebMvcRuntime.WebMvc31; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.web.method.HandlerMethod; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) -// Added to declutter console: tells power mock not to mess with implicit classes we aren't testing -@PowerMockIgnore({"org.apache.logging.*", "javax.script.*"}) -@PrepareForTest(WebMvcRuntime.class) -public class WebMvcRuntimeTest { +@ExtendWith(MockitoExtension.class) +class WebMvcRuntimeTest { - @Test public void findWebMvcRuntime_HandlerMethod_exists() throws Exception { + @Test void findWebMvcRuntime_HandlerMethod_exists() { assertThat(WebMvcRuntime.findWebMvcRuntime()) .isInstanceOf(WebMvc31.class); } - @Test public void findWebMvcRuntime_HandlerMethod_notFound() throws Exception { - mockStatic(Class.class); - when(Class.forName(HandlerMethod.class.getName())) - .thenThrow(new ClassNotFoundException()); - - assertThat(WebMvcRuntime.findWebMvcRuntime()) - .isInstanceOf(WebMvc25.class); - } - - @Test public void WebMvc31_isHandlerMethod() { + @Test void WebMvc31_isHandlerMethod() { HandlerMethod handlerMethod = mock(HandlerMethod.class); assertThat(new WebMvc31().isHandlerMethod(handlerMethod)) @@ -60,7 +46,7 @@ public class WebMvcRuntimeTest { } /** Due to HandlerMethod being only present after 3.1, we can't look up the class in 2.5 */ - @Test public void WebMvc25_isHandlerMethod_isFalse() { + @Test void WebMvc25_isHandlerMethod_isFalse() { HandlerMethod handlerMethod = mock(HandlerMethod.class); assertThat(new WebMvc25().isHandlerMethod(handlerMethod)) @@ -68,7 +54,7 @@ public class WebMvcRuntimeTest { } /** Spring 3+ can get beans by type, so use that! */ - @Test public void WebMvc31_httpTracing_byType() { + @Test void WebMvc31_httpTracing_byType() { ApplicationContext context = mock(ApplicationContext.class); new WebMvc31().httpTracing(context); @@ -78,7 +64,7 @@ public class WebMvcRuntimeTest { } /** Spring 2.5 cannot get beans by type, so fallback to name */ - @Test public void WebMvc25_httpTracing_byName() { + @Test void WebMvc25_httpTracing_byName() { ApplicationContext context = mock(ApplicationContext.class); when(context.containsBean("httpTracing")).thenReturn(true); when(context.getBean("httpTracing")).thenReturn(mock(HttpTracing.class)); @@ -90,20 +76,20 @@ public class WebMvcRuntimeTest { verifyNoMoreInteractions(context); } - @Test(expected = NoSuchBeanDefinitionException.class) - public void WebMvc25_httpTracing_whenWrongType() { + @Test void WebMvc25_httpTracing_whenWrongType() { ApplicationContext context = mock(ApplicationContext.class); when(context.containsBean("httpTracing")).thenReturn(true); when(context.getBean("httpTracing")).thenReturn("foo"); - new WebMvc25().httpTracing(context); + assertThatThrownBy(() -> new WebMvc25().httpTracing(context)) + .isInstanceOf(NoSuchBeanDefinitionException.class); } - @Test(expected = NoSuchBeanDefinitionException.class) - public void WebMvc25_httpTracing_whenDoesntExist() { + @Test void WebMvc25_httpTracing_whenDoesntExist() { ApplicationContext context = mock(ApplicationContext.class); when(context.containsBean("httpTracing")).thenReturn(false); - new WebMvc25().httpTracing(context); + assertThatThrownBy(() -> new WebMvc25().httpTracing(context)) + .isInstanceOf(NoSuchBeanDefinitionException.class); } } diff --git a/instrumentation/vertx-web/pom.xml b/instrumentation/vertx-web/pom.xml index e6b107f0a3..38147c518d 100644 --- a/instrumentation/vertx-web/pom.xml +++ b/instrumentation/vertx-web/pom.xml @@ -55,18 +55,4 @@ test - - - - - net.orfjackal.retrolambda - retrolambda-maven-plugin - - - none - - - - - diff --git a/mvnw b/mvnw index 41c0f0c23d..8d937f4c14 100755 --- a/mvnw +++ b/mvnw @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven Start Up Batch script +# Apache Maven Wrapper startup batch script, version 3.2.0 # # Required ENV vars: # ------------------ @@ -27,7 +27,6 @@ # # Optional ENV vars # ----------------- -# M2_HOME - location of maven2's installed home dir # MAVEN_OPTS - parameters passed to the Java VM when running Maven # e.g. to debug Maven itself, use # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @@ -36,6 +35,10 @@ if [ -z "$MAVEN_SKIP_RC" ] ; then + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi @@ -50,7 +53,7 @@ fi cygwin=false; darwin=false; mingw=false -case "`uname`" in +case "$(uname)" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true @@ -58,9 +61,9 @@ case "`uname`" in # See https://developer.apple.com/library/mac/qa/qa1170/_index.html if [ -z "$JAVA_HOME" ]; then if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME else - export JAVA_HOME="/Library/Java/Home" + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME fi fi ;; @@ -68,68 +71,38 @@ esac if [ -z "$JAVA_HOME" ] ; then if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` + JAVA_HOME=$(java-config --jre-home) fi fi -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - # For Cygwin, ensure paths are in UNIX format before anything is touched if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") fi # For Mingw, ensure paths are in UNIX format before anything is touched if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" fi if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" else - javaExecutable="`readlink -f \"$javaExecutable\"`" + javaExecutable="$(readlink -f "\"$javaExecutable\"")" fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') JAVA_HOME="$javaHome" export JAVA_HOME fi @@ -145,7 +118,7 @@ if [ -z "$JAVACMD" ] ; then JAVACMD="$JAVA_HOME/bin/java" fi else - JAVACMD="`which java`" + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" fi fi @@ -159,12 +132,9 @@ if [ -z "$JAVA_HOME" ] ; then echo "Warning: JAVA_HOME environment variable is not set." fi -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { - if [ -z "$1" ] then echo "Path not specified to find_maven_basedir" @@ -180,96 +150,99 @@ find_maven_basedir() { fi # workaround for JBEAP-8937 (on Solaris 10/Sparc) if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` + wdir=$(cd "$wdir/.." || exit 1; pwd) fi # end of workaround done - echo "${basedir}" + printf '%s' "$(cd "$basedir" || exit 1; pwd)" } # concatenates all lines of a file concat_lines() { if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" fi } -BASE_DIR=`find_maven_basedir "$(pwd)"` +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") if [ -z "$BASE_DIR" ]; then exit 1; fi +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + ########################################################################################## # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central # This allows using the maven wrapper in projects that prohibit checking in binary data. ########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi + log "Couldn't find $wrapperJarPath, downloading it ..." + if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") fi if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" fi elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" fi - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" # For Cygwin, switch paths to Windows format before running javac if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" fi fi fi @@ -278,33 +251,58 @@ fi # End of extension ########################################################################################## -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi fi + MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") fi # Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain +# shellcheck disable=SC2086 # safe args exec "$JAVACMD" \ $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd index 86115719e5..f80fbad3e7 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,182 +1,205 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index 2150a116da..ece2b38c9f 100755 --- a/pom.xml +++ b/pom.xml @@ -67,8 +67,8 @@ UTF-8 - 1.7 - java17 + 1.8 + java18 1.8 @@ -120,38 +120,38 @@ 2.9.3 - 4.13.1 - 3.18.1 - 2.0.9 - 3.6.28 + 4.13.2 + 5.10.1 + 3.24.2 + 5.8.0 2.33 - 4.2.4 - 1.15.1 + 4.2.10 + 1.19.3 ${skipTests} - 1.19 + 1.23 1.2.8 - 4.0.rc2 - 5.1.1 - 3.8.1 + 4.3 + 5.1.9 + 3.11.0 - 3.1.2 - 3.0.0-M1 - 3.0.0-M3 + 3.6.1 + 3.1.1 + 3.4.1 - 3.2.0 - 3.0.0-M1 - 3.2.1 - 3.2.0 - 3.2.0 - 3.0.0-M1 - 3.2.4 - 3.2.1 - 3.0.0-M5 - 1.6.8 + 3.4.0 + 3.1.1 + 3.6.0 + 3.6.2 + 3.3.0 + 3.0.1 + 3.5.1 + 3.3.0 + 3.2.2 + 1.6.13 @@ -197,10 +197,24 @@ ${junit.version} test + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + org.assertj assertj-core ${assertj.version} + + + + net.bytebuddy + * + + test @@ -233,7 +247,7 @@ org.mockito - mockito-core + mockito-junit-jupiter ${mockito.version} test @@ -242,16 +256,6 @@ - - - io.takari - maven - 0.7.7 - - 3.6.3 - - - de.qaware.maven @@ -278,6 +282,7 @@ error_prone_core ${errorprone.version} MAIN + jar org.apache.maven.surefire @@ -392,12 +397,13 @@ !release - true ${project.build.directory}/local-repo + verify - true ${skipTests} true + -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN @@ -423,24 +429,6 @@ ${maven-help-plugin.version} - - net.orfjackal.retrolambda - retrolambda-maven-plugin - 2.5.7 - - - - process-main - - - ${main.java.version} - true - true - - - - - org.codehaus.mojo animal-sniffer-maven-plugin @@ -516,9 +504,9 @@ - - [11,15) + + [11,12),[17,18),[21,22) @@ -658,9 +646,10 @@ - error-prone + error-prone-11+ - true + + [11,12),[17,18),[21,22) @@ -669,11 +658,8 @@ ${maven-compiler-plugin.version} true - - 1.8 - 1.8 - 1.8 - + ${main.java.version} + ${main.java.version} true true @@ -690,6 +676,17 @@ -XDcompilePolicy=simple -Xplugin:ErrorProne ${errorprone.args} + + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED @@ -727,7 +724,7 @@ maven-gpg-plugin - 1.6 + 3.1.0 sign-artifacts diff --git a/spring-beans/pom.xml b/spring-beans/pom.xml index a08827ee20..b6709fcbd1 100644 --- a/spring-beans/pom.xml +++ b/spring-beans/pom.xml @@ -31,8 +31,6 @@ brave.spring.beans ${project.basedir}/.. - 1.6 - java16 @@ -74,4 +72,40 @@ test + + + + release + + + 1.6 + java16 + + + + + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + enforce-java + + enforce + + + + + + [11,12) + + + + + + + + + + diff --git a/spring-beans/src/main/java/brave/spring/beans/TracingFactoryBean.java b/spring-beans/src/main/java/brave/spring/beans/TracingFactoryBean.java index a348095846..fe89bafc2e 100644 --- a/spring-beans/src/main/java/brave/spring/beans/TracingFactoryBean.java +++ b/spring-beans/src/main/java/brave/spring/beans/TracingFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2020 The OpenZipkin Authors + * Copyright 2013-2023 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at @@ -38,7 +38,7 @@ public class TracingFactoryBean extends AbstractFactoryBean { String localServiceName; @Deprecated Object localEndpoint, endpoint; // don't pin zipkin class @Deprecated Object spanReporter; // don't pin zipkin class - List spanHandlers = new ArrayList<>(); + List spanHandlers = new ArrayList(); Clock clock; Sampler sampler; @Deprecated ErrorParser errorParser;