All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.script.engine.util.ScriptExpressions Maven / Gradle / Ivy

package org.zodiac.script.engine.util;

import org.apache.commons.beanutils.BeanUtilsBean2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zodiac.commons.util.TemplateResolver;
import org.zodiac.script.engine.DynamicScriptEngine;
import org.zodiac.script.engine.DynamicScriptEngineFactory;
import org.zodiac.sdk.toolkit.crypto.Md5;
import org.zodiac.sdk.toolkit.util.collection.CollUtil;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;

import java.util.Map;
import java.util.regex.Pattern;

public abstract class ScriptExpressions {

    private ScriptExpressions() {
        super();
    }

    private static Logger log = LoggerFactory.getLogger(ScriptExpressions.class);

    /*表达式提取正则 ${.+?} 。*/
    private static final Pattern PATTERN = Pattern.compile("(?<=\\$\\{)(.+?)(?=})");

    /**
     * 

获取默认的表达式变量。

* * @return 变量集合 */ public static Map getDefaultVar() { return CollUtil.map(); } /** *

获取默认的表达式变量并将制定的变量合并在一起。

* * @param var 要合并的变量集合 * @return 变量集合 */ public static Map getDefaultVar(Map var) { Map vars = getDefaultVar(); vars.putAll(var); return vars; } /** *

使用默认的变量解析表达式。

* * @param expression 表达式字符串 * @param language 表达式语言 * @return 解析结果 * @throws Exception 解析错误 * @see ScriptExpressions#analytical(String, Map, String) */ public static String analytical(String expression, String language) throws Exception { return analytical(expression, CollUtil.map(), language); } /** *

解析表达式,表达式使用{@link ScriptExpressions#PATTERN}进行提取。


*

如调用 analytical("http://${3+2}/test",var,"spel")。


*

支持的表达式语言:

*
*
    *
  • freemarker
  • *
  • spel
  • *
  • ognl
  • *
  • groovy
  • *
  • js
  • *
*
* * @param expression 表达式字符串 * @param vars 变量 * @param language 表达式语言 * @return 解析结果 */ public static String analytical(String expression, Map vars, String language) { if (!expression.contains("${")) { return expression; } DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(language); if (engine == null) { return expression; } return TemplateResolver.parse(expression, var -> { if (StrUtil.isEmpty(var)) { return ""; } Object val = vars.get(var); if (val != null) { return String.valueOf(val); } if ("spel".equalsIgnoreCase(language) && !var.contains("#")) { try { Object fast = BeanUtilsBean2.getInstance().getPropertyUtils().getProperty(vars, var); if (fast != null) { return fast.toString(); } } catch (Exception ignore) { /*Ignore.*/ return ""; } } String id = Md5.md5Hex(var); try { if (!engine.compiled(id)) { engine.compile(id, var); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } try { return String.valueOf(engine.execute(id, vars).getIfSuccess()); } catch (Exception e) { log.error(e.getMessage(), e); return ""; } }); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy