示例#1
1
  /** Test of getBindings method, of class Jsr223JRubyEngine. */
  @Test
  public void testGetBindings() throws ScriptException {
    logger1.info("getBindings");
    ScriptEngine instance;
    synchronized (this) {
      System.setProperty("org.jruby.embed.localcontext.scope", "singlethread");
      System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");
      ScriptEngineManager manager = new ScriptEngineManager();
      instance = manager.getEngineByName("jruby");
    }

    instance.eval("p = 9.0");
    instance.eval("q = Math.sqrt p");
    Double expResult = 9.0;
    int scope = ScriptContext.ENGINE_SCOPE;
    Bindings result = instance.getBindings(scope);
    assertEquals(expResult, (Double) result.get("p"), 0.01);
    expResult = 3.0;
    assertEquals(expResult, (Double) result.get("q"), 0.01);

    scope = ScriptContext.GLOBAL_SCOPE;
    result = instance.getBindings(scope);
    // Bug of livetribe javax.script package impl.
    // assertTrue(result instanceof SimpleBindings);
    // assertEquals(0, result.size());
    JRubyScriptEngineManager manager2 = new JRubyScriptEngineManager();
    instance = (JRubyEngine) manager2.getEngineByName("jruby");
    result = instance.getBindings(scope);
    assertTrue(result instanceof SimpleBindings);
    assertEquals(0, result.size());

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
示例#2
0
 public Object get(Object key) {
   for (Resolver scriptResolver : scriptResolvers) {
     if (scriptResolver.containsKey(key)) {
       return scriptResolver.get(key);
     }
   }
   return defaultBindings.get(key);
 }
示例#3
0
  public Object eval(Reader script, ScriptContext scriptContext) throws ScriptException {
    Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);

    SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
    if (helper == null) {
      throw new ScriptException("SlingScriptHelper missing from bindings");
    }

    // ensure GET request
    if (helper.getRequest() != null && !"GET".equals(helper.getRequest().getMethod())) {
      throw new ScriptException("JRuby scripting only supports GET requests");
    }

    final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
      StringBuffer scriptString = new StringBuffer();
      BufferedReader bufferedScript = new BufferedReader(script);
      String nextLine = bufferedScript.readLine();
      while (nextLine != null) {
        scriptString.append(nextLine);
        scriptString.append("\n");
        nextLine = bufferedScript.readLine();
      }

      IRubyObject scriptRubyString = JavaEmbedUtils.javaToRuby(runtime, scriptString.toString());
      IRubyObject erb =
          (IRubyObject)
              JavaEmbedUtils.invokeMethod(
                  runtime, erbModule, "new", new Object[] {scriptRubyString}, IRubyObject.class);

      JavaEmbedUtils.invokeMethod(
          runtime,
          erb,
          "set_props",
          new Object[] {JavaEmbedUtils.javaToRuby(runtime, bindings)},
          IRubyObject.class);

      IRubyObject binding =
          (IRubyObject)
              JavaEmbedUtils.invokeMethod(
                  runtime, erb, "send", new Object[] {bindingSym}, IRubyObject.class);

      scriptContext
          .getWriter()
          .write(
              (String)
                  JavaEmbedUtils.invokeMethod(
                      runtime, erb, "result", new Object[] {binding}, String.class));
    } catch (Throwable t) {
      final ScriptException ex = new ScriptException("Failure running Ruby script:" + t);
      ex.initCause(t);
      throw ex;
    } finally {
      Thread.currentThread().setContextClassLoader(oldClassLoader);
    }
    return null;
  }
示例#4
0
 /** Transfers variables from one interpreter's bindings to another. */
 private void copyBindings(final ScriptInterpreter src, final ScriptInterpreter dest) {
   if (src == null) return; // nothing to copy
   final Bindings srcBindings = src.getBindings();
   final Bindings destBindings = dest.getBindings();
   for (final String key : src.getBindings().keySet()) {
     final Object value = src.getLanguage().decode(srcBindings.get(key));
     destBindings.put(key, value);
   }
 }
示例#5
0
 public void execute(Bindings bindings) {
   try {
     for (String key : bindings.keySet()) {
       engine.put(key, bindings.get(key));
     }
     compiledScript.eval();
   } catch (ScriptException e) {
     onScriptError(e);
     return;
   }
 }
示例#6
0
  /** Lists variables in the script context. */
  public void vars() {
    if (interpreter == null) return; // no active script language

    final List<String> keys = new ArrayList<>();
    final List<Object> types = new ArrayList<>();
    final Bindings bindings = interpreter.getBindings();
    for (final String key : bindings.keySet()) {
      final Object value = bindings.get(key);
      keys.add(key);
      types.add(type(value));
    }
    printColumns(keys, types);
  }
 private static void typeCastContextBindings(final ScriptContext context) {
   for (int scope : context.getScopes()) {
     Bindings bindings = context.getBindings(scope);
     if (!(bindings instanceof VariableLibrary) && null != bindings) {
       for (String key : bindings.keySet()) {
         Object object = bindings.get(key);
         if (object instanceof Atom) {
           bindings.put(key, ((Atom) object).getValue());
         }
       }
     }
   }
 }
示例#8
0
  @SuppressWarnings("rawtypes")
  // the caller is responsible for setting the task environment
  @Override
  protected Object evaluate(final ScriptEngine scriptEngine, final String script) {

    LOGGER.debug("evaluate called for {}", script);

    // Bindings bindings = new CustomEnvironmentBindings();
    // we can add any custom binding here if we override the EnvironmentBindings
    final Bindings bindings = new EnvironmentBindings(readContextNames, writeContextName);
    scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    if (!bindings.containsKey("task")) {
      LOGGER.warn("calling a script and no task in context, the script is [{}]", script);
    } else {
      LOGGER.info("got a task in the context >{}<", bindings.get("task"));
    }

    try {
      // we get a nullpointer exception if we have a comments only script, try to prevent this
      // by checking for a nullpointer clazz before calling eval on tne script engine:
      Class clazz = new GroovyClassLoader().parseClass(script);
      if (clazz == null) {
        LOGGER.debug("script parsed to null");
        return null;
      } else {
        final Object result = scriptEngine.eval(script);
        LOGGER.debug("script evaluated to {}", result);
        return result;
      }
    } catch (final Exception ex) {
      LOGGER.warn(
          "script error in script, the error is: {}, the script is: [{}], throwing error ",
          ex.getMessage(),
          script);
      throw new JbpmException("script evaluation error: " + ex.getMessage(), ex);
    }
  }
  @Override
  protected PicoContainer createContainerFromScript(
      final PicoContainer parentContainer, final Object assemblyScope) {
    Reader reader = null;
    ScriptEngine engine = null;
    final ScriptEngineManager mgr = new ScriptEngineManager();
    final ClassLoader oldClassLoader =
        AccessController.doPrivileged(
            new PrivilegedAction<ClassLoader>() {

              public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
              }
            });
    final ClassLoader newClassLoader = this.getClassLoader();
    try {
      if (applyCustomClassLoader()) {
        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {
              public Void run() {
                Thread.currentThread().setContextClassLoader(newClassLoader);
                return null;
              }
            });
      }

      engine = mgr.getEngineByName(engineName);
      if (engine == null) {
        final StringBuilder message =
            new StringBuilder(
                "Could not find a script engine named: '"
                    + engineName
                    + "' all script engines in your classpath are:\n");
        for (final ScriptEngineFactory eachFactory : mgr.getEngineFactories()) {
          message.append(
              "\t Engine named '"
                  + eachFactory.getEngineName()
                  + "' which supports the language '"
                  + eachFactory.getLanguageName()
                  + "' with short names '"
                  + Arrays.toString(eachFactory.getNames().toArray())
                  + "'\n");
        }

        throw new PicoCompositionException(message.toString());
      }

      final Bindings bindings = engine.createBindings();
      bindings.put("parent", parentContainer);
      bindings.put("assemblyScope", assemblyScope);
      applyOtherBindings(bindings);

      reader = this.getScriptReader();

      PicoContainer result = (PicoContainer) engine.eval(reader, bindings);
      if (result == null) {
        result = (PicoContainer) bindings.get("pico");
        if (result == null) {
          // Todo: remove as a deprecated variable name
          result = (PicoContainer) bindings.get("nano");
          if (result == null) {
            throw new PicoCompositionException(
                "Script completed successfully, but did not return any value, nor did it declare a variable named 'pico'");
          }
        }
      }
      return result;
    } catch (final ClassCastException e) {
      throw new ScriptedPicoContainerMarkupException(
          "The return type of the script must be of type PicoContainer", e);
    } catch (final IOException e) {
      throw new ScriptedPicoContainerMarkupException(
          "IOException encountered, message -'" + e.getMessage() + "'", e);
    } catch (final ScriptException e) {
      throw new ScriptedPicoContainerMarkupException(
          "Error executing composition script under engine '"
              + engine.getFactory().getEngineName()
              + "'",
          e);
    } finally {
      if (applyCustomClassLoader()) {
        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {

              public Void run() {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
                return null;
              }
            });
      }

      if (reader != null) {
        try {
          reader.close();
        } catch (final IOException e) {
          // Ignore
        }
      }
    }
  }
 private Object execute(final String script) throws Exception {
   final Bindings bindings = this.engine.createBindings();
   this.engine.eval(script, bindings);
   return bindings.get("result");
 }