Remove uses of org.jetbrains annotations (#6558)

* Remove uses of org.jetbrains annotations

We have a mix of org.jetbrains.annotations.NotNull and
javax.annotations.Nonnull. Change all to the latter. Add an errorprone
check to enforce this.

Signed-off-by: Danno Ferrin <danno.ferrin@swirldslabs.com>

* spotless

Signed-off-by: Danno Ferrin <danno.ferrin@swirldslabs.com>

* spdx

Signed-off-by: Danno Ferrin <danno.ferrin@swirldslabs.com>

---------

Signed-off-by: Danno Ferrin <danno.ferrin@swirldslabs.com>
This commit is contained in:
Danno Ferrin
2024-02-12 15:52:18 -07:00
committed by GitHub
parent b6a6402be9
commit 9ef48d4399
22 changed files with 215 additions and 39 deletions

View File

@@ -220,6 +220,7 @@ import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
@@ -232,7 +233,6 @@ import io.vertx.core.json.DecodeException;
import io.vertx.core.metrics.MetricsOptions;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import picocli.AutoComplete;
import picocli.CommandLine;
@@ -1796,7 +1796,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.cacheLastBlocks(numberOfblocksToCache);
}
@NotNull
@Nonnull
private Optional<PluginTransactionSelectorFactory> getTransactionSelectorFactory() {
final Optional<TransactionSelectionService> txSelectionService =
besuPluginContext.getService(TransactionSelectionService.class);

View File

@@ -16,9 +16,9 @@ package org.hyperledger.besu.datatypes;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.apache.tuweni.units.bigints.UInt256;
import org.jetbrains.annotations.NotNull;
/**
* StorageSlotKey represents a key used for storage slots in Ethereum. It contains the hash of the
@@ -105,7 +105,7 @@ public class StorageSlotKey implements Comparable<StorageSlotKey> {
}
@Override
public int compareTo(@NotNull final StorageSlotKey other) {
public int compareTo(@Nonnull final StorageSlotKey other) {
return this.slotHash.compareTo(other.slotHash);
}
}

View File

@@ -37,6 +37,8 @@ dependencies {
testImplementation 'com.google.errorprone:error_prone_test_helpers'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.junit.jupiter:junit-jupiter'
// imported to get org.jetbrains.annotations.NotNull
testImplementation 'org.jetbrains.kotlin:kotlin-stdlib'
epJavac 'com.google.errorprone:error_prone_check_api'
}

View File

@@ -0,0 +1,75 @@
/*
* (c) Copyright 2023 Palantir Technologies Inc. All rights reserved.
* Copyright Hyperledger Besu contributors.
*
* 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
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
/* Derived from https://github.com/palantir/gradle-baseline/blob/6fe385a80291473e7fc1441f176454bec4184d6b/baseline-error-prone/src/main/java/com/palantir/baseline/errorprone/PreferCommonAnnotations.java */
package org.hyperledger.errorpronechecks;
import java.util.Map;
import java.util.Objects;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ImportTree;
import com.sun.tools.javac.code.Type;
/**
* Checker that recommends using the common version of an annotation.
*
* <p>Examples: - Guava's version of {@code @VisibleForTesting} over other copies.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Prefer the common version of annotations over other copies.",
severity = SeverityLevel.WARNING)
public final class PreferCommonAnnotations extends BugChecker implements ImportTreeMatcher {
/** ClassName -> preferred import. */
private static final Map<String, String> PREFERRED_IMPORTS =
Map.of("org.jetbrains.annotations.NotNull", "javax.annotation.Nonnull");
@Override
public Description matchImport(ImportTree tree, VisitorState state) {
Type importType = ASTHelpers.getType(tree.getQualifiedIdentifier());
if (importType == null) {
return Description.NO_MATCH;
}
String importName = importType.toString();
for (Map.Entry<String, String> entry : PREFERRED_IMPORTS.entrySet()) {
String affectedClassName = entry.getKey();
String preferredType = entry.getValue();
if (importName.endsWith(affectedClassName) && !Objects.equals(importName, preferredType)) {
SuggestedFix fix =
SuggestedFix.builder().removeImport(importName).addImport(preferredType).build();
return this.buildDescription(tree)
.setMessage("Do not use " + importName + " use " + preferredType + " instead.")
.addFix(fix)
.build();
}
}
return Description.NO_MATCH;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright Hyperledger Besu contributors.
*
* 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
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class PreferCommonAnnotationsTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(PreferCommonAnnotations.class, getClass());
}
@Test
void preferCommonAnnotationsPositiveCases() {
compilationHelper.addSourceFile("PreferCommonAnnotationsPositiveCases.java").doTest();
}
@Test
void preferCommonAnnotationsNegativeCases() {
compilationHelper.addSourceFile("PreferCommonAnnotationsNegativeCases.java").doTest();
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright Hyperledger Besu contributors.
*
* 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
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import javax.annotation.Nonnull;
public class PreferCommonAnnotationsNegativeCases {
@Nonnull
public String getFoo() {
return "Foo";
}
// Fully Qualified Name is the "escape hatch"
@org.jetbrains.annotations.NotNull
public String getBar() {
return "Bar";
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright Hyperledger Besu contributors.
*
* 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
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
// BUG: Diagnostic contains: Do not use org.jetbrains.annotations.NotNull use
import org.jetbrains.annotations.NotNull;
public class PreferCommonAnnotationsPositiveCases {
@NotNull
public String getFoo() {
return "Foo";
}
}

View File

@@ -59,6 +59,7 @@ import java.util.Optional;
import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
@@ -97,7 +98,6 @@ import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -382,7 +382,7 @@ public class EngineJsonRpcService {
};
}
@NotNull
@Nonnull
private Handler<Buffer> handlerForUser(
final SocketAddress socketAddress,
final ServerWebSocket websocket,

View File

@@ -32,9 +32,9 @@ import org.hyperledger.besu.ethereum.rlp.RLPException;
import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import com.google.common.base.Suppliers;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -95,7 +95,7 @@ public class EthSendRawTransaction implements JsonRpcMethod {
errorReason -> getJsonRpcResponse(requestContext, errorReason, validationResult));
}
@NotNull
@Nonnull
private JsonRpcResponse getJsonRpcResponse(
final JsonRpcRequestContext requestContext,
final TransactionInvalidReason errorReason,

View File

@@ -58,10 +58,10 @@ import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tuweni.bytes.Bytes32;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -211,7 +211,7 @@ public class TraceFilter extends TraceBlock {
return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), result.getArrayNode());
}
@NotNull
@Nonnull
private List<Block> getBlockList(
final long fromBlock, final long toBlock, final Optional<Block> block) {
List<Block> blockList = new ArrayList<>();

View File

@@ -46,12 +46,12 @@ import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import javax.annotation.Nonnull;
import com.google.common.collect.ForwardingMap;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -781,7 +781,7 @@ public class BonsaiWorldStateUpdateAccumulator
}
@Override
public T put(@NotNull final Address address, @NotNull final T value) {
public T put(@Nonnull final Address address, @Nonnull final T value) {
consumer.process(address, value);
return accounts.put(address, value);
}
@@ -811,7 +811,7 @@ public class BonsaiWorldStateUpdateAccumulator
}
@Override
public T put(@NotNull final K slotKey, @NotNull final T value) {
public T put(@Nonnull final K slotKey, @Nonnull final T value) {
consumer.process(address, slotKey);
return storages.put(slotKey, value);
}

View File

@@ -28,8 +28,8 @@ import org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
public class ChainDataPrunerTest {
@@ -121,7 +121,7 @@ public class ChainDataPrunerTest {
@Override
public void shutdown() {}
@NotNull
@Nonnull
@Override
public List<Runnable> shutdownNow() {
return List.of();
@@ -138,12 +138,12 @@ public class ChainDataPrunerTest {
}
@Override
public boolean awaitTermination(final long timeout, final @NotNull TimeUnit unit) {
public boolean awaitTermination(final long timeout, final @Nonnull TimeUnit unit) {
return true;
}
@Override
public void execute(final @NotNull Runnable command) {
public void execute(final @Nonnull Runnable command) {
command.run();
}
}

View File

@@ -41,13 +41,13 @@ import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalNotification;
import org.apache.tuweni.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -168,7 +168,7 @@ public class EthPeers {
}
}
@NotNull
@Nonnull
private List<PeerConnection> getIncompleteConnections(final Bytes id) {
return incompleteConnections.asMap().keySet().stream()
.filter(nrc -> nrc.getPeer().getId().equals(id))

View File

@@ -38,8 +38,8 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,7 +85,7 @@ public class CompleteBlocksTask extends AbstractRetryingPeerTask<List<Block>> {
createEmptyBodyBasedOnProtocolSchedule(protocolSchedule, header))));
}
@NotNull
@Nonnull
private BlockBody createEmptyBodyBasedOnProtocolSchedule(
final ProtocolSchedule protocolSchedule, final BlockHeader header) {
return new BlockBody(

View File

@@ -50,12 +50,12 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.tuweni.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -235,7 +235,7 @@ public class RlpxAgent {
return peerConnectionCompletableFuture;
}
@NotNull
@Nonnull
private CompletableFuture<PeerConnection> createPeerConnectionCompletableFuture(final Peer peer) {
final CompletableFuture<PeerConnection> peerConnectionCompletableFuture =
initiateOutboundConnection(peer);

View File

@@ -59,6 +59,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import com.google.common.base.Ticker;
import com.google.common.cache.Cache;
@@ -75,7 +76,6 @@ import org.ethereum.beacon.discovery.schema.IdentitySchema;
import org.ethereum.beacon.discovery.schema.IdentitySchemaInterpreter;
import org.ethereum.beacon.discovery.schema.NodeRecord;
import org.ethereum.beacon.discovery.schema.NodeRecordFactory;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -1517,7 +1517,7 @@ public class PeerDiscoveryControllerTest {
verify(controller, times(1)).connectOnRlpxLayer(eq(maybePeer.get()));
}
@NotNull
@Nonnull
private Packet prepareForForkIdCheck(
final List<NodeKey> nodeKeys, final DiscoveryPeer sender, final boolean sendForkId) {
final HashMap<PacketType, Bytes> packetTypeBytesHashMap = new HashMap<>();

View File

@@ -39,10 +39,10 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import io.vertx.core.Vertx;
import org.assertj.core.api.Assertions;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -74,7 +74,7 @@ public class NetworkingServiceLifecycleTest {
}
}
@NotNull
@Nonnull
private DefaultP2PNetwork.Builder getP2PNetworkBuilder() {
final DefaultP2PNetwork.Builder builder = builder();
final MutableBlockchain blockchainMock = mock(MutableBlockchain.class);

View File

@@ -22,12 +22,12 @@ import org.hyperledger.besu.evm.internal.Words;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import com.google.common.annotations.VisibleForTesting;
import ethereum.ckzg4844.CKZG4844JNI;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -100,10 +100,10 @@ public class KZGPointEvalPrecompiledContract implements PrecompiledContract {
return 50000;
}
@NotNull
@Nonnull
@Override
public PrecompileContractResult computePrecompile(
final Bytes input, @NotNull final MessageFrame messageFrame) {
final Bytes input, @Nonnull final MessageFrame messageFrame) {
if (input.size() != 192) {
return PrecompileContractResult.halt(

View File

@@ -36,11 +36,11 @@ import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nonnull;
import com.google.common.collect.MultimapBuilder;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
@@ -219,7 +219,7 @@ class EVMExecutorTest {
assertThat(result).isNotNull();
}
@NotNull
@Nonnull
private static SimpleWorld createSimpleWorld() {
SimpleWorld simpleWorld = new SimpleWorld();

View File

@@ -43,10 +43,10 @@ import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import java.util.Deque;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@@ -252,7 +252,7 @@ public class Create2OperationTest {
assertThat(result.getHaltReason()).isEqualTo(CODE_TOO_LARGE);
}
@NotNull
@Nonnull
private MessageFrame testMemoryFrame(
final UInt256 memoryOffset,
final UInt256 memoryLength,

View File

@@ -43,10 +43,10 @@ import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import java.util.Deque;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
class CreateOperationTest {
@@ -271,7 +271,7 @@ class CreateOperationTest {
assertThat(messageFrame.getState()).isEqualTo(MessageFrame.State.CODE_SUSPENDED);
}
@NotNull
@Nonnull
private MessageFrame testMemoryFrame(
final UInt256 memoryOffset,
final UInt256 memoryLength,

View File

@@ -15,6 +15,7 @@
package org.hyperledger.besu.metrics.opentelemetry;
import java.util.Collection;
import javax.annotation.Nonnull;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.metrics.InstrumentType;
@@ -22,7 +23,6 @@ import io.opentelemetry.sdk.metrics.data.AggregationTemporality;
import io.opentelemetry.sdk.metrics.data.MetricData;
import io.opentelemetry.sdk.metrics.export.CollectionRegistration;
import io.opentelemetry.sdk.metrics.export.MetricReader;
import org.jetbrains.annotations.NotNull;
class DebugMetricReader implements MetricReader {
private CollectionRegistration registration;
@@ -34,7 +34,7 @@ class DebugMetricReader implements MetricReader {
}
@Override
public void register(final @NotNull CollectionRegistration registration) {
public void register(final @Nonnull CollectionRegistration registration) {
this.registration = registration;
}
@@ -50,7 +50,7 @@ class DebugMetricReader implements MetricReader {
@Override
public AggregationTemporality getAggregationTemporality(
final @NotNull InstrumentType instrumentType) {
final @Nonnull InstrumentType instrumentType) {
return AggregationTemporality.CUMULATIVE;
}
}