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

The following examples show how to use groovy.lang.Script#run() . 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: SecurityTestSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected void executeScript(Class scriptClass, Permission missingPermission) {
    try {
        Script script = InvokerHelper.createScript(scriptClass, new Binding());
        script.run();
        //InvokerHelper.runScript(scriptClass, null);
    } catch (AccessControlException ace) {
        if (missingPermission != null && missingPermission.implies(ace.getPermission())) {
            return;
        } else {
            fail(ace.toString());
        }
    }
    if (missingPermission != null) {
        fail("Should catch an AccessControlException");
    }
}
 
Example 3
Source File: CachingGroovyEngine.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate an expression.
 */
public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
        Class scriptClass = evalScripts.get(script);
        if (scriptClass == null) {
            scriptClass = loader.parseClass(script.toString(), source);
            evalScripts.put(script, scriptClass);
        } else {
            LOG.fine("eval() - Using cached script...");
        }
        //can't cache the script because the context may be different.
        //but don't bother loading parsing the class again
        Script s = InvokerHelper.createScript(scriptClass, context);
        return s.run();
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
}
 
Example 4
Source File: GroovySlide.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Component getComponent(int width, int height) throws IOException {
	final JPanel base = new JPanel();
	base.setOpaque(false);
	base.setPreferredSize(new Dimension(width, height));
	base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

	final Binding sharedData = new Binding();
	final GroovyShell shell = new GroovyShell(sharedData);
	sharedData.setProperty("slidePanel", base);
	final Script script = shell.parse(new InputStreamReader(GroovySlide.class.getResourceAsStream("../test.groovy")));
	script.run();

	// final RSyntaxTextArea textArea = new RSyntaxTextArea(20, 60);
	// textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_GROOVY);
	// textArea.setCodeFoldingEnabled(true);
	// final RTextScrollPane sp = new RTextScrollPane(textArea);
	// base.add(sp);

	return base;
}
 
Example 5
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 6
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 7
Source File: GroovyExecutor.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public GroovyResult execute(GroovyResult result, final Script groovyScript, final Map<String, Object> variables)
{
  if (variables != null) {
    final Binding binding = groovyScript.getBinding();
    for (final Map.Entry<String, Object> entry : variables.entrySet()) {
      binding.setVariable(entry.getKey(), entry.getValue());
    }
  }
  if (result == null) {
    result = new GroovyResult();
  }
  Object res = null;
  try {
    res = groovyScript.run();
  } catch (final Exception ex) {
    log.info("Groovy-Execution-Exception: " + ex.getMessage(), ex);
    return new GroovyResult(ex);
  }
  result.setResult(res);
  return result;
}
 
Example 8
Source File: TestSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void assertScript(final String text, final String scriptName) throws Exception {
    log.info("About to execute script");
    log.info(text);
    GroovyCodeSource gcs = AccessController.doPrivileged(
            (PrivilegedAction<GroovyCodeSource>) () -> new GroovyCodeSource(text, scriptName, "/groovy/testSupport")
    );
    Class groovyClass = loader.parseClass(gcs);
    Script script = InvokerHelper.createScript(groovyClass, new Binding());
    script.run();
}
 
Example 9
Source File: GroovyInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public InterpreterResult interpret(String cmd, InterpreterContext contextInterpreter) {
  try {
    Script script = getGroovyScript(contextInterpreter.getParagraphId(), cmd);
    Job runningJob = getRunningJob(contextInterpreter.getParagraphId());
    runningJob.info()
        .put("CURRENT_THREAD", Thread.currentThread()); //to be able to terminate thread
    Map<String, Object> bindings = script.getBinding().getVariables();
    bindings.clear();
    StringWriter out = new StringWriter((int) (cmd.length() * 1.75));
    //put shared bindings evaluated in this interpreter
    bindings.putAll(sharedBindings);
    //put predefined bindings
    bindings.put("g", new GObject(log, out, this.getProperties(), contextInterpreter, bindings));
    bindings.put("out", new PrintWriter(out, true));

    script.run();
    //let's get shared variables defined in current script and store them in shared map
    for (Map.Entry<String, Object> e : bindings.entrySet()) {
      if (!predefinedBindings.contains(e.getKey())) {
        if (log.isTraceEnabled()) {
          log.trace("groovy script variable " + e);  //let's see what we have...
        }
        sharedBindings.put(e.getKey(), e.getValue());
      }
    }

    bindings.clear();
    InterpreterResult result = new InterpreterResult(Code.SUCCESS, out.toString());
    return result;
  } catch (Throwable t) {
    t = StackTraceUtils.deepSanitize(t);
    String msg = t.toString() + "\n at " + t.getStackTrace()[0];
    log.error("Failed to run script: " + t + "\n" + cmd + "\n", t);
    return new InterpreterResult(Code.ERROR, msg);
  }
}
 
Example 10
Source File: PuzzleBuildingBlock.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
/**
 * processes all expressions and updates properties
 */
private void processExpressions() {
	boolean notificationRequired = false;
	for (Map.Entry<String, Script> entry : definitions.entrySet()) {
		String variable = entry.getKey();
		Script script = entry.getValue();
		Object value = script.run();
		if (putInternal(variable, value)) {
			notificationRequired = true;
		}
	}
	if (notificationRequired) {
		PuzzleEventDispatcher.get().notify(this);
	}
}
 
Example 11
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 12
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 13
Source File: TestCaseRun.java    From mdw with Apache License 2.0 5 votes vote down vote up
public void run() {
    startExecution();
    try {
        if (testCase.getAsset().getExtension().equals("postman")) {
            String runnerClass = NODE_PACKAGE + ".TestRunner";
            Package pkg = PackageCache.getPackage(testCase.getPackage());
            Class<?> testRunnerClass = CompiledJavaCache.getResourceClass(runnerClass, getClass().getClassLoader(), pkg);
            Object runner = testRunnerClass.newInstance();
            Method runMethod = testRunnerClass.getMethod("run", TestCase.class);
            runMethod.invoke(runner, testCase);
            finishExecution(null);
        }
        else {
            String groovyScript = testCase.getText();
            CompilerConfiguration compilerConfig = new CompilerConfiguration();
            compilerConfig.setScriptBaseClass(TestCaseScript.class.getName());

            Binding binding = new Binding();
            binding.setVariable("testCaseRun", this);

            ClassLoader classLoader = this.getClass().getClassLoader();
            Package testPkg = PackageCache.getPackage(testCase.getPackage());
            if (testPkg != null)
                classLoader = testPkg.getClassLoader();

            GroovyShell shell = new GroovyShell(classLoader, binding, compilerConfig);
            Script gScript = shell.parse(groovyScript);
            gScript.setProperty("out", log);
            gScript.run();
            finishExecution(null);
        }
    }
    catch (Throwable ex) {
        finishExecution(ex);
    }
}
 
Example 14
Source File: GroovyUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static Object runScriptAtLocation(String location, String methodName, Map<String, Object> context) throws GeneralException {
    if (!baseScriptInitialized) { initBaseScript(); } // SCIPIO
    Script script = InvokerHelper.createScript(getScriptClassFromLocation(location), getBinding(context));
    Object result = null;
    if (UtilValidate.isEmpty(methodName)) {
        result = script.run();
    } else {
        result = script.invokeMethod(methodName, new Object[] { context });
    }
    return result;
}
 
Example 15
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 16
Source File: RouteRuleFilter.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
public Map<String,Object> filter(Map<String,Object> input) {

    Binding binding = new Binding();
    binding.setVariable("input", input);

    GroovyShell shell = new GroovyShell(binding);
    
    String filterScript = "def field = input.get('field')\n"
                                  + "if (input.field == 'buyer') { return ['losDataBusinessName':'losESDataBusiness3', 'esIndex':'potential_goods_recommend1']}\n"
                                  + "if (input.field == 'seller') { return ['losDataBusinessName':'losESDataBusiness4', 'esIndex':'potential_goods_recommend2']}\n";
    Script script = shell.parse(filterScript);
    Object ret = script.run();
    System.out.println(ret);
    return (Map<String, Object>) ret;
}
 
Example 17
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();
}
 
Example 18
Source File: GroovyEngine.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
private Map<String, Object> serviceInvoker(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException {
    if (UtilValidate.isEmpty(modelService.location)) {
        throw new GenericServiceException("Cannot run Groovy service with empty location");
    }
    Map<String, Object> params = new HashMap<>();
    params.putAll(context);

    Map<String, Object> gContext = new HashMap<>();
    gContext.putAll(context);
    gContext.put(ScriptUtil.PARAMETERS_KEY, params);

    DispatchContext dctx = dispatcher.getLocalContext(localName);
    gContext.put("dctx", dctx);
    gContext.put("security", dctx.getSecurity());
    gContext.put("dispatcher", dctx.getDispatcher());
    gContext.put("delegator", dispatcher.getDelegator());
    try {
        ScriptContext scriptContext = ScriptUtil.createScriptContext(gContext, protectedKeys);
        ScriptHelper scriptHelper = (ScriptHelper)scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
        if (scriptHelper != null) {
            gContext.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
        }
        Script script = InvokerHelper.createScript(GroovyUtil.getScriptClassFromLocation(this.getLocation(modelService)), GroovyUtil.getBinding(gContext));
        Object resultObj = null;
        if (UtilValidate.isEmpty(modelService.invoke)) {
            resultObj = script.run();
        } else {
            resultObj = script.invokeMethod(modelService.invoke, EMPTY_ARGS);
        }
        if (resultObj == null) {
            resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
        }
        if (resultObj != null && resultObj instanceof Map<?, ?>) {
            return cast(resultObj);
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.putAll(modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), ModelService.OUT_PARAM));
        return result;
    } catch (GeneralException ge) {
        throw new GenericServiceException(ge);
    } catch (Exception e) {
        // detailMessage can be null.  If it is null, the exception won't be properly returned and logged, and that will
        // make spotting problems very difficult.  Disabling this for now in favor of returning a proper exception.
        throw new GenericServiceException("Error running Groovy method [" + modelService.invoke + "] in Groovy file [" + modelService.location + "]: ", e);
    }
}
 
Example 19
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 20
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());
   }