Skip to content

Commit 0a860c5

Browse files
author
Jan Luehe
committed
Have org.apache.logging.log4j.util.Base64Util invoke java.util.Base64 directly instead of reflectively (#3686)
1 parent 2bc484c commit 0a860c5

File tree

1 file changed

+3
-37
lines changed

1 file changed

+3
-37
lines changed

log4j-api/src/main/java/org/apache/logging/log4j/util/Base64Util.java

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,8 @@
1616
*/
1717
package org.apache.logging.log4j.util;
1818

19-
import java.lang.reflect.Method;
2019
import java.nio.charset.Charset;
21-
import org.apache.logging.log4j.Logger;
22-
import org.apache.logging.log4j.LoggingException;
23-
import org.apache.logging.log4j.status.StatusLogger;
20+
import java.util.Base64;
2421

2522
/**
2623
* Base64 encodes Strings. This utility is only necessary because the mechanism to do this changed in Java 8 and
@@ -30,27 +27,7 @@
3027
*/
3128
public final class Base64Util {
3229

33-
private static final Logger LOGGER = StatusLogger.getLogger();
34-
35-
private static Method encodeMethod = null;
36-
private static Object encoder = null;
37-
38-
static {
39-
try {
40-
final Class<?> clazz = LoaderUtil.loadClass("java.util.Base64");
41-
final Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder");
42-
final Method method = clazz.getMethod("getEncoder");
43-
encoder = method.invoke(null);
44-
encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class);
45-
} catch (Exception ex) {
46-
try {
47-
final Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter");
48-
encodeMethod = clazz.getMethod("printBase64Binary");
49-
} catch (Exception ex2) {
50-
LOGGER.error("Unable to create a Base64 Encoder", ex2);
51-
}
52-
}
53-
}
30+
private static final Base64.Encoder encoder = Base64.getEncoder();
5431

5532
private Base64Util() {}
5633

@@ -60,17 +37,6 @@ private Base64Util() {}
6037
*/
6138
@Deprecated
6239
public static String encode(final String str) {
63-
if (str == null) {
64-
return null;
65-
}
66-
final byte[] data = str.getBytes(Charset.defaultCharset());
67-
if (encodeMethod != null) {
68-
try {
69-
return (String) encodeMethod.invoke(encoder, data);
70-
} catch (Exception ex) {
71-
throw new LoggingException("Unable to encode String", ex);
72-
}
73-
}
74-
throw new LoggingException("No Encoder, unable to encode string");
40+
return str != null ? encoder.encodeToString(str.getBytes(Charset.defaultCharset())) : null;
7541
}
7642
}

0 commit comments

Comments
 (0)