001package ball.util;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: Converter.java 5285 2020-02-05 04:23:21Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-util/trunk/src/main/java/ball/util/Converter.java $
007 * %%
008 * Copyright (C) 2008 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import ball.lang.PrimitiveTypeMap;
024import java.util.TreeMap;
025
026import static java.util.Comparator.comparing;
027
028/**
029 * Conversion utility based on {@link Factory}.
030 *
031 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
032 * @version $Revision: 5285 $
033 */
034public class Converter extends TreeMap<Class<?>,Factory<?>> {
035    private static final long serialVersionUID = -3178874315076658917L;
036
037    private static final Converter INSTANCE = new Converter();
038
039    private Converter() {
040        super(comparing(Class::getName));
041
042        put(String.class, new Factory<>(String.class));
043
044        PrimitiveTypeMap.INSTANCE.values()
045            .stream()
046            .forEach(t -> put(t, new Factory<>(t)));
047        PrimitiveTypeMap.INSTANCE.keySet()
048            .stream()
049            .forEach(t -> put(t, get(PrimitiveTypeMap.INSTANCE.get(t))));
050    }
051
052    /**
053     * Static method to convert the argument to the specified type
054     * ({@link Class}).
055     *
056     * @param   from            The source value.
057     * @param   type            The target type ({@link Class}).
058     *
059     * @return  The converted value.
060     */
061    public static Object convertTo(Object from, Class<?> type) {
062        Object to = null;
063
064        try {
065            if (from == null || type.isAssignableFrom(from.getClass())) {
066                to = from;
067            } else {
068                to =
069                    INSTANCE.
070                    computeIfAbsent(type,
071                                    k -> (INSTANCE.values()
072                                          .stream()
073                                          .filter(t -> k.isAssignableFrom(t.getType()))
074                                          .findFirst()
075                                          .orElse(new Factory<>(k))))
076                    .getInstance(from);
077            }
078        } catch (RuntimeException exception) {
079            throw exception;
080        } catch (Exception exception) {
081            throw new IllegalArgumentException(exception);
082        }
083
084        return to;
085    }
086}