How do I use Java ScriptEngine to create a Javascript function
===

In this question I asked about supporting an expression language and used the Javascript idea sucessfully http://stackoverflow.com/questions/6285045/putting-a-simple-expression-language-into-java

But the Javascript expressions reequired hav become quote verbose and Im trying to work out how I can use ScriptEngine to create javascript functions that I can refer to in my expressions.

So far Ive hacked a solution by using reexp on the user entered string which can include a pseudo fucntion called ifempty whihc I then convert to the javascript before passing to script engine

 

    public final String formatFromMask(String mask,Song exampleSong)
        {
            mask = convertPsuedoFunctions(mask);
            try
            {
                ScriptEngineManager manager = new ScriptEngineManager();
                ScriptEngine engine = manager.getEngineByName("JavaScript");
                for(SongFieldName next:SongFieldName.values())
                {
                    engine.put(next.getScriptVar(),exampleSong.getFieldValueOrEmptyString(next.getSongFieldKey()));
                }
                Object result = engine.eval(mask);
                return (String)result;
            }
            catch(ScriptException se)
            {
                se.printStackTrace();
            }
            return "";
        }
    
    
        private String convertPsuedoFunctions(String mask)
        {
            //i.e ifnotempty(artist,' - ') -> (artist.length>0 ? artist + ' - ' : '')
            mask=mask.replaceAll("ifnotempty\\(([a-z]*)\\,('.*')\\)","($1.length>0 ? $1 + $2 : '')");
    
            return mask;
        }

 
but I was wondering about a proper solution, whereby I actually create a real javascript function.