package com.test.utils;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.test.ConfigBean;
import com.test.spring.SpringBeanFactory;
public class PyUtils
{
private static Logger logger = LoggerFactory.getLogger(PyUtils.class);
private static ConfigBean configBean = SpringBeanFactory.getBean("configBean");
private PythonInterpreter interpreter;
private PyFunction encryptFun;
private PyFunction decryptFun;
private static PyUtils self;
public String decrypt(String key, String data)
{
PyObject decryptFunctionResult = self.decryptFun.__call__(Py.newString(key), Py.newString(data));
return decryptFunctionResult.toString();
}
public String encrypt(String key, String data)
{
PyObject result = self.encryptFun.__call__(Py.newString(key), Py.newString(data));
return result.toString();
}
public static PyUtils getInstance()
{
if (self == null)
{
self = new PyUtils(configBean.getPythonDirectory());//此处是py脚本文件所在的目录
}
return self;
}
private PyUtils(String path)
{
if (StringUtils.endsWithIgnoreCase("develop", configBean.getEnv()))
{
}
else if (StringUtils.endsWithIgnoreCase("product", configBean.getEnv()))
{
Properties properties = new Properties();
properties.put("python.home", configBean.getJythonHome());//此处是jython安装后所在的目录,里面是有Lib目录等结构的
properties.put("python.console.encoding", "UTF-8");
properties.put("python.security.respectJavaAccessibility", "false");
properties.put("python.import.site", "false");
Properties systemProperties = System.getProperties();
PythonInterpreter.initialize(systemProperties, properties, new String[0]);
}
interpreter = new PythonInterpreter();
PySystemState pySystemState = Py.getSystemState();
pySystemState.path.add(path);
interpreter.exec("import sys");
interpreter.exec("print sys.path");
logger.info("Python path={}", pySystemState.path.toString());
interpreter.execfile("1.py");
interpreter.execfile("2.py");
interpreter.execfile("3.py");
interpreter.execfile("4.py");
interpreter.execfile("5.py");
interpreter.execfile("6.py");
encryptFun = interpreter.get("encrypt", PyFunction.class);
decryptFun = interpreter.get("decrypt", PyFunction.class);
}
public void close()
{
interpreter.cleanup();
interpreter.close();
}
}