1 ImportJava.io.*;2 Importjavax.script.Invocable;3 ImportJavax.script.ScriptEngine;4 ImportJavax.script.ScriptEngineManager;5 Importjavax.script.ScriptException;6 ImportOrg.slf4j.Logger;7 Importorg.slf4j.LoggerFactory;8 ImportCom.ppcredit.common.util.file.FileUtil;9 Ten /** One * Common JS script engine tool class A */ - Public classCommonscriptengineutil { - Private StaticLogger log = Loggerfactory.getlogger (commonscriptengineutil.class);//Log the - Private StaticScriptEngine engine = (NewScriptenginemanager ()). Getenginebyname ("JavaScript"); - - Private StaticInvocable invoke =NULL; + - /** + * Call the function in JS A * @paramjsname js file name at * @paramfunction name called by functionname - * @paramparam calling the parameters of the JS function - * @return - */ - Public Staticstring Invokejsfuntion (String jsname, string functionname, string param) { - Initjs (jsname); in synchronized(Invoke) { -String result =param; to if(Invoke! =NULL){ + Try { - LongStartTime =System.currenttimemillis (); theString C =(String) invoke.invokefunction (functionname, param); * LongEndTime =System.currenttimemillis (); $Log.info ("Invokejsfuntion Time >>>>" + (endtime-startTime));Panax Notoginsengresult =C; -}Catch(nosuchmethodexception e) { the Log.error (E.getmessage ()); +}Catch(scriptexception e) { A //Reload If an error occurs the Initjs (jsname); + Log.error (E.getmessage ()); - } $ } $ returnresult; - } - } the - Wuyi Private Static voidInitjs (String jsname) { theString BasePath = Fileutil.getapppath (commonscriptengineutil.class); -String jsfilename = basepath + "/resources/" + jsname;//Read JS file WuInputStreamReader reader =NULL; - Try { AboutReader =NewInputStreamReader (NewFileInputStream (Jsfilename), "UTF-8"); $ Engine.eval (reader); - if(Engineinstanceofinvocable) { -Invoke =(invocable) engine; - } A}Catch(FileNotFoundException e) { + Log.error (E.getmessage ()); the}Catch(scriptexception e) { - Log.error (E.getmessage ()); $}Catch(unsupportedencodingexception e) { the Log.error (E.getmessage ()); the}finally { the if(Reader! =NULL){ the Try { - reader.close (); in}Catch(IOException e) { the Log.error (E.getmessage ()); the } About } the } the } the + Public Static voidMain (string[] args) { -String enc = invokejsfuntion ("Aes.js", "Valaesencryptset", "123456"); the System.out.println (ENC);Bayi } the}
JS function called by scripting engine in Java