Java Code Examples for groovy.lang.Script#setBinding()

The following examples show how to use groovy.lang.Script#setBinding() . 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: GroovyTest.java    From streamline with Apache License 2.0 7 votes vote down vote up
@Test
public void testGroovyShell() throws Exception {
    GroovyShell groovyShell = new GroovyShell();
    final String s = "x  > 2  &&  y  > 1";
    Script script = groovyShell.parse(s);

    Binding binding = new Binding();
    binding.setProperty("x",5);
    binding.setProperty("y",3);
    script.setBinding(binding);

    Object result = script.run();
    Assert.assertEquals(true, result);
    log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s,
            script.getBinding().getProperty("x"), script.getBinding().getProperty("y"), result);

    binding.setProperty("y",0);
    result = script.run();
    Assert.assertEquals(false, result);
    log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s,
            binding.getProperty("x"), binding.getProperty("y"), result);
}
 
Example 2
Source File: JMeterScriptProcessor.java    From jsflight with Apache License 2.0 6 votes vote down vote up
/**
 * Post process every stored request just before it get saved to disk
 *
 * @param sampler recorded http-request (sampler)
 * @param tree   HashTree (XML like data structure) that represents exact recorded sampler
 */
public void processScenario(HTTPSamplerBase sampler, HashTree tree, Arguments userVariables, JMeterRecorder recorder)
{
    Binding binding = new Binding();
    binding.setVariable(ScriptBindingConstants.LOGGER, LOG);
    binding.setVariable(ScriptBindingConstants.SAMPLER, sampler);
    binding.setVariable(ScriptBindingConstants.TREE, tree);
    binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext());
    binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance());
    binding.setVariable(ScriptBindingConstants.USER_VARIABLES, userVariables);
    binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader);

    Script compiledProcessScript = ScriptEngine.getScript(getScenarioProcessorScript());
    if (compiledProcessScript == null)
    {
        return;
    }
    compiledProcessScript.setBinding(binding);
    LOG.info("Run compiled script");
    try {
        compiledProcessScript.run();
    } catch (Throwable throwable) {
        LOG.error(throwable.getMessage(), throwable);
    }
}
 
Example 3
Source File: ExpressionLanguageGroovyImpl.java    From oval with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
   LOG.debug("Evaluating Groovy expression: {1}", expression);
   try {
      final Script script = expressionCache.get().get(expression);

      final Binding binding = new Binding();
      for (final Entry<String, ?> entry : values.entrySet()) {
         binding.setVariable(entry.getKey(), entry.getValue());
      }
      script.setBinding(binding);
      return script.run();
   } catch (final Exception ex) {
      throw new ExpressionEvaluationException("Evaluating script with Groovy failed.", ex);
   }
}
 
Example 4
Source File: FactoryBuilderSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
public Object build(Script script) {
    // this used to be synchronized, but we also used to remove the
    // metaclass.  Since adding the metaclass is now a side effect, we
    // don't need to ensure the meta-class won't be observed and don't
    // need to hide the side effect.
    MetaClass scriptMetaClass = script.getMetaClass();
    script.setMetaClass(new FactoryInterceptorMetaClass(scriptMetaClass, this));
    script.setBinding(this);
    Object oldScriptName = getProxyBuilder().getVariables().get(SCRIPT_CLASS_NAME);
    try {
        getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, script.getClass().getName());
        return script.run();
    } finally {
        if(oldScriptName != null) {
            getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, oldScriptName);
        } else {
            getProxyBuilder().getVariables().remove(SCRIPT_CLASS_NAME);
        }
    }
}
 
Example 5
Source File: GroovyScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 5 votes vote down vote up
private groovy.lang.Script createScript(Object compiledScript, Map<String, Object> vars) throws Exception {
    Class<?> scriptClass = (Class<?>)compiledScript;
    Script scriptObject = (Script)scriptClass.getConstructor().newInstance();
    Binding binding = new Binding();
    binding.getVariables().putAll(vars);
    scriptObject.setBinding(binding);
    return scriptObject;
}
 
Example 6
Source File: ScriptManagerImpl.java    From jira-groovioli with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Object executeScript(String groovyScript, Map<String, Object> parameters) throws ScriptException {
    try {
        Script script = scriptCache.get(groovyScript);
        script.setBinding(fromMap(parameters));
        return script.run();
    } catch (ExecutionException ex) {
        throw new ScriptException("Error executing groovy script", ex);
    }
}
 
Example 7
Source File: TransformActivity.java    From mdw with Apache License 2.0 5 votes vote down vote up
private void executeGPath() throws ActivityException {
    String transform = (String) getAttributeValue(RULE);
    if (StringUtils.isBlank(transform)) {
        getLogger().info("No transform defined for activity: " + getActivityName());
        return;
    }

    GroovyShell shell = new GroovyShell(getClass().getClassLoader());
    Script script = shell.parse(transform);
    Binding binding = new Binding();

    Variable inputVar = getMainProcessDefinition().getVariable(inputDocument);
    if (inputVar == null)
      throw new ActivityException("Input document variable not found: " + inputDocument);
    String inputVarName = inputVar.getName();
    Object inputVarValue = getGPathParamValue(inputVarName, inputVar.getType());
    binding.setVariable(inputVarName, inputVarValue);

    Variable outputVar = getMainProcessDefinition().getVariable(getOutputDocuments()[0]);
    String outputVarName = outputVar.getName();
    Object outputVarValue = getGPathParamValue(outputVarName, outputVar.getType());
    binding.setVariable(outputVarName, outputVarValue);

    script.setBinding(binding);

    script.run();

    Object groovyVarValue = binding.getVariable(outputVarName);
    setGPathParamValue(outputVarName, outputVar.getType(), groovyVarValue);
}
 
Example 8
Source File: JMeterScriptProcessor.java    From jsflight with Apache License 2.0 5 votes vote down vote up
/**
 * Post process sample with groovy script.
 *
 * @param sampler
 * @param result
 * @param recorder
 * @return is sample ok
 */
public boolean processSampleDuringRecord(HTTPSamplerBase sampler, SampleResult result, JMeterRecorder recorder)
{
    Binding binding = new Binding();
    binding.setVariable(ScriptBindingConstants.LOGGER, LOG);
    binding.setVariable(ScriptBindingConstants.SAMPLER, sampler);
    binding.setVariable(ScriptBindingConstants.SAMPLE, result);
    binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext());
    binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance());
    binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader);

    Script script = ScriptEngine.getScript(getStepProcessorScript());
    if (script == null)
    {
        LOG.warn(sampler.getName() + ". No script found. Default result is " + SHOULD_BE_PROCESSED_DEFAULT);
        return SHOULD_BE_PROCESSED_DEFAULT;
    }
    script.setBinding(binding);
    LOG.info(sampler.getName() + ". Running compiled script");
    Object scriptResult = script.run();

    boolean shouldBeProcessed;
    if (scriptResult != null && scriptResult instanceof Boolean)
    {
        shouldBeProcessed = (boolean)scriptResult;
        LOG.info(sampler.getName() + ". Script result " + shouldBeProcessed);
    }
    else
    {
        shouldBeProcessed = SHOULD_BE_PROCESSED_DEFAULT;
        LOG.warn(sampler.getName() + ". Script result UNDEFINED. Default result is " + SHOULD_BE_PROCESSED_DEFAULT);
    }

    return shouldBeProcessed;
}
 
Example 9
Source File: DeploymentTest.java    From vertx-lang-groovy with Apache License 2.0 5 votes vote down vote up
@Test
public void testReuseBindingInScript() throws Exception {
  Class clazz = assertScript("ReuseBindingVerticleScript");
  Script script = (Script) clazz.newInstance();
  Binding binding = new Binding();
  binding.setVariable("myobject", new Object());
  script.setBinding(binding);
  ScriptVerticle verticle = new ScriptVerticle(script);
  assertDeploy((vertx, onDeploy) ->
      vertx.deployVerticle(verticle, onDeploy));
  assertTrue(isStarted());
}
 
Example 10
Source File: TestGroovyCapabilityBindings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
public void testCompile() throws Exception {
   CompilerConfiguration config = new CompilerConfiguration();
   config.setTargetDirectory(new File(TMP_DIR));
   config.addCompilationCustomizers(new DriverCompilationCustomizer(ServiceLocator.getInstance(CapabilityRegistry.class)));
   org.codehaus.groovy.tools.Compiler compiler = new org.codehaus.groovy.tools.Compiler(config);
   compiler.compile(new File("src/test/resources/Metadata.capability"));
   ClassLoader loader = new ClassLoader() {

      @Override
      protected Class<?> findClass(String name) throws ClassNotFoundException {
         File f = new File(TMP_DIR + "/" + name.replaceAll("\\.", "/") + ".class");
         if(!f.exists()) {
            throw new ClassNotFoundException();
         }
         try (FileInputStream is = new FileInputStream(f)) {
            byte [] bytes = IOUtils.toByteArray(is);
            return defineClass(name, bytes, 0, bytes.length);
         }
         catch(Exception e) {
            throw new ClassNotFoundException("Unable to load " + name, e);
         }
      }

   };
   Class<?> metadataClass = loader.loadClass("Metadata");
   System.out.println(metadataClass);
   System.out.println("Superclass: " + metadataClass.getSuperclass());
   System.out.println("Interfaces: " + Arrays.asList(metadataClass.getInterfaces()));
   System.out.println("Methods: ");
   for(Method m: Arrays.asList(metadataClass.getMethods())) {
      System.out.println("\t" + m);
   }

   GroovyCapabilityBuilder builder =
         new GroovyCapabilityBuilder(ServiceLocator.getInstance(CapabilityRegistry.class))
            .withName("Metadata");
   CapabilityEnvironmentBinding binding = new CapabilityEnvironmentBinding(builder);
   Script s = (Script) metadataClass.getConstructor(Binding.class).newInstance(binding);
   s.setMetaClass(new CapabilityScriptMetaClass(s.getClass()));
   s.getMetaClass().initialize();
   s.setBinding(binding);
   s.run();
   System.out.println("Definition: " + builder.create().getCapabilityDefinition());
}
 
Example 11
Source File: TestGroovyDriverBindings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
//   @Ignore
   public void testCompile() throws Exception {
      CapabilityRegistry registry = ServiceLocator.getInstance(CapabilityRegistry.class);

      CompilerConfiguration config = new CompilerConfiguration();
      config.setTargetDirectory(new File(TMP_DIR));
      config.addCompilationCustomizers(new DriverCompilationCustomizer(registry));
      org.codehaus.groovy.tools.Compiler compiler = new org.codehaus.groovy.tools.Compiler(config);
      compiler.compile(new File("src/test/resources/Metadata.driver"));
      ClassLoader loader = new ClassLoader() {

         @Override
         protected Class<?> findClass(String name) throws ClassNotFoundException {
            File f = new File(TMP_DIR + "/" + name.replaceAll("\\.", "/") + ".class");
            if(!f.exists()) {
               throw new ClassNotFoundException();
            }
            try (FileInputStream is = new FileInputStream(f)) {
               byte [] bytes = IOUtils.toByteArray(is);
               return defineClass(name, bytes, 0, bytes.length);
            }
            catch(Exception e) {
               throw new ClassNotFoundException("Unable to load " + name, e);
            }
         }

      };
      Class<?> metadataClass = loader.loadClass("Metadata");
      System.out.println(metadataClass);
      System.out.println("Superclass: " + metadataClass.getSuperclass());
      System.out.println("Interfaces: " + Arrays.asList(metadataClass.getInterfaces()));
      System.out.println("Methods: ");
      for(Method m: Arrays.asList(metadataClass.getMethods())) {
         System.out.println("\t" + m);
      }

      GroovyScriptEngine engine = new GroovyScriptEngine(new ClasspathResourceConnector());
      engine.setConfig(config);
      DriverBinding binding = new DriverBinding(
            ServiceLocator.getInstance(CapabilityRegistry.class),
            new GroovyDriverFactory(engine, registry, ImmutableSet.of(new ControlProtocolPlugin()))
      );
      Script s = (Script) metadataClass.getConstructor(Binding.class).newInstance(binding);
      s.setMetaClass(new DriverScriptMetaClass(s.getClass()));
      s.setBinding(binding);
      s.run();
      System.out.println("Definition: " + binding.getBuilder().createDefinition());
   }
 
Example 12
Source File: OperationGroovy.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Execute operation: load each imported groovy class file, instantiate each
 * groovy class, inject these instances in the groovy operation script, and
 * finally execute the groovy operation script
 *
 * @param runner
 * @return Next operation or null by default
 */
@Override
public Operation execute(Runner runner) throws Exception {
    if (runner instanceof ScenarioRunner) {
        GlobalLogger.instance().getSessionLogger().info(runner, TextEvent.Topic.CORE, this);
    } else {
        GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE, this);
    }

    // retrieve the list of groovy files to load
    String groovyFiles = getRootElement().attributeValue("name");

    // retrieve the groovy operation script source
    String scriptSource = getRootElement().getText();

    try {
        // instantiate the binding which manage the exchange of variables
        // between groovy scripts and MTS runner:
        MTSBinding mtsBinding = new MTSBinding(runner);

        // instantiate the classloader in charge of groovy scripts
        CompilerConfiguration compilerConfig = new CompilerConfiguration();
        compilerConfig.setScriptBaseClass("MTSScript");

        ClassLoader mtsClassLoader = getClass().getClassLoader();
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader(mtsClassLoader, compilerConfig);

        // load, instantiate and execute each groovy file,
        if (groovyFiles != null) {
            StringTokenizer st = new StringTokenizer(groovyFiles, ";");
            while (st.hasMoreTokens()) {
                String scriptName = st.nextToken();
                File file = new File(URIRegistry.MTS_TEST_HOME.resolve(scriptName));
                if (file.exists() && file.getName().endsWith(".groovy")) {
                    Class groovyClass = groovyClassLoader.parseClass(file);
                    Object obj = groovyClass.newInstance();
                    if (obj instanceof Script) {
                        // add the MTS Binding and execute the run method
                        ((Script) obj).setBinding(mtsBinding);
                        ((Script) obj).invokeMethod("run", new Object[]{});
                        prepareScriptProperties(runner, scriptName, (Script) obj);
                    }
                } else {
                    if (runner instanceof ScenarioRunner) {
                        GlobalLogger.instance().getSessionLogger().error(runner, TextEvent.Topic.CORE,
                                "invalid groovy file " + scriptName);
                    } else {
                        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE,
                                "invalid groovy file " + scriptName);
                    }
                }
            }
        }
        groovyClassLoader.close();

        // instantiate the groovy operation script
        Class scriptClass = groovyClassLoader.parseClass(scriptSource);
        Script script = (Script) scriptClass.newInstance();
        script.setBinding(mtsBinding);

        // inject each imported groovy class as a property of the groovy
        // operation script
        injectScriptProperties(script);

        // execute the groovy operation script
        Object result = script.run();

    } catch (AssertionError pae) {
        GlobalLogger.instance().getSessionLogger().error(runner, TextEvent.Topic.CORE, pae.getMessage(), scriptSource);
        throw new ExecutionException("Error in groovy test", pae);

    } catch (Exception e) {
        GlobalLogger.instance().getSessionLogger().error(runner, TextEvent.Topic.CORE, scriptSource,
                "Exception occured\n", e);
        throw new ExecutionException("Error executing groovy operation command", e);
    }

    return null;
}
 
Example 13
Source File: GroovyCodeRunner.java    From beakerx with Apache License 2.0 4 votes vote down vote up
private Object runScript(Script script) {
  groovyEvaluator.getScriptBinding().setVariable(Evaluator.BEAKER_VARIABLE_NAME, groovyEvaluator.getBeakerX());
  script.setBinding(groovyEvaluator.getScriptBinding());
  return script.run();
}