Skip to content

Commit 409a43e

Browse files
authored
MINOR: Collection/Option usage simplification via methods introduced in Java 9 & 11 (#18305)
Relevant methods: 1. `List.of`, `Set.of`, `Map.of` and similar (introduced in Java 9) 2. Optional: `isEmpty` (introduced in Java 11), `stream` (introduced in Java 9). Reviewers: Mickael Maison <[email protected]>
1 parent ca511cd commit 409a43e

File tree

87 files changed

+194
-271
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+194
-271
lines changed

clients/src/main/java/org/apache/kafka/clients/NetworkClient.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1219,7 +1219,7 @@ public long maybeUpdate(long now) {
12191219
return metadataTimeout;
12201220
}
12211221

1222-
if (!metadataAttemptStartMs.isPresent())
1222+
if (metadataAttemptStartMs.isEmpty())
12231223
metadataAttemptStartMs = Optional.of(now);
12241224

12251225
// Beware that the behavior of this method and the computation of timeouts for poll() are
@@ -1412,7 +1412,7 @@ private long maybeUpdate(long now, Node node) {
14121412
if (canSendRequest(nodeConnectionId, now)) {
14131413
Optional<AbstractRequest.Builder<?>> requestOpt = clientTelemetrySender.createRequest();
14141414

1415-
if (!requestOpt.isPresent())
1415+
if (requestOpt.isEmpty())
14161416
return Long.MAX_VALUE;
14171417

14181418
AbstractRequest.Builder<?> request = requestOpt.get();

clients/src/main/java/org/apache/kafka/common/Uuid.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@
2020
import java.util.ArrayList;
2121
import java.util.Arrays;
2222
import java.util.Base64;
23-
import java.util.Collections;
24-
import java.util.HashSet;
2523
import java.util.List;
2624
import java.util.Set;
2725

@@ -51,11 +49,7 @@ public class Uuid implements Comparable<Uuid> {
5149
/**
5250
* The set of reserved UUIDs that will never be returned by the randomUuid method.
5351
*/
54-
public static final Set<Uuid> RESERVED = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
55-
METADATA_TOPIC_ID,
56-
ZERO_UUID,
57-
ONE_UUID
58-
)));
52+
public static final Set<Uuid> RESERVED = Set.of(ZERO_UUID, ONE_UUID);
5953

6054
private final long mostSignificantBits;
6155
private final long leastSignificantBits;

clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ public boolean hasExpired() {
367367
}
368368

369369
synchronized List<KafkaMetric> metrics() {
370-
return unmodifiableList(new ArrayList<>(this.metrics.values()));
370+
return List.copyOf(this.metrics.values());
371371
}
372372

373373
/**

clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/secured/AccessTokenValidatorFactory.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@
1919

2020
import org.jose4j.keys.resolvers.VerificationKeyResolver;
2121

22-
import java.util.Collections;
23-
import java.util.HashSet;
2422
import java.util.List;
2523
import java.util.Map;
2624
import java.util.Set;
@@ -57,7 +55,7 @@ public static AccessTokenValidator create(Map<String, ?> configs,
5755
List<String> l = cu.get(SASL_OAUTHBEARER_EXPECTED_AUDIENCE);
5856

5957
if (l != null)
60-
expectedAudiences = Collections.unmodifiableSet(new HashSet<>(l));
58+
expectedAudiences = Set.copyOf(l);
6159

6260
Integer clockSkew = cu.validateInteger(SASL_OAUTHBEARER_CLOCK_SKEW_SECONDS, false);
6361
String expectedIssuer = cu.validateString(SASL_OAUTHBEARER_EXPECTED_ISSUER, false);

clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerCoordinatorTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ private GroupRebalanceConfig buildRebalanceConfig(Optional<String> groupInstance
223223
groupInstanceId,
224224
retryBackoffMs,
225225
retryBackoffMaxMs,
226-
!groupInstanceId.isPresent());
226+
groupInstanceId.isEmpty());
227227
}
228228

229229
@AfterEach
@@ -4135,7 +4135,7 @@ private static class RackAwareAssignor extends MockPartitionAssignor {
41354135
@Override
41364136
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) {
41374137
subscriptions.forEach((consumer, subscription) -> {
4138-
if (!subscription.rackId().isPresent())
4138+
if (subscription.rackId().isEmpty())
41394139
throw new IllegalStateException("Rack id not provided in subscription for " + consumer);
41404140
rackIds.add(subscription.rackId().get());
41414141
});

clients/src/test/java/org/apache/kafka/common/network/SelectorTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -891,7 +891,7 @@ private KafkaMetric getMetric(String name, Map<String, String> tags) throws Exce
891891
.filter(entry ->
892892
entry.getKey().name().equals(name) && entry.getKey().tags().equals(tags))
893893
.findFirst();
894-
if (!metric.isPresent())
894+
if (metric.isEmpty())
895895
throw new Exception(String.format("Could not find metric called %s with tags %s", name, tags.toString()));
896896

897897
return metric.get().getValue();
@@ -1112,7 +1112,7 @@ private KafkaMetric getMetric(String name) throws Exception {
11121112
Optional<Map.Entry<MetricName, KafkaMetric>> metric = metrics.metrics().entrySet().stream()
11131113
.filter(entry -> entry.getKey().name().equals(name))
11141114
.findFirst();
1115-
if (!metric.isPresent())
1115+
if (metric.isEmpty())
11161116
throw new Exception(String.format("Could not find metric called %s", name));
11171117

11181118
return metric.get().getValue();

connect/api/src/main/java/org/apache/kafka/connect/data/SchemaBuilder.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ public Schema valueSchema() {
420420
public Schema build() {
421421
return new ConnectSchema(type, isOptional(), defaultValue, name, version, doc,
422422
parameters == null ? null : Collections.unmodifiableMap(parameters),
423-
fields == null ? null : Collections.unmodifiableList(new ArrayList<>(fields.values())), keySchema, valueSchema);
423+
fields == null ? null : List.copyOf(fields.values()), keySchema, valueSchema);
424424
}
425425

426426
/**
@@ -441,4 +441,4 @@ private static void checkNotNull(String fieldName, Object val, String fieldToSet
441441
if (val == null)
442442
throw new SchemaBuilderException("Invalid SchemaBuilder call: " + fieldName + " must be specified to set " + fieldToSet);
443443
}
444-
}
444+
}

connect/mirror/src/main/java/org/apache/kafka/connect/mirror/MirrorCheckpointTask.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@
4646
import java.util.concurrent.ExecutionException;
4747
import java.util.function.Function;
4848
import java.util.stream.Collectors;
49-
import java.util.stream.Stream;
5049

5150
import static org.apache.kafka.connect.mirror.MirrorUtils.adminCall;
5251

@@ -196,7 +195,7 @@ Map<TopicPartition, Checkpoint> checkpointsForGroup(Map<TopicPartition, OffsetAn
196195
return upstreamGroupOffsets.entrySet().stream()
197196
.filter(x -> shouldCheckpointTopic(x.getKey().topic())) // Only perform relevant checkpoints filtered by "topic filter"
198197
.map(x -> checkpoint(group, x.getKey(), x.getValue()))
199-
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) // do not emit checkpoints for partitions that don't have offset-syncs
198+
.flatMap(o -> o.stream()) // do not emit checkpoints for partitions that don't have offset-syncs
200199
.filter(x -> x.downstreamOffset() >= 0) // ignore offsets we cannot translate accurately
201200
.filter(this::checkpointIsMoreRecent) // do not emit checkpoints for partitions that have a later checkpoint
202201
.collect(Collectors.toMap(Checkpoint::topicPartition, Function.identity()));

connect/mirror/src/main/java/org/apache/kafka/connect/mirror/MirrorMaker.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,7 @@ public class MirrorMaker {
102102

103103
private static final long SHUTDOWN_TIMEOUT_SECONDS = 60L;
104104

105-
public static final List<Class<?>> CONNECTOR_CLASSES = Collections.unmodifiableList(
106-
Arrays.asList(
107-
MirrorSourceConnector.class,
108-
MirrorHeartbeatConnector.class,
109-
MirrorCheckpointConnector.class));
105+
public static final List<Class<?>> CONNECTOR_CLASSES = List.of(MirrorSourceConnector.class, MirrorHeartbeatConnector.class, MirrorCheckpointConnector.class);
110106

111107
private final Map<SourceAndTarget, Herder> herders = new HashMap<>();
112108
private CountDownLatch startLatch;

connect/mirror/src/main/java/org/apache/kafka/connect/mirror/MirrorSourceConnector.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ private Set<String> toTopics(Collection<TopicPartition> tps) {
420420
void syncTopicAcls()
421421
throws InterruptedException, ExecutionException {
422422
Optional<Collection<AclBinding>> rawBindings = listTopicAclBindings();
423-
if (!rawBindings.isPresent())
423+
if (rawBindings.isEmpty())
424424
return;
425425
List<AclBinding> filteredBindings = rawBindings.get().stream()
426426
.filter(x -> x.pattern().resourceType() == ResourceType.TOPIC)

0 commit comments

Comments
 (0)