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.core.config.plugins.convert;
18  
19  import java.lang.invoke.MethodHandle;
20  import java.lang.invoke.MethodHandles;
21  import java.lang.invoke.MethodType;
22  import java.sql.Time;
23  import java.sql.Timestamp;
24  import java.util.Arrays;
25  import java.util.Date;
26  import java.util.Map;
27  import java.util.concurrent.ConcurrentHashMap;
28  
29  /**
30   * Utility methods for Date classes.
31   */
32  public final class DateTypeConverter {
33  
34      private static final Map<Class<? extends Date>, MethodHandle> CONSTRUCTORS = new ConcurrentHashMap<>();
35  
36      static {
37          final MethodHandles.Lookup lookup = MethodHandles.publicLookup();
38          for (final Class<? extends Date> dateClass : Arrays.asList(Date.class, java.sql.Date.class, Time.class,
39              Timestamp.class)) {
40              try {
41                  CONSTRUCTORS.put(dateClass,
42                      lookup.findConstructor(dateClass, MethodType.methodType(void.class, long.class)));
43              } catch (final NoSuchMethodException | IllegalAccessException ignored) {
44                  // these classes all have this exact constructor
45              }
46          }
47      }
48  
49      /**
50       * Create a Date-related object from a timestamp in millis.
51       *
52       * @param millis timestamp in millis
53       * @param type   date type to use
54       * @param <D>    date class to use
55       * @return new instance of D or null if there was an error
56       */
57      @SuppressWarnings("unchecked")
58      public static <D extends Date> D fromMillis(final long millis, final Class<D> type) {
59          try {
60              return (D) CONSTRUCTORS.get(type).invoke(millis);
61          } catch (final Throwable ignored) {
62              return null;
63          }
64      }
65  
66      private DateTypeConverter() {
67      }
68  }