001
014
015 package com.liferay.portal.scripting.python;
016
017 import com.liferay.portal.kernel.cache.SingleVMPoolUtil;
018 import com.liferay.portal.kernel.scripting.ExecutionException;
019 import com.liferay.portal.kernel.scripting.ScriptingException;
020 import com.liferay.portal.kernel.scripting.ScriptingExecutor;
021
022 import java.util.HashMap;
023 import java.util.Map;
024 import java.util.Set;
025
026 import org.python.core.CompileMode;
027 import org.python.core.Py;
028 import org.python.core.PyCode;
029 import org.python.core.PySystemState;
030 import org.python.util.InteractiveInterpreter;
031
032
035 public class PythonExecutor implements ScriptingExecutor {
036
037 public static final String CACHE_NAME = PythonExecutor.class.getName();
038
039 public static final String LANGUAGE = "python";
040
041 public void clearCache() {
042 SingleVMPoolUtil.clear(CACHE_NAME);
043 }
044
045 public String getLanguage() {
046 return LANGUAGE;
047 }
048
049 public Map<String, Object> eval(
050 Set<String> allowedClasses, Map<String, Object> inputObjects,
051 Set<String> outputNames, String script)
052 throws ScriptingException {
053
054 if (allowedClasses != null) {
055 throw new ExecutionException(
056 "Constrained execution not supported for Python");
057 }
058
059 PyCode compiledScript = getCompiledScript(script);
060
061 InteractiveInterpreter interactiveInterpreter =
062 new InteractiveInterpreter();
063
064 for (String varName: inputObjects.keySet()) {
065 interactiveInterpreter.set(varName, inputObjects.get(varName));
066 }
067
068 interactiveInterpreter.exec(compiledScript);
069
070 if (outputNames == null) {
071 return null;
072 }
073
074 Map<String, Object> outputObjects = new HashMap<String, Object>();
075
076 for (String outputName : outputNames) {
077 outputObjects.put(
078 outputName, interactiveInterpreter.get(outputName));
079 }
080
081 return outputObjects;
082 }
083
084 protected PyCode getCompiledScript(String script) {
085 if (!_initialized) {
086 synchronized (this) {
087 PySystemState.initialize();
088
089 _initialized = true;
090 }
091 }
092
093 String key = String.valueOf(script.hashCode());
094
095 PyCode compiledScript = (PyCode)SingleVMPoolUtil.get(CACHE_NAME, key);
096
097 if (compiledScript == null) {
098 compiledScript = Py.compile_flags(
099 script, "<string>", CompileMode.exec, Py.getCompilerFlags());
100
101 SingleVMPoolUtil.put(CACHE_NAME, key, compiledScript);
102 }
103
104 return compiledScript;
105 }
106
107 private boolean _initialized;
108
109 }