001/*
002 * Copyright (c) 2024 QOS.ch Sarl (Switzerland)
003 * All rights reserved.
004 *
005 * Permission is hereby granted, free  of charge, to any person obtaining
006 * a  copy  of this  software  and  associated  documentation files  (the
007 * "Software"), to  deal in  the Software without  restriction, including
008 * without limitation  the rights to  use, copy, modify,  merge, publish,
009 * distribute,  sublicense, and/or sell  copies of  the Software,  and to
010 * permit persons to whom the Software  is furnished to do so, subject to
011 * the following conditions:
012 *
013 * The  above  copyright  notice  and  this permission  notice  shall  be
014 * included in all copies or substantial portions of the Software.
015 *
016 * THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
017 * EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
018 * MERCHANTABILITY,    FITNESS    FOR    A   PARTICULAR    PURPOSE    AND
019 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
020 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
021 * OF CONTRACT, TORT OR OTHERWISE,  ARISING FROM, OUT OF OR IN CONNECTION
022 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023 *
024 *
025 *
026 */
027
028package ch.qos.logback.tyler.base.util;
029
030import ch.qos.logback.core.joran.util.StringToObjectConverter;
031
032import java.nio.charset.Charset;
033
034public class StringToVariableStament {
035
036    static final String DOLLAR_LEFT_ACCOLADE = "${";
037
038    public static boolean containsVariable(String input) {
039        if(input != null) {
040            return input.contains(DOLLAR_LEFT_ACCOLADE);
041        } else {
042            return false;
043        }
044    }
045
046    public static String convertArg (Class<?> type, String value) {
047        boolean isVar = containsVariable(value);
048
049        if (String.class.isAssignableFrom(type)) {
050            return isVar ? "subst($S)" : "$S";
051        } else if (Integer.TYPE.isAssignableFrom(type)) {
052            return "$N";
053        } else if (Long.TYPE.isAssignableFrom(type)) {
054            return "$N";
055        } else if (Float.TYPE.isAssignableFrom(type)) {
056            return "$N";
057        } else if (Double.TYPE.isAssignableFrom(type)) {
058            return "$N";
059        } else if (Boolean.TYPE.isAssignableFrom(type)) {
060            return "$N";
061        } else if (type.isEnum()) {
062            return "Enum.valueOf("+type.getName()+", $S";
063        } else if (StringToObjectConverter.followsTheValueOfConvention(type)) {
064            return type.getName()+".valueOf($S)";
065        } else if (isOfTypeCharset(type)) {
066            return  "Charset.forName($S)";
067        }
068
069        return null;
070    }
071
072    static private boolean isOfTypeCharset(Class<?> type) {
073        return Charset.class.isAssignableFrom(type);
074    }
075
076}