java scripting API - how to stop the evaluation

后端 未结 7 1646
孤城傲影
孤城傲影 2020-12-09 06:10

i have writen a servlet that recives a java script code and process it and returns the answer. for that i have used the java scripting API

in the code below if scrip

7条回答
  •  萌比男神i
    2020-12-09 07:11

    I know this is an older thread, but I have a more direct solution for stopping the JavaScript eval: Invoke the "exit" function that Nashorn provides.

    Inside the class I use to run the script engine, I include:

    private Invocable invocable_ = null;
    private final ExecutorService pool_ = Executors.newFixedThreadPool(1);  
    
    public boolean runScript(String fileName)
        {
        pool_.submit(new Callable() 
            {       
            ScriptEngine engine 
                = new ScriptEngineManager().getEngineByName("nashorn");
            public Boolean call() throws Exception
                {
                try
                    {
                    invocable_ = (Invocable)engine;
                    engine.eval(
                            new InputStreamReader(
                                    new FileInputStream(fileName), 
                                    Charset.forName("UTF-8")) );
                    return true;
                    }
                catch (ScriptException ex)
                    {
                    ...
                    return false;
                    } 
                catch (FileNotFoundException ex)
                    {
                    ...
                    return false;
                    }                   
                }
            });
    
        return true;
        }
    
    public void
    shutdownNow()
        {
    
        try
            {
            invocable_.invokeFunction("exit");
            } 
        catch (ScriptException ex)
            {
            ...
            } 
        catch (NoSuchMethodException ex)
            {
            ...
            }
    
        pool_.shutdownNow();
        invocable_ = null;
        }
    

    Now, call:

    myAwesomeClass.shutdownNow();
    

    The script will stop immediately.

提交回复
热议问题