org.zodiac.script.engine.ognl.OgnlEngine Maven / Gradle / Ivy
package org.zodiac.script.engine.ognl;
import ognl.Ognl;
import org.zodiac.script.engine.ExecuteResult;
import org.zodiac.script.engine.ListenerSupportEngine;
import org.zodiac.script.engine.ScriptContext;
import org.zodiac.script.engine.costants.ScriptEngineConstants;
import org.zodiac.sdk.toolkit.crypto.Md5;
import org.zodiac.sdk.toolkit.util.SystemClock;
import org.zodiac.sdk.toolkit.util.collection.CollUtil;
import java.util.Map;
public class OgnlEngine extends ListenerSupportEngine {
protected final Map cache;
public OgnlEngine() {
cache = CollUtil.concurrentMap();
}
@Override
public boolean compiled(String id) {
return cache.containsKey(id);
}
@Override
public ScriptContext getContext(String id) {
return cache.get(id);
}
@Override
public boolean remove(String id) {
return cache.remove(id) != null;
}
@Override
public void init(String... contents) throws Exception {}
@Override
public String getScriptEngineName() {
return ScriptEngineConstants.OGNL_ENGINE_NAME;
}
@Override
public ExecuteResult execute(String id) {
return execute(id, CollUtil.map());
}
@Override
public boolean compile(String id, String code) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Compile OGNL {} : {}", id, code);
}
cache.put(id, new OgnlScriptContext(id, Md5.md5Hex(code), Ognl.parseExpression(code)));
return false;
}
@Override
public ExecuteResult execute(String id, Map param) {
if (logger.isDebugEnabled()) {
logger.debug("Execute OGNL {} : {}", id, param);
}
ExecuteResult result = new ExecuteResult();
long start = SystemClock.nowTimeMillis();
OgnlScriptContext scriptContext = cache.get(id);
try {
if (scriptContext != null) {
doListenerBefore(scriptContext);
scriptContext = cache.get(id);
param = CollUtil.map(param);
param.putAll(getGlobalVariable());
Object obj = Ognl.getValue(scriptContext.getScript(), param, param);
result.setSuccess(true).setResult(obj);
} else {
result.setSuccess(false).setMessage(String.format("OGNL: %s not found!", id));
}
long end = SystemClock.nowTimeMillis();
result.setUseTime(end - start);
} catch (Exception e) {
logger.error("Execute OGNL error", e);
result.setException(e);
}
doListenerAfter(scriptContext, result);
return result;
}
class OgnlScriptContext extends ScriptContext {
private Object script;
public OgnlScriptContext(String id, String md5, Object script) {
super(id, md5);
this.script = script;
}
public Object getScript() {
return script;
}
}
}