001/*
002 *    Copyright 2024-2025, Warm-Flow (290631660@qq.com).
003 *
004 *    Licensed under the Apache License, Version 2.0 (the "License");
005 *    you may not use this file except in compliance with the License.
006 *    You may obtain a copy of the License at
007 *
008 *       https://www.apache.org/licenses/LICENSE-2.0
009 *
010 *    Unless required by applicable law or agreed to in writing, software
011 *    distributed under the License is distributed on an "AS IS" BASIS,
012 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *    See the License for the specific language governing permissions and
014 *    limitations under the License.
015 */
016package org.dromara.warm.flow.core.utils;
017
018import org.dromara.warm.flow.core.constant.ExceptionCons;
019import org.dromara.warm.flow.core.exception.FlowException;
020import org.dromara.warm.flow.core.variable.DefaultVariableStrategy;
021import org.dromara.warm.flow.core.variable.VariableStrategy;
022
023import java.util.HashMap;
024import java.util.Map;
025import java.util.concurrent.atomic.AtomicReference;
026
027/**
028 * 变量替换工具类
029 *
030 * @author warm
031 */
032public class VariableUtil {
033
034    private static final Map<String, VariableStrategy> map = new HashMap<>();
035
036    private VariableUtil() {
037
038    }
039
040    static {
041        setExpression(new DefaultVariableStrategy());
042    }
043
044    public static void setExpression(VariableStrategy variableStrategy) {
045        map.put(variableStrategy.getType(), variableStrategy);
046    }
047
048    /**
049     * @param expression 变量表达式,比如“@@default@@|${flag}” ,或者自定义策略
050     * @param variable
051     * @return
052     */
053    public static String eval(String expression, Map<String, Object> variable) {
054        if (StringUtils.isNotEmpty(expression)) {
055            AtomicReference<String> result = new AtomicReference<>();
056            map.forEach((k, v) -> {
057                if (expression.startsWith(k + "|")) {
058                    if (v == null) {
059                        throw new FlowException(ExceptionCons.NULL_EXPRESSION_STRATEGY);
060                    }
061                    result.set(v.eval(expression.replace(k + "|", ""), variable));
062                }
063            });
064
065            if (StringUtils.isNotEmpty(result.get())) {
066                return result.get();
067            }
068        }
069
070        return expression;
071    }
072
073}