How can you run Javascript using Rhino for Java in a sandbox?

前端 未结 6 868
梦毁少年i
梦毁少年i 2020-12-04 08:50

Part of our java application needs to run javascript that is written by non-developers. These non-developers are using javascript for data formatting. (Simple logic and str

6条回答
  •  春和景丽
    2020-12-04 09:40

    To guard against infinite loops, you can observe the instruction count as the script runs (this works only with interpreted scripts, not with compiled ones).

    There is this example in the Rhino JavaDocs to prevent a script from running for more than ten seconds:

     protected void observeInstructionCount(Context cx, int instructionCount)
     {
         MyContext mcx = (MyContext)cx;
         long currentTime = System.currentTimeMillis();
         if (currentTime - mcx.startTime > 10*1000) {
             // More then 10 seconds from Context creation time:
             // it is time to stop the script.
             // Throw Error instance to ensure that script will never
             // get control back through catch or finally.
             throw new Error();
         }
     }
    

提交回复
热议问题