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  
23  /**
24   * Base64 encodes Strings. This utility is only necessary because the mechanism to do this changed in Java 8 and
25   * the original method was removed in Java 9.
26   */
27  public final class Base64Util {
28  
29      private static Method encodeMethod = null;
30      private static Object encoder = null;
31  
32      static {
33          try {
34              Class<?> clazz = LoaderUtil.loadClass("java.util.Base64");
35              Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder");
36              Method method = clazz.getMethod("getEncoder");
37              encoder = method.invoke(null);
38              encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class);
39          } catch (Exception ex) {
40              try {
41                  Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter");
42                  encodeMethod = clazz.getMethod("printBase64Binary");
43              } catch (Exception ex2) {
44                  LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2);
45              }
46          }
47      }
48  
49      private Base64Util() {
50      }
51  
52      public static String encode(String str) {
53          if (str == null) {
54              return null;
55          }
56          byte [] data = str.getBytes();
57          if (encodeMethod != null) {
58              try {
59                  return (String) encodeMethod.invoke(encoder, data);
60              } catch (Exception ex) {
61                  throw new LoggingException("Unable to encode String", ex);
62              }
63          }
64          throw new LoggingException("No Encoder, unable to encode string");
65      }
66  }