org.mozilla.javascript.tools.shell.Global Java Examples

The following examples show how to use org.mozilla.javascript.tools.shell.Global. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DoctestsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void runDoctest() throws Exception {
    ContextFactory factory = ContextFactory.getGlobal();
    Context cx = factory.enterContext();
    try {
        cx.setOptimizationLevel(optimizationLevel);
        Global global = new Global(cx);
        // global.runDoctest throws an exception on any failure
        int testsPassed = global.runDoctest(cx, global, source, name, 1);
        System.out.println(name + "(" + optimizationLevel + "): " +
                testsPassed + " passed.");
        assertTrue(testsPassed > 0);
    } catch (Exception ex) {
      System.out.println(name + "(" + optimizationLevel + "): FAILED due to "+ex);
      throw ex;
    } finally {
        Context.exit();
    }
}
 
Example #2
Source File: DoctestsTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@Test
public void runDoctest() throws Exception {
    Context cx = RhinoAndroidHelper.prepareContext();
    try {
        cx.setOptimizationLevel(optimizationLevel);
        Global global = new Global(cx);
        TestUtils.addAssetLoading(global);
        // global.runDoctest throws an exception on any failure
        int testsPassed = global.runDoctest(cx, global, source, name, 1);
        System.out.println(name + "(" + optimizationLevel + "): " +
                testsPassed + " passed.");
        assertTrue(testsPassed > 0);
    } catch (Exception ex) {
      System.out.println(name + "(" + optimizationLevel + "): FAILED due to "+ex);
      throw ex;
    } finally {
        Context.exit();
    }
}
 
Example #3
Source File: Main.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Helper method for {@link #mainEmbedded(String)}, etc.
 */
private static Main mainEmbeddedImpl(ContextFactory factory,
                                     Object scopeProvider,
                                     String title) {
    if (title == null) {
        title = "Rhino JavaScript Debugger (embedded usage)";
    }
    Main main = new Main(title);
    main.doBreak();
    main.setExitAction(new IProxy(IProxy.EXIT_ACTION));

    main.attachTo(factory);
    if (scopeProvider instanceof ScopeProvider) {
        main.setScopeProvider((ScopeProvider)scopeProvider);
    } else {
        Scriptable scope = (Scriptable)scopeProvider;
        if (scope instanceof Global) {
            Global global = (Global)scope;
            global.setIn(main.getIn());
            global.setOut(main.getOut());
            global.setErr(main.getErr());
        }
        main.setScope(scope);
    }

    main.pack();
    main.setSize(600, 460);
    main.setVisible(true);
    return main;
}
 
Example #4
Source File: JSConfigParser.java    From celos with Apache License 2.0 5 votes vote down vote up
public void putPropertiesInScope(Map<String, Object> jsParameters, Global scope) {
    if (jsParameters != null) {
        for (String key : jsParameters.keySet()) {
            ScriptableObject.putProperty(scope, key, jsParameters.get(key));
        }
    }
}
 
Example #5
Source File: JSConfigParser.java    From celos with Apache License 2.0 5 votes vote down vote up
public Global createGlobalScope() {
    Global scope = new Global();
    scope.initStandardObjects(context, true);
    Object wrappedMapper = Context.javaToJS(Util.JSON_READER, scope);
    ScriptableObject.putProperty(scope, "celosReader", wrappedMapper);
    Object wrappedScope = Context.javaToJS(scope, scope);
    ScriptableObject.putProperty(scope, "celosScope", wrappedScope);

    return scope;
}
 
Example #6
Source File: WorkflowConfigurationParser.java    From celos with Apache License 2.0 5 votes vote down vote up
public void importDefaultsIntoScope(String label, Global scope) throws IOException {
    File defaultsFile = new File(defaultsDir, label + "." + WORKFLOW_FILE_EXTENSION);
    LOGGER.info("Loading defaults: " + defaultsFile);
    FileReader fileReader = new FileReader(defaultsFile);
    String fileName = defaultsFile.toString();
    jsConfigParser.evaluateReader(scope, fileReader, fileName);
}
 
Example #7
Source File: TestConfigurationParser.java    From celos with Apache License 2.0 5 votes vote down vote up
Object evaluateTestConfig(Reader reader, String desc) throws IOException {
    Global scope = jsConfigParser.createGlobalScope();

    Object wrappedContext = Context.javaToJS(this, scope);
    Map jsProperties = Maps.newHashMap();
    jsProperties.put("testConfigurationParser", wrappedContext);
    jsConfigParser.putPropertiesInScope(jsProperties, scope);

    InputStream scripts = getClass().getResourceAsStream("celos-ci-scripts.js");
    jsConfigParser.evaluateReader(scope, new InputStreamReader(scripts), "celos-ci-scripts.js");
    return jsConfigParser.evaluateReader(scope, reader, desc);
}
 
Example #8
Source File: Main.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper method for {@link #mainEmbedded(String)}, etc.
 */
private static Main mainEmbeddedImpl(ContextFactory factory,
                                     Object scopeProvider,
                                     String title) {
    if (title == null) {
        title = "Rhino JavaScript Debugger (embedded usage)";
    }
    Main main = new Main(title);
    main.doBreak();
    main.setExitAction(new IProxy(IProxy.EXIT_ACTION));

    main.attachTo(factory);
    if (scopeProvider instanceof ScopeProvider) {
        main.setScopeProvider((ScopeProvider)scopeProvider);
    } else {
        Scriptable scope = (Scriptable)scopeProvider;
        if (scope instanceof Global) {
            Global global = (Global)scope;
            global.setIn(main.getIn());
            global.setOut(main.getOut());
            global.setErr(main.getErr());
        }
        main.setScope(scope);
    }

    main.pack();
    main.setSize(600, 460);
    main.setVisible(true);
    return main;
}
 
Example #9
Source File: Main.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Entry point for embedded applications.  This method attaches
 * to the global {@link ContextFactory} with a scope of a newly
 * created {@link Global} object.  No I/O redirection is performed
 * as with {@link #main(String[])}.
 */
public static Main mainEmbedded(String title) {
    ContextFactory factory = ContextFactory.getGlobal();
    Global global = new Global();
    global.init(factory);
    return mainEmbedded(factory, global, title);
}
 
Example #10
Source File: ExternalArrayTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Before
public void init()
{
    cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setGeneratingDebug(true);

    Global global = new Global(cx);
    TestUtils.addAssetLoading(global);
    root = cx.newObject(global);
}
 
Example #11
Source File: SunSpiderBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runTest(int optLevel)
    throws IOException
{

    Context cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(optLevel);
    Global root = new Global(cx);
    TestUtils.addAssetLoading(root);
    root.put("RUN_NAME", root, "SunSpider-" + optLevel);
    Object result = cx.evaluateString(root, TestUtils.readAsset(TEST_SRC), TEST_SRC, 1, null);
    results.put(optLevel, result.toString());
}
 
Example #12
Source File: V8Benchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runTest(int optLevel)
    throws IOException
{


    Context cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(optLevel);
    Global root = new Global(cx);
    TestUtils.addAssetLoading(root);
    root.put("RUN_NAME", root, "V8-Benchmark-" + optLevel);
    Object result = cx.evaluateString(root, TestUtils.readAsset(TEST_SRC), TEST_SRC, 1, null);
    results.put(optLevel, result.toString());
}
 
Example #13
Source File: CaliperObjectBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@BeforeExperiment
@SuppressWarnings("unused")
void create()
    throws IOException
{
    cx = Context.enter();
    cx.setOptimizationLevel(optLevel);
    cx.setLanguageVersion(Context.VERSION_ES6);

    scope = new Global(cx);
    runCode(cx, scope, "testsrc/benchmarks/caliper/fieldTests.js");

    Object[] sarray = new Object[stringKeys];
    for (int i = 0; i < stringKeys; i++) {
        int len = rand.nextInt(49) + 1;
        char[] c = new char[len];
        for (int cc = 0; cc < len; cc++) {
            c[cc] = (char) ('a' + rand.nextInt(25));
        }
        sarray[i] = new String(c);
    }
    strings = cx.newArray(scope, sarray);

    Object[] iarray = new Object[intKeys];
    for (int i = 0; i < intKeys; i++) {
        iarray[i] = rand.nextInt(10000);
    }
    ints = cx.newArray(scope, iarray);
}
 
Example #14
Source File: CaliperSpiderBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@BeforeExperiment
@SuppressWarnings("unused")
void create()
    throws IOException
{
    cx = Context.enter();
    cx.setOptimizationLevel(optLevel);
    cx.setLanguageVersion(Context.VERSION_ES6);
    scope = new Global(cx);

    for (String bn : BENCHMARKS) {
        compileScript(cx, bn);
    }
}
 
Example #15
Source File: TestUtils.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
public static void loadAsset(Context cx, Scriptable thisObj,
                             Object[] args, Function funObj)
{
    for (Object arg : args) {
        String file = Context.toString(arg);
        Global.load(cx, thisObj, new Object[]{copyFromAssets(file)}, funObj);
    }
}
 
Example #16
Source File: Main.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Entry point for embedded applications.  This method attaches
 * to the global {@link ContextFactory} with a scope of a newly
 * created {@link Global} object.  No I/O redirection is performed
 * as with {@link #main(String[])}.
 */
public static Main mainEmbedded(String title) {
    ContextFactory factory = ContextFactory.getGlobal();
    Global global = new Global();
    global.init(factory);
    return mainEmbedded(factory, global, title);
}
 
Example #17
Source File: LessCompiler.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Initializes this <code>LessCompiler</code>.
 * <p>
 * It is not needed to call this method manually, as it is called implicitly by the compile methods if needed.
 * </p>
 */
public synchronized void init() {
  final long start = System.currentTimeMillis();

  try {
    final Context cx = Context.enter();
    cx.setOptimizationLevel(-1);
    cx.setLanguageVersion(Context.VERSION_1_7);

    final Global global = new Global();
    global.init(cx);

    scope = cx.initStandardObjects(global);

    final List<URL> jsUrls = new ArrayList<URL>(2 + customJs.size());
    jsUrls.add(envJs);
    jsUrls.add(lessJs);
    jsUrls.addAll(customJs);

    for(final URL url : jsUrls){
      final InputStreamReader inputStreamReader = new InputStreamReader(url.openConnection().getInputStream());
      try{
        cx.evaluateReader(scope, inputStreamReader, url.toString(), 1, null);
      }finally{
        inputStreamReader.close();
      }
    }
    doIt = cx.compileFunction(scope, COMPILE_STRING, "doIt.js", 1, null);
  }
  catch (final Exception e) {
    final String message = "Failed to initialize LESS compiler.";
    log.error(message, e);
    throw new IllegalStateException(message, e);
  }finally{
    Context.exit();
  }

  if (log.isDebugEnabled()) {
    log.debug("Finished initialization of LESS compiler in " + (System.currentTimeMillis() - start) + " ms.");
  }
}
 
Example #18
Source File: WorkflowConfigurationParser.java    From celos with Apache License 2.0 4 votes vote down vote up
Object evaluateReader(Reader r, String fileName, StateDatabaseConnection connection) throws Exception {

        Global scope = jsConfigParser.createGlobalScope();

        Object wrappedThis = Context.javaToJS(this, scope);
        Map jsProperties = Maps.newHashMap(additionalJsVariables);
        jsProperties.put("celosWorkflowConfigurationParser", wrappedThis);
        jsProperties.put("celosConnection", connection);

        jsConfigParser.putPropertiesInScope(jsProperties, scope);

        InputStream scripts = WorkflowConfigurationParser.class.getResourceAsStream(CELOS_SCRIPTS_FILENAME);
        jsConfigParser.evaluateReader(scope, new InputStreamReader(scripts), CELOS_SCRIPTS_FILENAME);

        return jsConfigParser.evaluateReader(scope, r, fileName);
    }
 
Example #19
Source File: ScriptPlugin.java    From ramus with GNU General Public License v3.0 4 votes vote down vote up
@Override
  public ActionDescriptor[] getActionDescriptors() {
      ActionDescriptor javaScript = new ActionDescriptor();
      javaScript.setActionLevel(ActionLevel.GLOBAL);
      javaScript.setAction(new AbstractAction() {
          /**
           *
           */
          private static final long serialVersionUID = -6161853134240219376L;

          {
              putValue(ACTION_COMMAND_KEY, "JavaScriptConsole");
          }

          @Override
          public void actionPerformed(ActionEvent e) {
              SwingUtilities.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                      if (main == null) {
                          main = new Main("Rhino JavaScript Debugger");
                          main.doBreak();

                          main.getDebugFrame().setDefaultCloseOperation(
                                  JFrame.HIDE_ON_CLOSE);

                          ((SwingGui) main.getDebugFrame())
                                  .setExitAction(new Runnable() {
                                      @Override
                                      public void run() {
                                          main.setVisible(false);
                                          Options.saveOptions(main
                                                  .getDebugFrame());
                                      }
                                  });

                          System.setIn(main.getIn());
                          System.setOut(main.getOut());
                          System.setErr(main.getErr());

                          Global global = org.mozilla.javascript.tools.shell.Main
                                  .getGlobal();
                          global.setIn(main.getIn());
                          global.setOut(main.getOut());
                          global.setErr(main.getErr());

                          main
                                  .attachTo(org.mozilla.javascript.tools.shell.Main.shellContextFactory);

                          main.setScope(global);

                          main.pack();
                          main.getDebugFrame().setMinimumSize(
                                  main.getDebugFrame().getSize());
                          main.setSize(600, 460);
                          Options.loadOptions(main.getDebugFrame());

                          new Thread(new Runnable() {
                              @Override
                              public void run() {
                                  org.mozilla.javascript.tools.shell.Main
                                          .exec(new String[]{});
                                  Options.saveOptions(main.getDebugFrame());
                              }
                          }).start();

                      }
                      main.setVisible(true);
                  }
              });
          }
      });

      javaScript.setMenu("Tools");

/*
       * ActionDescriptor ruby = new ActionDescriptor();
 * ruby.setActionLevel(ActionLevel.GLOBAL); ruby.setAction(new
 * AbstractAction() {
 * 
 * private static final long serialVersionUID = 9004972326340291462L;
 * 
 * { putValue(ACTION_COMMAND_KEY, getString("IRBConsole")); }
 * 
 * @Override public void actionPerformed(ActionEvent e) { if
 * (rubyConsole == null) { rubyConsole = new
 * RubyConsole(ScriptPlugin.this); rubyConsole.pack();
 * rubyConsole.setMinimumSize(rubyConsole.getSize()); }
 * rubyConsole.setVisible(true); } });
 * 
 * ruby.setMenu("Tools");
 */

      return new ActionDescriptor[]{javaScript};
  }
 
Example #20
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 3 votes vote down vote up
/**
 * Starts an interactive JavaScript debugger, and break at the next JavaScript execution.
 *
 * <p>
 * This is useful during debugging a test so that you can step execute and inspect state of JavaScript.
 * This will launch a Swing GUI, and the method returns immediately.
 *
 * <p>
 * Note that installing a debugger appears to make an execution of JavaScript substantially slower.
 *
 * <p>
 * TODO: because each script block evaluation in HtmlUnit is done in a separate Rhino context,
 * if you step over from one script block, the debugger fails to kick in on the beginning of the next script
 * block.
 * This makes it difficult to set a break point on arbitrary script block in the HTML page. We need to fix this
 * by tweaking {@link org.mozilla.javascript.tools.debugger.Dim.StackFrame#onLineChange(Context, int)}.
 */
public Dim interactiveJavaScriptDebugger() {
    Global global = new Global();
    HtmlUnitContextFactory cf = ((JavaScriptEngine)getJavaScriptEngine()).getContextFactory();
    global.init(cf);

    Dim dim = org.mozilla.javascript.tools.debugger.Main.mainEmbedded(cf, global, "Rhino debugger: " + testDescription.getDisplayName());

    // break on exceptions. this catch most of the errors
    dim.setBreakOnExceptions(true);

    return dim;
}
 
Example #21
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 3 votes vote down vote up
/**
 * Starts an interactive JavaScript debugger, and break at the next JavaScript execution.
 *
 * <p>
 * This is useful during debugging a test so that you can step execute and inspect state of JavaScript.
 * This will launch a Swing GUI, and the method returns immediately.
 *
 * <p>
 * Note that installing a debugger appears to make an execution of JavaScript substantially slower.
 *
 * <p>
 * TODO: because each script block evaluation in HtmlUnit is done in a separate Rhino context,
 * if you step over from one script block, the debugger fails to kick in on the beginning of the next script block.
 * This makes it difficult to set a break point on arbitrary script block in the HTML page. We need to fix this
 * by tweaking {@link Dim.StackFrame#onLineChange(Context, int)}.
 */
public Dim interactiveJavaScriptDebugger() {
    Global global = new Global();
    HtmlUnitContextFactory cf = ((JavaScriptEngine)getJavaScriptEngine()).getContextFactory();
    global.init(cf);

    Dim dim = org.mozilla.javascript.tools.debugger.Main.mainEmbedded(cf, global, "Rhino debugger: " + getName());

    // break on exceptions. this catch most of the errors
    dim.setBreakOnExceptions(true);

    return dim;
}