javaphpquercusscriptengine

How do I register a Quercus custom function when using Quercus in Java ScriptEngine?


I am using Quercus in Apache JMeter for simple scripting of tests. I have a requirement to log from PHP using log4j, and on the whole this works well. So I wrote a Quercus module like this:

public class LogFunction extends AbstractQuercusModule {

    private static Logger log = Logger.getLogger(LogFunction.class);

    public void log_str(Env env, String str) {
        log.info(str);
    }
}

Now, I am testing this with the following code:

public class QuercusTest {

private static ScriptEngine engine;

static{     
    //set up Quercus
    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("php");
}

public static void main(String[] args) throws ScriptException{
    engine.eval("<?php log_str('Hello');");
}

}

This throws an exception (as I would expect) because this custom function isn't registered.

Exception in thread "main" com.caucho.quercus.QuercusErrorException: eval::1: Fatal Error: 'log_str' is an unknown function.
    at com.caucho.quercus.env.Env.error(Env.java:6420)
    at com.caucho.quercus.env.Env.error(Env.java:6306)
    at com.caucho.quercus.env.Env.error(Env.java:5990)
    at com.caucho.quercus.expr.CallExpr.evalImpl(CallExpr.java:198)
    at com.caucho.quercus.expr.CallExpr.eval(CallExpr.java:151)
    at com.caucho.quercus.expr.Expr.evalTop(Expr.java:523)
    at com.caucho.quercus.statement.ExprStatement.execute(ExprStatement.java:67)
    at com.caucho.quercus.program.QuercusProgram.execute(QuercusProgram.java:413)
    at com.caucho.quercus.script.QuercusScriptEngine.eval(QuercusScriptEngine.java:134)
    at com.caucho.quercus.script.QuercusScriptEngine.eval(QuercusScriptEngine.java:179)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
    at com.succeed.QuercusTest.main(QuercusTest.java:18)

However, I can't see how to register this Quercus module with the Java scripting engine. Docs are a bit sparse... Any help would be appreciated.


Solution

  • 1.

    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("php");
    

    2.

    if( engine instanceof QuercusScriptEngine )
    {
        ((QuercusScriptEngine)engine).getQuercus().addModule(new LogFunction());
    }
    

    This works. (quercus-4.0.18-src + resin 4.0)