View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.util;
18  
19  import java.lang.reflect.Method;
20  
21  import org.apache.logging.log4j.LoggingException;
22  import org.apache.logging.log4j.status.StatusLogger;
23  
24  /**
25   * Base64 encodes Strings. This utility is only necessary because the mechanism to do this changed in Java 8 and
26   * the original method was removed in Java 9.
27   */
28  public final class Base64Util {
29  
30      private static Method encodeMethod = null;
31      private static Object encoder = null;
32  
33      static {
34          try {
35              Class<?> clazz = LoaderUtil.loadClass("java.util.Base64");
36              Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder");
37              Method method = clazz.getMethod("getEncoder");
38              encoder = method.invoke(null);
39              encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class);
40          } catch (Exception ex) {
41              try {
42                  Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter");
43                  encodeMethod = clazz.getMethod("printBase64Binary");
44              } catch (Exception ex2) {
45                  LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2);
46              }
47          }
48      }
49  
50      private Base64Util() {
51      }
52  
53      public static String encode(String str) {
54          if (str == null) {
55              return null;
56          }
57          byte [] data = str.getBytes();
58          if (encodeMethod != null) {
59              try {
60                  return (String) encodeMethod.invoke(encoder, data);
61              } catch (Exception ex) {
62                  throw new LoggingException("Unable to encode String", ex);
63              }
64          }
65          throw new LoggingException("No Encoder, unable to encode string");
66      }
67  }