`
收藏列表
标题 标签 来源
Cglib代理TestCglibProxy
public class TestCglibProxy {
	 public static void main(String args[]){
        CglibProxy proxy = new CglibProxy();
        //动态生成子类的方法创建代理类
        ForumServiceImpl fsi = (ForumServiceImpl)proxy.getProxy(ForumServiceImpl.class);
        fsi.removeForum(10);
        fsi.removeTopic(2);
    }
}
Cglib代理CglibProxy
public class CglibProxy implements MethodInterceptor {

	private Enhancer enhancer = new Enhancer();
	 
    //覆盖MethodInterceptor接口的getProxy()方法,设置
    public Object getProxy(Class clazz){
        enhancer.setSuperclass(clazz); //设置要创建子类的类
        enhancer.setCallback(this); //设置回调的对象
        return enhancer.create(); //通过字节码技术动态创建子类实例,
    }
    
    public Object intercept(Object obj,Method method,Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("模拟代理增强方法");
        //通过代理类实例调用父类的方法,即是目标业务类方法的调用
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("模拟代理增强方法结束");
        return result;
    }

}
JDK代理ForumServiceImpl
public interface IForumService {
	public void removeTopic(int topicId);
	public void removeForum(int forumId);
}

public class ForumServiceImpl implements IForumService {
	public void removeTopic(int topicId){
        System.out.println("模拟删除记录"+topicId);
        try{
            Thread.currentThread().sleep(20);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
	
    public void removeForum(int forumId){
        System.out.println("模拟删除记录"+forumId);
        try{
            Thread.currentThread().sleep(20);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
}
JDK代理InvocationHandler
public class PerformanceHandler implements InvocationHandler {

	private Object target; //要进行代理的业务类的实例
	
    public PerformanceHandler(Object target){
        this.target = target;
    }
    
    //覆盖java.lang.reflect.InvocationHandler的方法invoke()进行织入(增强)的操作
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable{
        System.out.println("Object target proxy:"+target);
        System.out.println("模拟代理加强的方法...");
        Object obj = method.invoke(target, args); //调用目标业务类的方法
        System.out.println("模拟代理加强的方法执行完毕...");
        return obj;
    }

}
JDK代理TestForumService
public class TestForumService {
	 public static void main(String args[]){
		//要进行代理的目标业务类
        IForumService target = new ForumServiceImpl();
        
        //用代理类把目标业务类进行编织
        PerformanceHandler handler = new PerformanceHandler(target);
 
        //创建代理实例,它可以看作是要代理的目标业务类的加多了横切代码(方法)的一个子类
        IForumService proxy = (IForumService)Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), handler);
        proxy.removeForum(10);
        proxy.removeTopic(20);
    }
}
JdbcTemplateDaoTestCase
public class JdbcTemplateDaoTestCase extends BaseDBTestCase {
	private IJdbcDao jdbcTemplateDao = BeanHelper.getBean("jdbcTemplateDao", IJdbcDao.class);

	public JdbcTemplateDaoTestCase(String name) {
		super(name);
	}

	@Override
	protected IDataSet getDataSet() throws Exception {
		return DataSetUtil.getDataSetFromFile("com/hwls/framework/dao/jdbc/prepare_data.xml");
	}
	public void testInsert() throws Exception{
		Object [] paramObjects = new Object[]{ 0003,"王五","王五",30,"memo3",333.33,DateUtil.toDate("2002-03-03")};
		int result = jdbcTemplateDao.execute("insert into test_user_info(user_id,login_name,full_name,age,memo,money,birthday) values(?,?,?,?,?,?,?) ",paramObjects);
		this.assertEquals(1, result);
		
		//预期结果取得
		IDataSet expectedDataSet = DataSetUtil.getDataSetFromFile("com/hwls/framework/dao/jdbc/insert_except_data.xml");
		ITable expectedTable = expectedDataSet.getTable("test_user_info");
	
		//实际结果取得
		//预想结果和实际结果的比较
		IDataSet databaseDataSet = getConnection().createDataSet();
		ITable actualTable = databaseDataSet.getTable("test_user_info");
		
		 SortedTable sortedTable1 = new SortedTable(expectedTable, new String[]{"USER_ID"});
         sortedTable1.setUseComparable(true); // must be invoked immediately after the constructor
         SortedTable sortedTable2 = new SortedTable(actualTable, new String[]{"USER_ID"});
         sortedTable2.setUseComparable(true); // must be invoked immediately after the constructor
         Assertion.assertEquals(sortedTable1, sortedTable2);
	}

}
BaseDBTestCase
public abstract class BaseDBTestCase extends DBTestCase {

	public BaseDBTestCase(String name){
		super(name);
		System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "oracle.jdbc.OracleDriver" );
        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:oracle:thin:@10.132.30.32:1521:crm2dev1" );
        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "bsp" );
        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "HWLS01" );
        System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, "bsp" );
	}
	
	protected DatabaseOperation getSetUpOperation() throws Exception{
		System.out.println("------------------------getSetUpOperation...");
		return DatabaseOperation.CLEAN_INSERT;
    }

//    protected DatabaseOperation getTearDownOperation() throws Exception{
//    	System.out.println("------------------------getTearDownOperation...");
//    	 return DatabaseOperation.DELETE_ALL;
//    }
	
    @Override
	protected void setUp() throws Exception {
    	super.setUp();
    	System.out.println("------------------------setUp...");
	}

    protected void tearDown() throws Exception {
    	super.tearDown();
    	System.out.println("------------------------tearDown...");
	}
	
	/**
	 * 给定数据集
	 */
	abstract protected IDataSet getDataSet() throws Exception;

}
database_compilation.javascript
/*****
 ** 
 **database manipulation
 **
 *****/
var dao = {};
dao.select=function(databaseName,sql,args,iStart,iEnd){ 
	if(!args)
		args=[];
	if(!iStart)
		iStart=1;
	if(!iEnd)
		iEnd=100;
	if(typeof(args)=='object'&&!(args instanceof Date)&&!(args instanceof Array)){
		sql=_LIGHT.filterSql(sql,args);
		return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "selectByObject",_LIGHT.stringifyJson([databaseName,sql,args,iStart,iEnd])))[0];
	}else if(!args||args instanceof Array){
		return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "select",_LIGHT.stringifyJson([databaseName,sql,args,iStart,iEnd])))[0];
	}else{
		log.error("Wrong parameters, select(sql,Array/Object,Rownum), Please Check databaseName:"+databaseName+",sql:"+sql+",args:"+args+",rows:"+iStart+"/"+iEnd);
		return [];
	}
};

dao.execute=function(databaseName,sql,args){ 
	if(!args)
		args=[];
	if(typeof(args)=='object'&&!(args instanceof Date)&&!(args instanceof Array)){
		sql=_LIGHT.filterSql(sql,args);
		return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "executeUpdateByObject",_LIGHT.stringifyJson([databaseName,sql,args])))[0];
	}else if(!args||args instanceof Array){
		return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "executeUpdate",_LIGHT.stringifyJson([databaseName,sql,args])))[0];
	}else{
		log.error("Wrong parameters, execute(sql,Array/Object,Rownum), Please Check databaseName:"+databaseName+",sql:"+sql+",args:"+args);
		return [];
	}
}; 

dao.insert=function(databaseName,tableName,valueObject){
	//check parameters
	if(arguments.length!=3||typeof(valueObject)!='object'||typeof(tableName)!='string')
	{
		log.error("Wrong Parameters, please check:databaseName:"+databaseName+",tableName:"+tableName+",valueObject:"+valueObject);
		return ;
	}

	if(valueObject instanceof Array){
		return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
					"light.core.database.LightDataBaseAccessForScript", "insertList",_LIGHT.stringifyJson([].slice.apply(arguments))))[0];
	}else{
		return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
					"light.core.database.LightDataBaseAccessForScript", "insert",_LIGHT.stringifyJson([].slice.apply(arguments))))[0];
	}
	
}

dao.remove=function(databaseName,tableName,valueObject){
	//check parameters
	if(arguments.length!=3||typeof(valueObject)!='object'||typeof(tableName)!='string')
	{
		log.error("Wrong Parameters, please check:databaseName:"+databaseName+",tableName:"+tableName+",valueObject:"+valueObject);
		return ;
	}
	return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "delete",_LIGHT.stringifyJson([].slice.apply(arguments))))[0];
}

dao.update=function(databaseName,tableName,valueObject,conditionObject){ 
	if(arguments.length!=4||typeof(valueObject)!='object'||typeof(conditionObject)!='object'||typeof(tableName)!='string')
	{
		log.error("Wrong Parameters, please check:databaseName:"+databaseName+",tableName:"+tableName+",valueObject:"+valueObject+",conditionObject:"+conditionObject);
		return ;
	}
	return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "update",_LIGHT.stringifyJson([].slice.apply(arguments))))[0];
}

dao.sequence=function(databaseName,sequenceName){
	return _LIGHT.parseJson(Packages.light.core.service.LightService.runJavaService(
				"light.core.database.LightDataBaseAccessForScript", "sequence",_LIGHT.stringifyJson([].slice.apply(arguments))))[0];
}
server_compilation.javascript
var log={};
log._getString=function(msg){try{if(typeof(msg)=='string')return msg;return JSON.stringify(msg);}catch(e){return msg+"";}};
log.debug=function(msg){_log.debug(log._getString(msg))};
log.info=function(msg){_log.info(log._getString(msg))};
log.warn=function(msg){_log.warn(log._getString(msg))};
log.error=function(msg){log._getString(msg)};
log.fatal=function(msg){log._getString(msg)};

var _SCRIPT_ENGINE = {};

_SCRIPT_ENGINE.registerScript = function(fullnamespace,myObj)
{
    var nsArray = fullnamespace.split('.');
    var sEval = "";
    var sNS = "";
    for (var i = 0; i < nsArray.length; i++)
    {
        if (i != 0) sNS += ".";
        sNS += nsArray[i];
        sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();"
    }
    if (sEval != "") eval(sEval);
	eval(fullnamespace+'=myObj');
};

_SCRIPT_ENGINE.parseJson = function(jsonString){
	var jsonObj={};
	try{
		jsonObj= JSON.parse(jsonString);
	}catch(e){
		log.debug('a little glitch occurred in parseJson('+jsonString+'):'+e.message);
		jsonObj= jsonString;
	};
	//log.debug("parseJson:"+jsonString+">("+typeof(jsonObj)+")"+jsonObj);
	return jsonObj;
};


_SCRIPT_ENGINE.stringifyJson = function(jsonObj){
	var jsonString="";
	try{
		if(typeof(jsonObj)=='string'){
			jsonString= jsonObj;
		}else{
			jsonString=JSON.stringify(jsonObj);
		}
	}catch(e){
		log.debug('a little glitch occurred in stringifyJson:'+e.message);
		jsonString= jsonObj+"";
	}
	//log.debug("stringify:("+typeof(jsonObj)+")"+jsonObj+">"+jsonString);
	return jsonString;
};


_SCRIPT_ENGINE.executeFunction=function(funName, funArgString){
	var funArg=[];
	if(!funName)
		return null;
	funName=eval(funName); 
	if(funArgString)
		funArg=eval(funArgString);
	var funResult=funName.apply(this,funArg);
	if(!funResult)
		return null;
	return JSON.stringify(funResult);
};

callJavaService = function(javaClassFullName, methodName,params){
	if(typeof(javaClassFullName)!='string'||
		typeof(methodName)!='string'){
			log.warn("class name and method name must be string:"+javaClassFullName+"["+methodName+"]");
			return null;
		}
	var paraJsonArray = [];
	for(var i = 2;i < arguments.length;i ++){
		paraJsonArray.push(arguments[i]);
	}
	
	return JSON.parse(Packages.com.hwls.component.script.engine.ServiceCaller.runJavaService(javaClassFullName, methodName,JSON.stringify(paraJsonArray)));
};
ScriptLog
	protected Logger log = LoggerFactory.getLogger(ScriptEngine.class);

	public void debug(String message) {
		log.debug(message);
	}

	public void debug(String message, Throwable t) {
		log.debug(message, t);
	}

	public void error(String message) {
		log.error(message);
	}

	public void error(String message, Throwable t) {
		log.error(message, t);
	}

	public void info(String message) {
		log.info(message);
	}

	public void info(String message, Throwable t) {
		log.info(message, t);
	}

	public boolean isDebugEnabled() {
		return log.isDebugEnabled();
	}

	public boolean isErrorEnabled() {
		return log.isErrorEnabled();
	}

	public boolean isInfoEnabled() {
		return log.isInfoEnabled();
	}

	public boolean isTraceEnabled() {
		return log.isTraceEnabled();
	}

	public boolean isWarnEnabled() {
		return log.isWarnEnabled();
	}

	public void trace(String message) {
		log.trace(message);
	}

	public void trace(String message, Throwable t) {
		log.trace(message, t);
	}

	public void warn(String message) {
		log.warn(message);
	}

	public void warn(String message, Throwable t) {
		log.warn(message, t);
	}
ScriptCompiler
public static Script compile(Script script) throws ScriptCompileException {
		StringBuilder compiledScriptBuilder = new StringBuilder();
		compiledScriptBuilder.append("_SCRIPT_ENGINE.registerScript('").append(script.getScriptId()).append("',(function(){\n")
	        	.append("_SCRIPT_ENGINE_CUR_PATH='").append(script.getScriptId()).append("';\n")
	        	.append("javaScriptId='").append(script.getScriptId()).append("';\n")
	        	.append(script.getOriginalScript()).append(";\n")
				.append("return {");
		
		List<String> objectNameList = getObjectFromScript(script.getOriginalScript());
		for(int i = 0 ;i < objectNameList.size();i ++){
			if(i > 0){
				compiledScriptBuilder.append(",");
			}
			compiledScriptBuilder.append(objectNameList.get(i) + ":" + objectNameList.get(i)).append("\n");
		}
		
		compiledScriptBuilder.append("};\n");
		
		compiledScriptBuilder.append("})());");
		
		script.setCompiledScript(compiledScriptBuilder.toString());
		
		Scriptable scope = ScriptObjectManager.addScriptObject(script.getScriptId(), script.getCompiledScript());
		
		script.setScope(scope);
		
		return script;
	}
	
	private static List<String> getObjectFromScript(String script){
		List<String> objectNameList = new ArrayList<String>();
		Context cx = Context.enter();
		Scriptable scope = cx.initStandardObjects();
		cx.evaluateString(scope, script,"", 0, null);
		Object [] ids = scope.getIds();
		for(Object item : ids){
			objectNameList.add(String.valueOf(item));
		}
		
		return objectNameList;
	}
ScriptExecutor
	public static Object runScript(String script,String functionName,Object[] paramObjects){
		 Context cx = Context.enter();
		 Object result = null;
	     try {
		        Scriptable scope = cx.initStandardObjects();
				cx.evaluateString(scope, script,"MySource", 1, null);
				
				//获取方法
				Object object = scope.get(functionName, scope);
			    if (object == Scriptable.NOT_FOUND) {
	                System.out.println(functionName + "a is not defined.");
	            } else {
	                System.out.println(functionName + " = " + Context.toString(object));
	            }
				if (!(object instanceof Function)) {
				    System.out.println("f is undefined or not a function.");
				} else {
				    Function f = (Function)object;
				    result = f.call(cx, scope, scope, paramObjects);
				    System.out.println("result:" + result);
				}
	     } finally {
	            Context.exit();
	     }
	     
	     return result;
	}
ScriptFileReader
public static String loadScript(String scriptId) throws IOException {
			String path = scriptId.replaceAll("\\.", "/");
			path = path + ".javascript";
			String script = FileUtil.getResourceAsString(path);
			return script;
	}
ScriptUtil
public static Object findObject(Scriptable scope,String path){
		Object object = null;
		String [] paths = path.split("\\.");
		for(String item : paths){
			object = scope.get(item, scope);
			if (object != Scriptable.NOT_FOUND) {
            	scope = (Scriptable)object;
            }
		}
		
		return object;
	}
	
	public static String toString(Scriptable scope){
		 Context cx = Context.enter();
		 StringBuilder result = new StringBuilder();
		 Object [] ids = scope.getIds();
	     try {
				//获取方法
	    	 	for(Object id : ids){
	    	 		System.out.println(id.toString());
	    	 		Object object = scope.get(id.toString(), scope);
	    	 		if(object instanceof Scriptable){
	    	 			result.append(toString((Scriptable)object));
	    			}
	    	 		else{
	    	 			result.append(Context.toString(object));
	    	 		}
	    	 	}
	     } finally {
	            Context.exit();
	     }
	     
	     return result.toString();
	}
ScriptFactory
public static Script createScript(String scriptId) throws IOException, ScriptCompileException{
		return createScript(scriptId,null);
	}
	
	public static Script createScript(String scriptId,Class scriptClass) throws IOException, ScriptCompileException{
		Script javaScript = null;
		String script = ScriptFileReader.loadScript(scriptId);
		if(scriptClass != null){
			Object object = ClassUtil.getInstance(scriptClass);
			if(object != null){
				javaScript = (Script)object;
			}
		}
		else{
			javaScript = new Script();
		}
		
		javaScript.setScriptId(scriptId);
		javaScript.setOriginalScript(script);
		
		return javaScript;
	}
ScriptEngine
protected static Logger log = LoggerFactory.getLogger(ScriptEngine.class);
	
	public static Script getScriptById(String scriptId) throws Exception{
		Script script = ScriptFactory.createScript(scriptId);
		return script;
	}
	
	public static Object runScriptById(String scriptId,String functionName,String paramJsonString) throws Exception{
		List list = DataCarrierUtil.getListFromJsonString(paramJsonString);
		Object [] paramObjects = list.toArray();
		Object result = runScriptById(scriptId, functionName, paramObjects);
		return result;
	}
	
	public static Object runScriptById(String scriptId,String functionName,Object[] paramObjects) throws Exception{
		if(!ScriptObjectManager.isExist(scriptId)){
			addScriptById(scriptId);
		}
		Object result = ScriptObjectManager.runScript(scriptId, functionName, paramObjects);
		return result;
	}
	
	public static Object runScript(String script,String functionName,Object[] paramObjects){
		Object result = ScriptExecutor.runScript(script, functionName, paramObjects);
		return result;
	}
	
	public static Scriptable addScript(Script script) throws Exception{
		Scriptable scope = null;

		if(ScriptObjectManager.isExist(script.getScriptId())){
			throw new Exception("the script(" + script.getScriptId() + ") has exist.");
		}
		else{
			script.compile();
			scope = ScriptObjectManager.addScriptObject(script.getScriptId(), script.getCompiledScript());
		}
		
		return scope;
	}
	
	public static Scriptable addScriptById(String scriptId) throws Exception{
		Scriptable scope = null;
		if(!ScriptObjectManager.isExist(scriptId)){
			Script script = ScriptFactory.createScript(scriptId);
			if(script == null){
				throw new ScriptNotFoundException("can not find the script by the scriptId.");
			}
			else{
				script.compile();
				scope = ScriptObjectManager.addScriptObject(script.getScriptId(), script.getCompiledScript());
			}
		}
		
		return scope;
	}
	
	public static Scriptable getScriptable(String scriptId) throws ScriptNotFoundException{
		return ScriptObjectManager.getScriptObject(scriptId);
	}
	
	public static void removeScriptable(String scriptId){
		ScriptObjectManager.removeScriptObject(scriptId);
	}
	
	public static void updateScriptable(Script script) throws Exception{
		if(ScriptObjectManager.isExist(script.getScriptId())){
			ScriptObjectManager.removeScriptObject(script.getScriptId());
		}
		
		script.compile();
		ScriptObjectManager.addScriptObject(script.getScriptId(),script.getCompiledScript());
	}
ScriptObjectManager
protected static Logger log = LoggerFactory.getLogger(ScriptObjectManager.class);
	public static Scriptable globalScope = null;
	private static String globalScriptPath = "classpath*:/script/global/*.javascript";
	
	static {
		try{
			loadGlobalScriptObject();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private static void loadGlobalScriptObject() throws ScriptCompileException{
		Context cx = Context.enter();
		try {
			globalScope = cx.initStandardObjects();
			//load all common script in javascript/global/
			List<FileInfo> fileInfoList = FileUtil.loadFiles(globalScriptPath);
			for(FileInfo fileInfo : fileInfoList){
				int startIndex = fileInfo.getFilePath().indexOf("script/global");
				int endIndex = fileInfo.getFilePath().indexOf(".javascript");
				String path = fileInfo.getFilePath().substring(startIndex,endIndex);
				path = path.replaceAll("/", "\\.");//javascript.global.xxx
				cx.evaluateString(globalScope, fileInfo.getContent(),path, 0, null);
			}
			
			ScriptableObject.putProperty(globalScope, "_log", new ScriptLog());
		}catch (Exception e) {
			throw new ScriptCompileException("an error occured when compiling globalScript:\n"+e,e);
		} finally {
			Context.exit();
		}
	}
	
	public static boolean isExist(String scriptId){
		try{
			Object object = findObject(globalScope, scriptId);
			if(object != null){
				return true;
			}
			else{
				return false;
			}
			
		}catch(ScriptNotFoundException e){
			return false;
		}
	}
	
	public static void removeScriptObject(String scriptId){
		globalScope.delete(scriptId);
	}
	
	public static void removeAllScriptObject(){
		Object [] ids = globalScope.getIds();
		for(Object id : ids){
			globalScope.delete(String.valueOf(id));
		}
	}
	
	
	public static Scriptable addScriptObject(String scriptId,String script) throws ScriptCompileException{
		Context cx = Context.enter();
		Scriptable scope = null;
		
		try {
			
			cx.evaluateString(globalScope, script,scriptId, 0, null);
			scope = (Scriptable)findObject(globalScope, scriptId);
			
		}catch (Exception e) {
			throw new ScriptCompileException("an error occured when compiling globalScript:\n"+e,e);
		} finally {
			Context.exit();
		}
		
		return scope;
	}
	
	public static void updateScriptObject(String scriptId,String script) throws ScriptCompileException{
		removeScriptObject(scriptId);
		addScriptObject(scriptId,script);
		
	}
	
	public static Scriptable getScriptObject(String scriptId) throws ScriptNotFoundException{
		Scriptable scope = (Scriptable)findObject(globalScope, scriptId);
		return scope;
	}
	
	public static Object findObject(Scriptable scope,String path) throws ScriptNotFoundException{
		Object object = null;
		String [] paths = path.split("\\.");
		for(String item : paths){
			object = scope.get(item, scope);
			if (object != Scriptable.NOT_FOUND) {
            	scope = (Scriptable)object;
            }
		}
		
	    if (object == Scriptable.NOT_FOUND) {
            throw new ScriptNotFoundException(path + " is not defined.");
        } else {
            log.debug(path + " = " + Context.toString(object));
        }
	    
		return object;
	}
	
	public static Object runScript(String scriptId,String functionName,String paramJsonString) throws ScriptNotFoundException{
		 Context cx = Context.enter();
		 Object result = null;
	     try {
		        Scriptable scope = getScriptObject(scriptId);
		        Object fun = ScriptUtil.findObject(scope, "_SCRIPT_ENGINE.executeFunction");
				if(!functionName.startsWith("_SCRIPT_ENGINE."))
					functionName = scriptId + "." + functionName;
				Object functionArgs[] = { functionName,paramJsonString};
				Function f = (Function) fun;
				result = f.call(cx, scope, scope, functionArgs);
				String strReturn = Context.toString(result);
				return strReturn;
				
	     } finally {
	            Context.exit();
	     }
	}
	
	public static Object runScript(String scriptId,String functionName,Object[] paramObjects) throws ScriptRuntimeException,ScriptNotFoundException{
		 Context cx = Context.enter();
		 Object result = null;
	     try {
	    	 	Scriptable scope = getScriptObject(scriptId);
	    	 	String realFunctionName = scriptId + "." + functionName;
	    	 	
		        Object function = ScriptUtil.findObject(scope, realFunctionName);
		        
				//获取方法
			    if (function == Scriptable.NOT_FOUND) {
	                throw new ScriptRuntimeException(realFunctionName + " is not defined.");
	            } else {
	                log.debug(realFunctionName + " = " + Context.toString(function));
	            }
				if (!(function instanceof Function)) {
				    throw new ScriptRuntimeException(realFunctionName + " is undefined or not a function.");
				} else {
				    Function f = (Function)function;
				    result = f.call(cx, scope, scope, paramObjects);
				    log.debug("result:{}" , result);
				}
	     } finally {
	            Context.exit();
	     }
	     
	     return result;
	}
DeleteScopeInvalid
public static void main(String[] args) {
		 Context ctx = Context.enter();
		 Scriptable globalScope = ctx.initStandardObjects();
	     try {
		        ctx.evaluateString(globalScope, "function add(x,y){return x + y;}","addScope", 0, null);
		        ctx.evaluateString(globalScope, "function minus(x,y){return x + y;}","minusScope", 0, null);
	     } finally {
	            Context.exit();
	     }
	     
	     String result = PrintScope.print(globalScope);
	     System.out.println("before:" + result);
	     
	     ctx = Context.enter();
	     try {
	    	 globalScope.delete("minusScope");
	     } finally {
	            Context.exit();
	     }
	     
	     String result2 = PrintScope.print(globalScope);
	     System.out.println("after:" + result2);
	}
DeleteScope
public static void main(String[] args) {
		 Context ctx = Context.enter();
		 Scriptable globalScope = ctx.initStandardObjects();
	     try {
		        ctx.evaluateString(globalScope, "function add(x,y){return x + y;}","add", 0, null);
	     } finally {
	            Context.exit();
	     }
	     
	     ctx = Context.enter();
		 Scriptable scope = ctx.initStandardObjects();
	     try {
		        ctx.evaluateString(scope, "function minus(x,y){return x + y;}","minus", 0, null);
		        globalScope.put("minusScope", globalScope, scope);
	     } finally {
	            Context.exit();
	     }
	     
	     String result1 = PrintScope.print(globalScope);
	     System.out.println("before:" + result1);
	     
	     ctx = Context.enter();
	     try {
	    	 globalScope.delete("minusScope");
	     } finally {
	            Context.exit();
	     }
	     
	     String result2 = PrintScope.print(globalScope);
	     System.out.println("after:" + result2);
	}
ScriptExecutor
public static Object execute(Scriptable scope,String functionName,Object... params){
		 Context cx = Context.enter();
		 Object result = null;
	     try {
	    	//获取方法
			Object object = scope.get(functionName, scope);
		    if (object == Scriptable.NOT_FOUND) {
                System.out.println(functionName + " is not defined.");
            } else {
                System.out.println(functionName + " = " + Context.toString(object));
            }
		    
			if (!(object instanceof Function)) {
			    System.out.println(functionName + " is undefined or not a function.");
			} else {
			    Function f = (Function)object;
			    result = f.call(cx, scope, scope, params);
			    String report = Context.toString(result);
			    System.out.println(report);
			}
	     } finally {
	            Context.exit();
	     }
	     
	     return result;
	}
ScopeInScope
public static void main(String[] args) {
		 
		 Context ctx = Context.enter();
		 Scriptable globalScope = ctx.initStandardObjects();
	     try {
		        ctx.evaluateString(globalScope, "function add(x,y){return x + y;}","add", 0, null);
	     } finally {
	            Context.exit();
	     }
	     
	     ctx = Context.enter();
		 Scriptable scope = ctx.initStandardObjects();
	     try {
		        ctx.evaluateString(scope, "function minus(x,y){return x - y;}","minus", 0, null);
		        ctx.evaluateString(scope, "function add1(x,y){return add(x,y);}","add1", 0, null);
		        globalScope.put("minusScope", globalScope, scope);
	     } finally {
	            Context.exit();
	     }
	     
	     String scriptResult = ScriptUtil.toString(globalScope);
	     System.out.println(scriptResult);
	     
	     Context cx = Context.enter();
	     try {
	    	 Scriptable minusScope = (Scriptable)globalScope.get("minusScope", globalScope);
	    	 String functionName = "add1";
	    	 
	    	//获取方法
			Object object = minusScope.get(functionName, minusScope);
		    if (object == Scriptable.NOT_FOUND) {
                System.out.println(functionName + " is not defined.");
            } else {
                System.out.println(functionName + " = " + Context.toString(object));
            }
		    
			if (!(object instanceof Function)) {
			    System.out.println(functionName + " is undefined or not a function.");
			} else {
			    Object functionArgs[] = { 6,3 };
			    Function f = (Function)object;
			    Object result2 = f.call(cx, globalScope, minusScope, functionArgs);
			    String report = Context.toString(result2);
			    System.out.println(report);
			}
	     } finally {
	            Context.exit();
	     }

	}
ScriptGetter
public static String getScript(String path) throws IOException{
		InputStream input = ClassLoader.getSystemResourceAsStream(path); 
		ByteArrayOutputStream outputstream = null;
		if(input == null)
			throw new IOException("can not find file:" + path);
		
		String fileString = "";
		try { 
			outputstream = new ByteArrayOutputStream();
			byte[] str_b = new byte[1024];
			int i = -1;
			while ((i = input.read(str_b)) > 0) {
			   outputstream.write(str_b,0,i);
			}
			fileString = outputstream.toString("UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			input.close();
			outputstream.close();
		}
		
		return fileString;
	}
ScopeInScope2
public static void main(String[] args) throws IOException {
		 
		 Context ctx = Context.enter();
		 Scriptable globalScope = ctx.initStandardObjects();
	     try {
	    	 String globalScript = ScriptGetter.getScript("javascript/global.javascript");
	    	 String mathScript = ScriptGetter.getScript("javascript/math.javascript");
		     ctx.evaluateString(globalScope, globalScript,"globalScript", 0, null);
		     ctx.evaluateString(globalScope, mathScript,"mathScript", 0, null);
	     } finally {
	            Context.exit();
	     }
	     
	     Scriptable scope = (Scriptable)globalScope.get("math", globalScope);
	     
	     Object result = ScriptExecutor.execute(scope, "add", new Object[]{5,6});
	     
	     result = ScriptExecutor.execute(scope, "print", new Object[]{"me"});
	     
	     globalScope.delete("math");
	     
	     scope = (Scriptable)globalScope.get("math", globalScope);
	     
	     System.out.println(scope);
	     
	}
书籍
深入理解计算机系统

虚拟机的设计与实现

Joel 说软件

How to design program

程序设计心理学

Linux内核设计与实现

数据访问模式-面向对象应用中的数据库交互
UsingJavaScriptVariables
public class UsingJavaScriptVariables {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Context cx = Context.enter();
	        try {
	            // Set version to JavaScript1.2 so that we get object-literal style
	            // printing instead of "[object Object]"
	            cx.setLanguageVersion(Context.VERSION_1_2);

	            // Initialize the standard objects (Object, Function, etc.)
	            // This must be done before scripts can be executed.
	            Scriptable scope = cx.initStandardObjects();

	            // Now we can evaluate a script. Let's create a new object
	            // using the object literal notation.
	            Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", "MySource", 1, null);
	            Scriptable obj = (Scriptable) scope.get("obj", scope);

	            // Should print "obj == result" (Since the result of an assignment
	            // expression is the value that was assigned)
	            System.out.println("obj " + (obj == result ? "==" : "!=") + " result");

	            // Should print "obj.a == 1"
	            System.out.println("obj.a == " + obj.get("a", obj));

	            Scriptable b = (Scriptable) obj.get("b", obj);

	            // Should print "obj.b[0] == x"
	            System.out.println("obj.b[0] == " + b.get(0, b));

	            // Should print "obj.b[1] == y"
	            System.out.println("obj.b[1] == " + b.get(1, b));

	            // Should print {a:1, b:["x", "y"]}
	            Function fn = (Function) ScriptableObject.getProperty(obj, "toString");
	            System.out.println(fn.call(cx, scope, obj, new Object[0]));
	        } finally {
	            Context.exit();
	        }
	}

}
UseJavaAPI
public class UseJavaAPI {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Context cx = Context.enter();
	        try {
	            Scriptable scope = cx.initStandardObjects();
	            String s = "java.lang.System.out.println(3)";
	            Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
	            System.err.println(Context.toString(result));
	        } finally {
	            Context.exit();
	        }

	}

}
ScriptException
public class ScriptException {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) {
		 Context cx = Context.enter();
	     try {
		        Scriptable scope = cx.initStandardObjects();
				InputStream in = ClassLoader.getSystemResourceAsStream("js/catch_exception.js"); 
				
				LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
				String script = "";
				String line = "";
			    while((line = reader.readLine()) != null) {
			    	script += line;
		        }
			    
				cx.evaluateString(scope, script,"MySource", 1, null);
				
	     } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
	            Context.exit();
	     }
	}

}
RunScript
public class RunScript {
	 public static void main(String args[]){
	        // Creates and enters a Context. The Context stores information
	        // about the execution environment of a script.
	        Context cx = Context.enter();
	        try {
	            // Initialize the standard objects (Object, Function, etc.)
	            // This must be done before scripts can be executed. Returns
	            // a scope object that we use in later calls.
	            Scriptable scope = cx.initStandardObjects();

	            // Collect the arguments into a single string.
	            String s = "function f(){var 1a=1;var b=2;return a+b;} f();";

	            // Now evaluate the string we've colected.
	            Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);

	            // Convert the result to a string and print it.
	            System.err.println(Context.toString(result));

	        } finally {
	            // Exit from the context.
	            Context.exit();
	        }
	    }
}
ImportPackage
public class ImportPackage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Context cx = Context.enter();
	        try {
	            Scriptable scope = new ImporterTopLevel(cx);
	            String s = "importPackage(java.lang);System.out.println(3)";
	            Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
	            System.err.println(Context.toString(result));
	        } finally {
	            Context.exit();
	        }

	}

}
ImportClass
public class ImportClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Context cx = Context.enter();
	        try {
	            Scriptable scope = new ImporterTopLevel(cx);
	            String s = "importClass(java.lang.System);System.out.println(3);";
	            Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
	            System.err.println(Context.toString(result));
	        } finally {
	            Context.exit();
	        }
	}

}
Global site tag (gtag.js) - Google Analytics