001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.config.plugins.convert;
018
019import java.lang.invoke.MethodHandle;
020import java.lang.invoke.MethodHandles;
021import java.lang.invoke.MethodType;
022import java.sql.Time;
023import java.sql.Timestamp;
024import java.util.Arrays;
025import java.util.Date;
026import java.util.Map;
027import java.util.concurrent.ConcurrentHashMap;
028
029/**
030 * Utility methods for Date classes.
031 */
032public final class DateTypeConverter {
033
034    private static final Map<Class<? extends Date>, MethodHandle> CONSTRUCTORS = new ConcurrentHashMap<>();
035
036    static {
037        final MethodHandles.Lookup lookup = MethodHandles.publicLookup();
038        for (final Class<? extends Date> dateClass : Arrays.asList(Date.class, java.sql.Date.class, Time.class,
039            Timestamp.class)) {
040            try {
041                CONSTRUCTORS.put(dateClass,
042                    lookup.findConstructor(dateClass, MethodType.methodType(void.class, long.class)));
043            } catch (final NoSuchMethodException | IllegalAccessException ignored) {
044                // these classes all have this exact constructor
045            }
046        }
047    }
048
049    /**
050     * Create a Date-related object from a timestamp in millis.
051     *
052     * @param millis timestamp in millis
053     * @param type   date type to use
054     * @param <D>    date class to use
055     * @return new instance of D or null if there was an error
056     */
057    @SuppressWarnings("unchecked")
058    public static <D extends Date> D fromMillis(final long millis, final Class<D> type) {
059        try {
060            return (D) CONSTRUCTORS.get(type).invoke(millis);
061        } catch (final Throwable ignored) {
062            return null;
063        }
064    }
065
066    private DateTypeConverter() {
067    }
068}