Skip to content

Commit 8bdd73c

Browse files
authored
KAFKA-19137 Use StandardCharsets.UTF_8 instead of StandardCharsets.UTF_8.name() (#19464)
Replace `StandardCharsets.UTF_8.name()` with `StandardCharsets.UTF_8` to avoid UnsupportedEncodingException and optimize the related code at the same time. Reviewers: Ken Huang <[email protected]>, PoAn Yang <[email protected]>, Chia-Ping Tsai <[email protected]>
1 parent 598eb13 commit 8bdd73c

File tree

7 files changed

+40
-52
lines changed

7 files changed

+40
-52
lines changed

Diff for: connect/file/src/main/java/org/apache/kafka/connect/file/FileStreamSinkTask.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public void start(Map<String, String> props) {
6969
outputStream = new PrintStream(
7070
Files.newOutputStream(Paths.get(filename), StandardOpenOption.CREATE, StandardOpenOption.APPEND),
7171
false,
72-
StandardCharsets.UTF_8.name());
72+
StandardCharsets.UTF_8);
7373
} catch (IOException e) {
7474
throw new ConnectException("Couldn't find or create file '" + filename + "' for FileStreamSinkTask", e);
7575
}

Diff for: connect/mirror/src/main/java/org/apache/kafka/connect/mirror/MirrorMaker.java

+5-12
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,11 @@
5252
import org.slf4j.LoggerFactory;
5353

5454
import java.io.File;
55-
import java.io.UnsupportedEncodingException;
5655
import java.net.InetAddress;
5756
import java.net.URI;
5857
import java.net.URLEncoder;
5958
import java.net.UnknownHostException;
6059
import java.nio.charset.StandardCharsets;
61-
import java.util.Arrays;
6260
import java.util.Collections;
6361
import java.util.HashMap;
6462
import java.util.HashSet;
@@ -236,14 +234,9 @@ private void checkHerder(SourceAndTarget sourceAndTarget) {
236234
private void addHerder(SourceAndTarget sourceAndTarget) {
237235
log.info("creating herder for " + sourceAndTarget.toString());
238236
Map<String, String> workerProps = config.workerConfig(sourceAndTarget);
239-
List<String> restNamespace;
240-
try {
241-
String encodedSource = encodePath(sourceAndTarget.source());
242-
String encodedTarget = encodePath(sourceAndTarget.target());
243-
restNamespace = Arrays.asList(encodedSource, encodedTarget);
244-
} catch (UnsupportedEncodingException e) {
245-
throw new RuntimeException("Unable to create encoded URL paths for source and target using UTF-8", e);
246-
}
237+
String encodedSource = encodePath(sourceAndTarget.source());
238+
String encodedTarget = encodePath(sourceAndTarget.target());
239+
List<String> restNamespace = List.of(encodedSource, encodedTarget);
247240
String workerId = generateWorkerId(sourceAndTarget);
248241
Plugins plugins = new Plugins(workerProps);
249242
plugins.compareAndSwapWithDelegatingLoader();
@@ -282,8 +275,8 @@ private void addHerder(SourceAndTarget sourceAndTarget) {
282275
herders.put(sourceAndTarget, herder);
283276
}
284277

285-
private static String encodePath(String rawPath) throws UnsupportedEncodingException {
286-
return URLEncoder.encode(rawPath, StandardCharsets.UTF_8.name())
278+
private static String encodePath(String rawPath) {
279+
return URLEncoder.encode(rawPath, StandardCharsets.UTF_8)
287280
// Java's out-of-the-box URL encoder encodes spaces (' ') as pluses ('+'),
288281
// and pluses as '%2B'
289282
// But Jetty doesn't decode pluses at all and leaves them as-are in decoded

Diff for: connect/runtime/src/test/java/org/apache/kafka/connect/integration/RestForwardingIntegrationTest.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ public void testRestForwardToLeader(boolean dualListener, boolean followerSsl, b
215215
"\"name\": \"blah\"," +
216216
"\"config\": {}" +
217217
"}";
218-
StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8.name());
218+
StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);
219219
entity.setContentType("application/json");
220220
request.setEntity(entity);
221221
HttpResponse httpResponse = executeRequest(followerUrl, request);

Diff for: connect/runtime/src/test/java/org/apache/kafka/connect/runtime/rest/ConnectRestServerTest.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ private String executeGet(URI serverUrl, String endpoint) throws IOException {
463463

464464
private String executePut(URI serverUrl, String endpoint, String jsonBody) throws IOException {
465465
HttpPut request = new HttpPut(endpoint);
466-
StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8.name());
466+
StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);
467467
entity.setContentType("application/json");
468468
request.setEntity(entity);
469469
HttpResponse response = executeRequest(serverUrl, request);

Diff for: streams/src/test/java/org/apache/kafka/streams/kstream/PrintedTest.java

+7-7
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@
3333
import java.io.IOException;
3434
import java.io.InputStream;
3535
import java.io.PrintStream;
36-
import java.io.UnsupportedEncodingException;
3736
import java.nio.charset.StandardCharsets;
3837
import java.nio.file.Files;
3938

4039
import static org.hamcrest.CoreMatchers.equalTo;
4140
import static org.hamcrest.MatcherAssert.assertThat;
41+
import static org.junit.jupiter.api.Assertions.assertEquals;
4242
import static org.junit.jupiter.api.Assertions.assertThrows;
4343

4444
public class PrintedTest {
@@ -75,34 +75,34 @@ public void shouldCreateProcessorThatPrintsToFile() throws IOException {
7575
}
7676

7777
@Test
78-
public void shouldCreateProcessorThatPrintsToStdOut() throws UnsupportedEncodingException {
78+
public void shouldCreateProcessorThatPrintsToStdOut() {
7979
final ProcessorSupplier<String, Integer, Void, Void> supplier = new PrintedInternal<>(sysOutPrinter).build("processor");
8080
final Processor<String, Integer, Void, Void> processor = supplier.get();
8181

8282
processor.process(new Record<>("good", 2, 0L));
8383
processor.close();
84-
assertThat(sysOut.toString(StandardCharsets.UTF_8.name()), equalTo("[processor]: good, 2\n"));
84+
assertEquals(sysOut.toString(StandardCharsets.UTF_8), "[processor]: good, 2\n");
8585
}
8686

8787
@Test
88-
public void shouldPrintWithLabel() throws UnsupportedEncodingException {
88+
public void shouldPrintWithLabel() {
8989
final Processor<String, Integer, Void, Void> processor = new PrintedInternal<>(sysOutPrinter.withLabel("label"))
9090
.build("processor")
9191
.get();
9292

9393
processor.process(new Record<>("hello", 3, 0L));
9494
processor.close();
95-
assertThat(sysOut.toString(StandardCharsets.UTF_8.name()), equalTo("[label]: hello, 3\n"));
95+
assertEquals(sysOut.toString(StandardCharsets.UTF_8), "[label]: hello, 3\n");
9696
}
9797

9898
@Test
99-
public void shouldPrintWithKeyValueMapper() throws UnsupportedEncodingException {
99+
public void shouldPrintWithKeyValueMapper() {
100100
final Processor<String, Integer, Void, Void> processor = new PrintedInternal<>(
101101
sysOutPrinter.withKeyValueMapper((key, value) -> String.format("%s -> %d", key, value))
102102
).build("processor").get();
103103
processor.process(new Record<>("hello", 1, 0L));
104104
processor.close();
105-
assertThat(sysOut.toString(StandardCharsets.UTF_8.name()), equalTo("[processor]: hello -> 1\n"));
105+
assertEquals(sysOut.toString(StandardCharsets.UTF_8), "[processor]: hello -> 1\n");
106106
}
107107

108108
@Test

Diff for: tools/src/main/java/org/apache/kafka/tools/PushHttpMetricsReporter.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ static HttpURLConnection newHttpConnection(URL url) throws IOException {
235235

236236
// Static package-private so unit tests can mock reading response
237237
static String readResponse(InputStream is) {
238-
try (Scanner s = new Scanner(is, StandardCharsets.UTF_8.name()).useDelimiter("\\A")) {
238+
try (Scanner s = new Scanner(is, StandardCharsets.UTF_8).useDelimiter("\\A")) {
239239
return s.hasNext() ? s.next() : "";
240240
}
241241
}

Diff for: tools/src/test/java/org/apache/kafka/tools/ConnectPluginPathTest.java

+24-29
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
import java.io.OutputStream;
3939
import java.io.PrintStream;
4040
import java.io.UncheckedIOException;
41-
import java.io.UnsupportedEncodingException;
4241
import java.net.MalformedURLException;
4342
import java.nio.charset.StandardCharsets;
4443
import java.nio.file.Files;
@@ -591,34 +590,30 @@ public CommandResult(int returnCode, String out, String err, PluginScanResult re
591590
private static CommandResult runCommand(Object... args) {
592591
ByteArrayOutputStream out = new ByteArrayOutputStream();
593592
ByteArrayOutputStream err = new ByteArrayOutputStream();
594-
try {
595-
int returnCode = ConnectPluginPath.mainNoExit(
596-
Arrays.stream(args)
597-
.map(Object::toString)
598-
.collect(Collectors.toList())
599-
.toArray(new String[]{}),
600-
new PrintStream(out, true, "utf-8"),
601-
new PrintStream(err, true, "utf-8"));
602-
Set<Path> pluginLocations = getPluginLocations(args);
603-
ClassLoader parent = ConnectPluginPath.class.getClassLoader();
604-
ClassLoaderFactory factory = new ClassLoaderFactory();
605-
try (DelegatingClassLoader delegatingClassLoader = factory.newDelegatingClassLoader(parent)) {
606-
Set<PluginSource> sources = PluginUtils.pluginSources(pluginLocations, delegatingClassLoader, factory);
607-
String stdout = new String(out.toByteArray(), StandardCharsets.UTF_8);
608-
String stderr = new String(err.toByteArray(), StandardCharsets.UTF_8);
609-
log.info("STDOUT:\n{}", stdout);
610-
log.info("STDERR:\n{}", stderr);
611-
return new CommandResult(
612-
returnCode,
613-
stdout,
614-
stderr,
615-
new ReflectionScanner().discoverPlugins(sources),
616-
new ServiceLoaderScanner().discoverPlugins(sources)
617-
);
618-
} catch (IOException e) {
619-
throw new RuntimeException(e);
620-
}
621-
} catch (UnsupportedEncodingException e) {
593+
int returnCode = ConnectPluginPath.mainNoExit(
594+
Arrays.stream(args)
595+
.map(Object::toString)
596+
.toList()
597+
.toArray(new String[]{}),
598+
new PrintStream(out, true, StandardCharsets.UTF_8),
599+
new PrintStream(err, true, StandardCharsets.UTF_8));
600+
Set<Path> pluginLocations = getPluginLocations(args);
601+
ClassLoader parent = ConnectPluginPath.class.getClassLoader();
602+
ClassLoaderFactory factory = new ClassLoaderFactory();
603+
try (DelegatingClassLoader delegatingClassLoader = factory.newDelegatingClassLoader(parent)) {
604+
Set<PluginSource> sources = PluginUtils.pluginSources(pluginLocations, delegatingClassLoader, factory);
605+
String stdout = out.toString(StandardCharsets.UTF_8);
606+
String stderr = err.toString(StandardCharsets.UTF_8);
607+
log.info("STDOUT:\n{}", stdout);
608+
log.info("STDERR:\n{}", stderr);
609+
return new CommandResult(
610+
returnCode,
611+
stdout,
612+
stderr,
613+
new ReflectionScanner().discoverPlugins(sources),
614+
new ServiceLoaderScanner().discoverPlugins(sources)
615+
);
616+
} catch (IOException e) {
622617
throw new RuntimeException(e);
623618
}
624619
}

0 commit comments

Comments
 (0)