使用JSR223集成jython到Java中
一个小示例
需要 jython-engine.jar jython.jar
java 文件
package
test.jsr223;
import java.io. * ;
import java.util. * ;
import javax.script. * ;
public class jsr223 {
private ScriptEngine engine;
static private Map < String, ScriptEngineFactory > scriptMap = null ;
static private void createMaps() {
if (scriptMap == null ) {
scriptMap = new HashMap < String, ScriptEngineFactory > ();
ScriptEngineManager manager = new ScriptEngineManager();
List < ScriptEngineFactory > list = manager.getEngineFactories();
for (ScriptEngineFactory scriptEngineFactory : list) {
scriptMap.put(scriptEngineFactory.getEngineName(),
scriptEngineFactory);
scriptMap.put(scriptEngineFactory.getLanguageName(),
scriptEngineFactory);
List < String > mimeList = scriptEngineFactory.getMimeTypes();
for (String string2 : mimeList) {
scriptMap.put(string2, scriptEngineFactory);
}
}
}
}
static public ScriptEngine initEngineByScript(Scanner reader) {
createMaps();
ScriptEngine engine = null ;
String firstLine = reader.nextLine();
if (firstLine != null ) {
Set < String > keys = scriptMap.keySet();
for (String string : keys) {
if (firstLine.indexOf(string) != - 1 ) {
engine = scriptMap.get(string).getScriptEngine();
break ;
}
}
}
return engine;
}
static public ScriptEngine initEngineByFileName(String scriptFileName) {
ScriptEngine engine = null ;
int index = scriptFileName.lastIndexOf( ' . ' );
if (index != - 1 ) {
String ext = scriptFileName.substring(index + 1 , scriptFileName
.length());
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByExtension(ext);
}
return engine;
}
static public ScriptEngine initEngine(String scriptFileName) {
ScriptEngine engine = null ;
Scanner scanner = null ;
try {
scanner = new Scanner( new InputStreamReader( new FileInputStream(
scriptFileName)));
engine = initEngineByScript(scanner);
if (engine == null )
engine = initEngineByFileName(scriptFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null )
scanner.close();
}
return engine;
}
private void init(String scriptFileName) {
engine = initEngine(scriptFileName);
Reader reader = null ;
try {
reader = new InputStreamReader( new FileInputStream(scriptFileName));
engine.eval(reader);
} catch (FileNotFoundException e) {
System.err.printf( " Script file %s can't find!\n " , scriptFileName);
e.printStackTrace();
System.exit( - 1 );
} catch (ScriptException e) {
System.err.printf( " Run script file %s error!\n " , scriptFileName);
e.printStackTrace();
} finally {
if (reader != null )
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public jsr223(File scriptFile) {
String name = scriptFile.getName();
init(name);
}
public jsr223(String scriptFileName) {
init(scriptFileName);
}
static public void ShowAllAvilableScript() {
ScriptEngineManager manager = new ScriptEngineManager();
List < ScriptEngineFactory > list = manager.getEngineFactories();
for (ScriptEngineFactory scriptEngineFactory : list) {
System.out.printf(
" EngineName:%s LanguageName:%s Extensions:%s Mime:%s\n " ,
scriptEngineFactory.getEngineName(), scriptEngineFactory
.getLanguageName(), scriptEngineFactory
.getExtensions(), scriptEngineFactory
.getMimeTypes());
}
}
public void callStart() throws ScriptException, NoSuchMethodException {
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction( " Start " , " hello world 世界你好\n " );
}
public void callStop() throws ScriptException, NoSuchMethodException {
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction( " Stop " , " GoodBye 再见\n " );
}
/**
* @param args
* @throws ScriptException
* @throws NoSuchMethodException
*/
public static void main(String[] args) throws ScriptException,
NoSuchMethodException {
// TODO Auto-generated method stub
// ShowAllAvilableScript();
String scriptFileName = " E:\\workspace\\JSR223\\src\\test\\jsr223\\test.py " ;
jsr223 jsr = new jsr223(scriptFileName);
jsr.callStart();
jsr.callStop();
}
}
jython 文件
import java.io. * ;
import java.util. * ;
import javax.script. * ;
public class jsr223 {
private ScriptEngine engine;
static private Map < String, ScriptEngineFactory > scriptMap = null ;
static private void createMaps() {
if (scriptMap == null ) {
scriptMap = new HashMap < String, ScriptEngineFactory > ();
ScriptEngineManager manager = new ScriptEngineManager();
List < ScriptEngineFactory > list = manager.getEngineFactories();
for (ScriptEngineFactory scriptEngineFactory : list) {
scriptMap.put(scriptEngineFactory.getEngineName(),
scriptEngineFactory);
scriptMap.put(scriptEngineFactory.getLanguageName(),
scriptEngineFactory);
List < String > mimeList = scriptEngineFactory.getMimeTypes();
for (String string2 : mimeList) {
scriptMap.put(string2, scriptEngineFactory);
}
}
}
}
static public ScriptEngine initEngineByScript(Scanner reader) {
createMaps();
ScriptEngine engine = null ;
String firstLine = reader.nextLine();
if (firstLine != null ) {
Set < String > keys = scriptMap.keySet();
for (String string : keys) {
if (firstLine.indexOf(string) != - 1 ) {
engine = scriptMap.get(string).getScriptEngine();
break ;
}
}
}
return engine;
}
static public ScriptEngine initEngineByFileName(String scriptFileName) {
ScriptEngine engine = null ;
int index = scriptFileName.lastIndexOf( ' . ' );
if (index != - 1 ) {
String ext = scriptFileName.substring(index + 1 , scriptFileName
.length());
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByExtension(ext);
}
return engine;
}
static public ScriptEngine initEngine(String scriptFileName) {
ScriptEngine engine = null ;
Scanner scanner = null ;
try {
scanner = new Scanner( new InputStreamReader( new FileInputStream(
scriptFileName)));
engine = initEngineByScript(scanner);
if (engine == null )
engine = initEngineByFileName(scriptFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null )
scanner.close();
}
return engine;
}
private void init(String scriptFileName) {
engine = initEngine(scriptFileName);
Reader reader = null ;
try {
reader = new InputStreamReader( new FileInputStream(scriptFileName));
engine.eval(reader);
} catch (FileNotFoundException e) {
System.err.printf( " Script file %s can't find!\n " , scriptFileName);
e.printStackTrace();
System.exit( - 1 );
} catch (ScriptException e) {
System.err.printf( " Run script file %s error!\n " , scriptFileName);
e.printStackTrace();
} finally {
if (reader != null )
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public jsr223(File scriptFile) {
String name = scriptFile.getName();
init(name);
}
public jsr223(String scriptFileName) {
init(scriptFileName);
}
static public void ShowAllAvilableScript() {
ScriptEngineManager manager = new ScriptEngineManager();
List < ScriptEngineFactory > list = manager.getEngineFactories();
for (ScriptEngineFactory scriptEngineFactory : list) {
System.out.printf(
" EngineName:%s LanguageName:%s Extensions:%s Mime:%s\n " ,
scriptEngineFactory.getEngineName(), scriptEngineFactory
.getLanguageName(), scriptEngineFactory
.getExtensions(), scriptEngineFactory
.getMimeTypes());
}
}
public void callStart() throws ScriptException, NoSuchMethodException {
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction( " Start " , " hello world 世界你好\n " );
}
public void callStop() throws ScriptException, NoSuchMethodException {
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction( " Stop " , " GoodBye 再见\n " );
}
/**
* @param args
* @throws ScriptException
* @throws NoSuchMethodException
*/
public static void main(String[] args) throws ScriptException,
NoSuchMethodException {
// TODO Auto-generated method stub
// ShowAllAvilableScript();
String scriptFileName = " E:\\workspace\\JSR223\\src\\test\\jsr223\\test.py " ;
jsr223 jsr = new jsr223(scriptFileName);
jsr.callStart();
jsr.callStop();
}
}
jython的本地化太....了。在py中用ToJavaString,ToPyString函数
#
/usr/bin/env python
# coding=gbk
import sys
def GetLocalEncoding():
''' Get local system encoding
return None when fail.
'''
import java.lang.System as JSystem
propertys = [ " sun.jnu.encoding " , " file.encoding " ]
Encoding = None;
for property in propertys:
Encoding = JSystem.getProperty(property)
if Encoding != None:
break
return Encoding
def ToJavaString( astr,localEncoding = GetLocalEncoding()):
import java.lang.String as JString
if localEncoding == None:
raise EnvironmentError( " Can't get local encoding!\n " )
tmpstr = JString(astr)
rtnstr = JString (tmpstr.getBytes( " ISO8859_1 " ), localEncoding)
if tmpstr.length() != rtnstr.length():
return rtnstr
else :
return astr
def ToPyString(astr):
import java.lang.String as JString
import org.python.core.PyString as PyString
tmpstr = JString(astr)
rtnstr = JString(tmpstr.getBytes(), " ISO8859_1 " )
return PyString(rtnstr)
def Start( * args):
print sys.path
for i in args:
t = ToPyString(i)
print t
def Stop( * args):
for i in args:
t = ToPyString(i)
print t
if __name__ == ' __main__ ' :
print ' hello '
# coding=gbk
import sys
def GetLocalEncoding():
''' Get local system encoding
return None when fail.
'''
import java.lang.System as JSystem
propertys = [ " sun.jnu.encoding " , " file.encoding " ]
Encoding = None;
for property in propertys:
Encoding = JSystem.getProperty(property)
if Encoding != None:
break
return Encoding
def ToJavaString( astr,localEncoding = GetLocalEncoding()):
import java.lang.String as JString
if localEncoding == None:
raise EnvironmentError( " Can't get local encoding!\n " )
tmpstr = JString(astr)
rtnstr = JString (tmpstr.getBytes( " ISO8859_1 " ), localEncoding)
if tmpstr.length() != rtnstr.length():
return rtnstr
else :
return astr
def ToPyString(astr):
import java.lang.String as JString
import org.python.core.PyString as PyString
tmpstr = JString(astr)
rtnstr = JString(tmpstr.getBytes(), " ISO8859_1 " )
return PyString(rtnstr)
def Start( * args):
print sys.path
for i in args:
t = ToPyString(i)
print t
def Stop( * args):
for i in args:
t = ToPyString(i)
print t
if __name__ == ' __main__ ' :
print ' hello '