Skip to content

Commit 5cf6a9d

Browse files
authored
MINOR: Cleanup Tools Module (1/n) (#20091)
Now that Kafka support Java 17, this PR makes some changes in tools module. The changes in this PR are limited to only some files. A future PR(s) shall follow. The changes mostly include: - Collections.emptyList(), Collections.singletonList() and Arrays.asList() are replaced with List.of() - Collections.emptyMap() and Collections.singletonMap() are replaced with Map.of() - Collections.singleton() is replaced with Set.of() Sub modules targeted: tools/src/main Reviewers: Ken Huang <s7133700@gmail.com>, Jhen-Yung Hsu <jhenyunghsu@gmail.com>, Chia-Ping Tsai <chia7712@gmail.com>
1 parent dfd996e commit 5cf6a9d

35 files changed

+264
-322
lines changed

tools/src/main/java/org/apache/kafka/tools/AclCommand.java

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,7 @@
4040
import java.io.IOException;
4141
import java.util.AbstractMap;
4242
import java.util.ArrayList;
43-
import java.util.Arrays;
4443
import java.util.Collection;
45-
import java.util.Collections;
4644
import java.util.HashMap;
4745
import java.util.HashSet;
4846
import java.util.List;
@@ -177,7 +175,7 @@ private static void printResourceAcls(Map<ResourcePattern, Set<AccessControlEntr
177175

178176
private static void removeAcls(Admin adminClient, Set<AccessControlEntry> acls, ResourcePatternFilter filter) throws ExecutionException, InterruptedException {
179177
if (acls.isEmpty()) {
180-
adminClient.deleteAcls(Collections.singletonList(new AclBindingFilter(filter, AccessControlEntryFilter.ANY))).all().get();
178+
adminClient.deleteAcls(List.of(new AclBindingFilter(filter, AccessControlEntryFilter.ANY))).all().get();
181179
} else {
182180
List<AclBindingFilter> aclBindingFilters = acls.stream().map(acl -> new AclBindingFilter(filter, acl.toFilter())).collect(Collectors.toList());
183181
adminClient.deleteAcls(aclBindingFilters).all().get();
@@ -249,8 +247,8 @@ private static Map<ResourcePatternFilter, Set<AccessControlEntry>> getProducerRe
249247
Set<ResourcePatternFilter> transactionalIds = filters.stream().filter(f -> f.resourceType() == ResourceType.TRANSACTIONAL_ID).collect(Collectors.toSet());
250248
boolean enableIdempotence = opts.options.has(opts.idempotentOpt);
251249

252-
Set<AccessControlEntry> topicAcls = getAcl(opts, new HashSet<>(Arrays.asList(WRITE, DESCRIBE, CREATE)));
253-
Set<AccessControlEntry> transactionalIdAcls = getAcl(opts, new HashSet<>(Arrays.asList(WRITE, DESCRIBE)));
250+
Set<AccessControlEntry> topicAcls = getAcl(opts, Set.of(WRITE, DESCRIBE, CREATE));
251+
Set<AccessControlEntry> transactionalIdAcls = getAcl(opts, Set.of(WRITE, DESCRIBE));
254252

255253
//Write, Describe, Create permission on topics, Write, Describe on transactionalIds
256254
Map<ResourcePatternFilter, Set<AccessControlEntry>> result = new HashMap<>();
@@ -261,7 +259,7 @@ private static Map<ResourcePatternFilter, Set<AccessControlEntry>> getProducerRe
261259
result.put(transactionalId, transactionalIdAcls);
262260
}
263261
if (enableIdempotence) {
264-
result.put(CLUSTER_RESOURCE_FILTER, getAcl(opts, Collections.singleton(IDEMPOTENT_WRITE)));
262+
result.put(CLUSTER_RESOURCE_FILTER, getAcl(opts, Set.of(IDEMPOTENT_WRITE)));
265263
}
266264
return result;
267265
}
@@ -272,8 +270,8 @@ private static Map<ResourcePatternFilter, Set<AccessControlEntry>> getConsumerRe
272270
Set<ResourcePatternFilter> groups = filters.stream().filter(f -> f.resourceType() == ResourceType.GROUP).collect(Collectors.toSet());
273271

274272
//Read, Describe on topic, Read on consumerGroup
275-
Set<AccessControlEntry> topicAcls = getAcl(opts, new HashSet<>(Arrays.asList(READ, DESCRIBE)));
276-
Set<AccessControlEntry> groupAcls = getAcl(opts, Collections.singleton(READ));
273+
Set<AccessControlEntry> topicAcls = getAcl(opts, Set.of(READ, DESCRIBE));
274+
Set<AccessControlEntry> groupAcls = getAcl(opts, Set.of(READ));
277275

278276
Map<ResourcePatternFilter, Set<AccessControlEntry>> result = new HashMap<>();
279277
for (ResourcePatternFilter topic : topics) {
@@ -333,9 +331,9 @@ private static Set<String> getHosts(AclCommandOptions opts, OptionSpec<String> h
333331
if (opts.options.has(hostOptionSpec)) {
334332
return opts.options.valuesOf(hostOptionSpec).stream().map(String::trim).collect(Collectors.toSet());
335333
} else if (opts.options.has(principalOptionSpec)) {
336-
return Collections.singleton(AclEntry.WILDCARD_HOST);
334+
return Set.of(AclEntry.WILDCARD_HOST);
337335
} else {
338-
return Collections.emptySet();
336+
return Set.of();
339337
}
340338
}
341339

@@ -345,7 +343,7 @@ private static Set<KafkaPrincipal> getPrincipals(AclCommandOptions opts, OptionS
345343
.map(s -> SecurityUtils.parseKafkaPrincipal(s.trim()))
346344
.collect(Collectors.toSet());
347345
} else {
348-
return Collections.emptySet();
346+
return Set.of();
349347
}
350348
}
351349

@@ -547,7 +545,7 @@ void checkArgs() {
547545
if (!options.has(bootstrapServerOpt) && !options.has(bootstrapControllerOpt)) {
548546
CommandLineUtils.printUsageAndExit(parser, "One of --bootstrap-server or --bootstrap-controller must be specified");
549547
}
550-
List<AbstractOptionSpec<?>> mutuallyExclusiveOptions = Arrays.asList(addOpt, removeOpt, listOpt);
548+
List<AbstractOptionSpec<?>> mutuallyExclusiveOptions = List.of(addOpt, removeOpt, listOpt);
551549
long mutuallyExclusiveOptionsCount = mutuallyExclusiveOptions.stream()
552550
.filter(abstractOptionSpec -> options.has(abstractOptionSpec))
553551
.count();
@@ -592,10 +590,10 @@ public PatternType convert(String value) {
592590

593591
@Override
594592
public String valuePattern() {
595-
List<PatternType> values = Arrays.asList(PatternType.values());
593+
List<PatternType> values = List.of(PatternType.values());
596594
List<PatternType> filteredValues = values.stream()
597595
.filter(type -> type != PatternType.UNKNOWN)
598-
.collect(Collectors.toList());
596+
.toList();
599597
return filteredValues.stream()
600598
.map(Object::toString)
601599
.collect(Collectors.joining("|"));

tools/src/main/java/org/apache/kafka/tools/ClientCompatibilityTest.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,14 +59,14 @@
5959
import java.time.Duration;
6060
import java.util.Arrays;
6161
import java.util.Collection;
62-
import java.util.Collections;
6362
import java.util.HashMap;
6463
import java.util.Iterator;
6564
import java.util.LinkedList;
6665
import java.util.List;
6766
import java.util.Map;
6867
import java.util.NoSuchElementException;
6968
import java.util.Properties;
69+
import java.util.Set;
7070
import java.util.concurrent.ExecutionException;
7171
import java.util.concurrent.Future;
7272

@@ -291,13 +291,13 @@ void testAdminClient() throws Throwable {
291291
tryFeature("createTopics", testConfig.createTopicsSupported,
292292
() -> {
293293
try {
294-
client.createTopics(Collections.singleton(
294+
client.createTopics(Set.of(
295295
new NewTopic("newtopic", 1, (short) 1))).all().get();
296296
} catch (ExecutionException e) {
297297
throw e.getCause();
298298
}
299299
},
300-
() -> createTopicsResultTest(client, Collections.singleton("newtopic"))
300+
() -> createTopicsResultTest(client, Set.of("newtopic"))
301301
);
302302

303303
while (true) {
@@ -337,7 +337,7 @@ private void testDescribeConfigsMethod(final Admin client) throws Throwable {
337337
);
338338

339339
Map<ConfigResource, Config> brokerConfig =
340-
client.describeConfigs(Collections.singleton(configResource)).all().get();
340+
client.describeConfigs(Set.of(configResource)).all().get();
341341

342342
if (brokerConfig.get(configResource).entries().isEmpty()) {
343343
throw new KafkaException("Expected to see config entries, but got zero entries");

tools/src/main/java/org/apache/kafka/tools/ClientMetricsCommand.java

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@
3737
import java.io.IOException;
3838
import java.util.Arrays;
3939
import java.util.Collection;
40-
import java.util.Collections;
4140
import java.util.HashMap;
4241
import java.util.List;
4342
import java.util.Map;
43+
import java.util.Objects;
4444
import java.util.Optional;
4545
import java.util.Properties;
4646
import java.util.Set;
@@ -91,11 +91,7 @@ static void execute(String... args) throws Exception {
9191
}
9292
} catch (ExecutionException e) {
9393
Throwable cause = e.getCause();
94-
if (cause != null) {
95-
printException(cause);
96-
} else {
97-
printException(e);
98-
}
94+
printException(Objects.requireNonNullElse(cause, e));
9995
exitCode = 1;
10096
} catch (Throwable t) {
10197
printException(t);
@@ -130,8 +126,8 @@ public void alterClientMetrics(ClientMetricsCommandOptions opts) throws Exceptio
130126
Collection<AlterConfigOp> alterEntries = configsToBeSet.entrySet().stream()
131127
.map(entry -> new AlterConfigOp(new ConfigEntry(entry.getKey(), entry.getValue()),
132128
entry.getValue().isEmpty() ? AlterConfigOp.OpType.DELETE : AlterConfigOp.OpType.SET))
133-
.collect(Collectors.toList());
134-
adminClient.incrementalAlterConfigs(Collections.singletonMap(configResource, alterEntries), alterOptions).all()
129+
.toList();
130+
adminClient.incrementalAlterConfigs(Map.of(configResource, alterEntries), alterOptions).all()
135131
.get(30, TimeUnit.SECONDS);
136132

137133
System.out.println("Altered client metrics config for " + entityName + ".");
@@ -144,8 +140,8 @@ public void deleteClientMetrics(ClientMetricsCommandOptions opts) throws Excepti
144140
ConfigResource configResource = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, entityName);
145141
AlterConfigsOptions alterOptions = new AlterConfigsOptions().timeoutMs(30000).validateOnly(false);
146142
Collection<AlterConfigOp> alterEntries = oldConfigs.stream()
147-
.map(entry -> new AlterConfigOp(entry, AlterConfigOp.OpType.DELETE)).collect(Collectors.toList());
148-
adminClient.incrementalAlterConfigs(Collections.singletonMap(configResource, alterEntries), alterOptions)
143+
.map(entry -> new AlterConfigOp(entry, AlterConfigOp.OpType.DELETE)).toList();
144+
adminClient.incrementalAlterConfigs(Map.of(configResource, alterEntries), alterOptions)
149145
.all().get(30, TimeUnit.SECONDS);
150146

151147
System.out.println("Deleted client metrics config for " + entityName + ".");
@@ -162,7 +158,7 @@ public void describeClientMetrics(ClientMetricsCommandOptions opts) throws Excep
162158
System.out.println("The client metric resource " + entityNameOpt.get() + " doesn't exist and doesn't have dynamic config.");
163159
return;
164160
}
165-
entities = Collections.singletonList(entityNameOpt.get());
161+
entities = List.of(entityNameOpt.get());
166162
} else {
167163
Collection<ConfigResource> resources = adminClient
168164
.listConfigResources(Set.of(ConfigResource.Type.CLIENT_METRICS), new ListConfigResourcesOptions())
@@ -189,7 +185,7 @@ public void listClientMetrics() throws Exception {
189185

190186
private Collection<ConfigEntry> getClientMetricsConfig(String entityName) throws Exception {
191187
ConfigResource configResource = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, entityName);
192-
Map<ConfigResource, Config> result = adminClient.describeConfigs(Collections.singleton(configResource))
188+
Map<ConfigResource, Config> result = adminClient.describeConfigs(Set.of(configResource))
193189
.all().get(30, TimeUnit.SECONDS);
194190
return result.get(configResource).entries();
195191
}

tools/src/main/java/org/apache/kafka/tools/ClusterTool.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@
3232
import net.sourceforge.argparse4j.inf.Subparsers;
3333

3434
import java.io.PrintStream;
35-
import java.util.Arrays;
3635
import java.util.Collection;
36+
import java.util.List;
3737
import java.util.Optional;
3838
import java.util.Properties;
3939
import java.util.concurrent.ExecutionException;
@@ -74,7 +74,7 @@ static void execute(String... args) throws Exception {
7474
.help("Unregister a broker.");
7575
Subparser listEndpoints = subparsers.addParser("list-endpoints")
7676
.help("List endpoints");
77-
for (Subparser subpparser : Arrays.asList(clusterIdParser, unregisterParser, listEndpoints)) {
77+
for (Subparser subpparser : List.of(clusterIdParser, unregisterParser, listEndpoints)) {
7878
MutuallyExclusiveGroup connectionOptions = subpparser.addMutuallyExclusiveGroup().required(true);
7979
connectionOptions.addArgument("--bootstrap-server", "-b")
8080
.action(store())
@@ -162,7 +162,7 @@ static void listEndpoints(PrintStream stream, Admin adminClient, boolean listCon
162162
Collection<Node> nodes = adminClient.describeCluster(option).nodes().get();
163163

164164
String maxHostLength = String.valueOf(nodes.stream().map(node -> node.host().length()).max(Integer::compareTo).orElse(100));
165-
String maxRackLength = String.valueOf(nodes.stream().filter(node -> node.hasRack()).map(node -> node.rack().length()).max(Integer::compareTo).orElse(10));
165+
String maxRackLength = String.valueOf(nodes.stream().filter(Node::hasRack).map(node -> node.rack().length()).max(Integer::compareTo).orElse(10));
166166

167167
if (listControllerEndpoints) {
168168
String format = "%-10s %-" + maxHostLength + "s %-10s %-" + maxRackLength + "s %-15s%n";

tools/src/main/java/org/apache/kafka/tools/ConnectPluginPath.java

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
import java.nio.file.Path;
4343
import java.nio.file.Paths;
4444
import java.util.ArrayList;
45-
import java.util.Arrays;
4645
import java.util.Collections;
4746
import java.util.EnumSet;
4847
import java.util.HashMap;
@@ -149,14 +148,12 @@ private static Config parseConfig(ArgumentParser parser, Namespace namespace, Pr
149148
if (subcommand == null) {
150149
throw new ArgumentParserException("No subcommand specified", parser);
151150
}
152-
switch (subcommand) {
153-
case "list":
154-
return new Config(Command.LIST, locations, false, false, out, err);
155-
case "sync-manifests":
156-
return new Config(Command.SYNC_MANIFESTS, locations, namespace.getBoolean("dry_run"), namespace.getBoolean("keep_not_found"), out, err);
157-
default:
158-
throw new ArgumentParserException("Unrecognized subcommand: '" + subcommand + "'", parser);
159-
}
151+
return switch (subcommand) {
152+
case "list" -> new Config(Command.LIST, locations, false, false, out, err);
153+
case "sync-manifests" ->
154+
new Config(Command.SYNC_MANIFESTS, locations, namespace.getBoolean("dry_run"), namespace.getBoolean("keep_not_found"), out, err);
155+
default -> throw new ArgumentParserException("Unrecognized subcommand: '" + subcommand + "'", parser);
156+
};
160157
}
161158

162159
private static Set<Path> parseLocations(ArgumentParser parser, Namespace namespace) throws ArgumentParserException, TerseException {
@@ -197,7 +194,7 @@ private static Set<Path> parseLocations(ArgumentParser parser, Namespace namespa
197194
}
198195

199196
enum Command {
200-
LIST, SYNC_MANIFESTS;
197+
LIST, SYNC_MANIFESTS
201198
}
202199

203200
private static class Config {
@@ -326,11 +323,12 @@ private static Set<Row> enumerateRows(ManifestWorkspace.SourceWorkspace<?> works
326323
rowAliases.add(PluginUtils.prunedName(pluginDesc));
327324
rows.add(newRow(workspace, pluginDesc.className(), new ArrayList<>(rowAliases), pluginDesc.type(), pluginDesc.version(), true));
328325
// If a corresponding manifest exists, mark it as loadable by removing it from the map.
326+
// TODO: The use of Collections here shall be fixed with KAFKA-19524.
329327
nonLoadableManifests.getOrDefault(pluginDesc.className(), Collections.emptySet()).remove(pluginDesc.type());
330328
});
331329
nonLoadableManifests.forEach((className, types) -> types.forEach(type -> {
332330
// All manifests which remain in the map are not loadable
333-
rows.add(newRow(workspace, className, Collections.emptyList(), type, PluginDesc.UNDEFINED_VERSION, false));
331+
rows.add(newRow(workspace, className, List.of(), type, PluginDesc.UNDEFINED_VERSION, false));
334332
}));
335333
return rows;
336334
}
@@ -436,8 +434,8 @@ private static void listTablePrint(Config config, Object... args) {
436434
}
437435

438436
private static PluginScanResult discoverPlugins(PluginSource source, ReflectionScanner reflectionScanner, ServiceLoaderScanner serviceLoaderScanner) {
439-
PluginScanResult serviceLoadResult = serviceLoaderScanner.discoverPlugins(Collections.singleton(source));
440-
PluginScanResult reflectiveResult = reflectionScanner.discoverPlugins(Collections.singleton(source));
441-
return new PluginScanResult(Arrays.asList(serviceLoadResult, reflectiveResult));
437+
PluginScanResult serviceLoadResult = serviceLoaderScanner.discoverPlugins(Set.of(source));
438+
PluginScanResult reflectiveResult = reflectionScanner.discoverPlugins(Set.of(source));
439+
return new PluginScanResult(List.of(serviceLoadResult, reflectiveResult));
442440
}
443441
}

tools/src/main/java/org/apache/kafka/tools/ConsumerPerformance.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
import java.text.SimpleDateFormat;
3838
import java.time.Duration;
3939
import java.util.Collection;
40-
import java.util.Collections;
4140
import java.util.Map;
4241
import java.util.Properties;
4342
import java.util.Random;
@@ -221,8 +220,8 @@ private static void printExtendedProgress(long bytesRead,
221220
}
222221

223222
public static class ConsumerPerfRebListener implements ConsumerRebalanceListener {
224-
private AtomicLong joinTimeMs;
225-
private AtomicLong joinTimeMsInSingleRound;
223+
private final AtomicLong joinTimeMs;
224+
private final AtomicLong joinTimeMsInSingleRound;
226225
private long joinStartMs;
227226

228227
public ConsumerPerfRebListener(AtomicLong joinTimeMs, long joinStartMs, AtomicLong joinTimeMsInSingleRound) {
@@ -355,7 +354,7 @@ public Properties props() throws IOException {
355354
}
356355

357356
public Set<String> topic() {
358-
return Collections.singleton(options.valueOf(topicOpt));
357+
return Set.of(options.valueOf(topicOpt));
359358
}
360359

361360
public long numMessages() {

tools/src/main/java/org/apache/kafka/tools/DelegationTokenCommand.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
import java.text.SimpleDateFormat;
3939
import java.util.ArrayList;
4040
import java.util.Base64;
41-
import java.util.Collections;
4241
import java.util.List;
4342
import java.util.Properties;
4443
import java.util.Set;
@@ -106,7 +105,7 @@ public static DelegationToken createToken(Admin adminClient, DelegationTokenComm
106105
CreateDelegationTokenResult createResult = adminClient.createDelegationToken(createDelegationTokenOptions);
107106
DelegationToken token = createResult.delegationToken().get();
108107
System.out.println("Created delegation token with tokenId : " + token.tokenInfo().tokenId());
109-
printToken(Collections.singletonList(token));
108+
printToken(List.of(token));
110109

111110
return token;
112111
}

tools/src/main/java/org/apache/kafka/tools/EndToEndLatency.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@
3434
import java.nio.charset.StandardCharsets;
3535
import java.time.Duration;
3636
import java.util.Arrays;
37-
import java.util.Collections;
3837
import java.util.List;
3938
import java.util.Optional;
4039
import java.util.Properties;
4140
import java.util.Random;
41+
import java.util.Set;
4242
import java.util.concurrent.ExecutionException;
4343
import java.util.stream.Collectors;
4444

@@ -90,7 +90,7 @@ static void execute(String... args) throws Exception {
9090
int messageSizeBytes = Integer.parseInt(args[4]);
9191
Optional<String> propertiesFile = (args.length > 5 && !Utils.isBlank(args[5])) ? Optional.of(args[5]) : Optional.empty();
9292

93-
if (!Arrays.asList("1", "all").contains(acks)) {
93+
if (!List.of("1", "all").contains(acks)) {
9494
throw new IllegalArgumentException("Latency testing requires synchronous acknowledgement. Please use 1 or all");
9595
}
9696

@@ -186,7 +186,7 @@ private static void createTopic(Optional<String> propertiesFile, String brokers,
186186
Admin adminClient = Admin.create(adminProps);
187187
NewTopic newTopic = new NewTopic(topic, DEFAULT_NUM_PARTITIONS, DEFAULT_REPLICATION_FACTOR);
188188
try {
189-
adminClient.createTopics(Collections.singleton(newTopic)).all().get();
189+
adminClient.createTopics(Set.of(newTopic)).all().get();
190190
} catch (ExecutionException | InterruptedException e) {
191191
System.out.printf("Creation of topic %s failed%n", topic);
192192
throw new RuntimeException(e);

0 commit comments

Comments
 (0)