Package net.xoetrope.optional.scripts.javascript

Source Code of net.xoetrope.optional.scripts.javascript.JavaScriptEngine

package net.xoetrope.optional.scripts.javascript;

import net.xoetrope.optional.scripts.ScriptEngine;
import net.xoetrope.optional.scripts.ScriptException;
import net.xoetrope.optional.scripts.Session;
import net.xoetrope.xui.XPage;
import net.xoetrope.xui.XPageManager;
import net.xoetrope.xui.XProject;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

/**
*
* @author Donald D. Walters
*/
public class JavaScriptEngine implements ScriptEngine
{
  private XProject currentProject;
  private XPageManager pageMgr;

  /**
   * Creates a new instance of JavaScriptEngine
   * @param proj the current project
   */
  public JavaScriptEngine()
  {
  }

  /**
   * Set the owning project
   * @param proj the current project
   */
  public void setProject( XProject proj )
  {
    currentProject = proj;
    pageMgr = currentProject.getPageManager();
  }

  /**
   * Returns the scripts for this page
   */
  public String getPageScript()
  {
    XPage currentPage = (XPage)pageMgr.getCurrentPage( null );
    return (String)currentPage.getAttribute( "source", "scripts" );
  }

  /** Configures the current environment with some necessary variables*/
  public void configureScriptEnvironment( Scriptable scope, Context cx )
  {
    scope.put("session", scope, Session.getSession());
    scope.put("console", scope, System.out);
    scope.put("pageManager", scope, pageMgr );
    scope.put("document", scope, (XPage)pageMgr.getCurrentPage( null ));

    cx.evaluateString(scope, getPageScript(), "<cmd>", 1, null);
  }

  /**
   * Executes a given script and returns the result.
   * @param script the script to be executed for the current page
   */
  public Object executeScript( String script ) throws ScriptException
  {
    Object result = null;
    Context cx = Context.enter();

    try {           
      Scriptable scope = cx.initStandardObjects();

      configureScriptEnvironment( scope, cx );

      result = cx.evaluateString( scope, script, "<cmd>", 1, null );           
    }
    catch(Exception e){           
      e.printStackTrace();
      throw new ScriptException( e.getMessage(), e );           
    }
    finally {
      //flushes the current context
      Context.exit();           
    }

    return result;
  }
}
TOP

Related Classes of net.xoetrope.optional.scripts.javascript.JavaScriptEngine

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.