Java Code Examples for groovy.lang.GroovyShell

The following are top voted examples for showing how to use groovy.lang.GroovyShell. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Reer   File: ApiGroovyCompiler.java   View source code 6 votes vote down vote up
private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.1")) < 0) {
        throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + "");
    }
    Binding binding = new Binding();
    binding.setVariable("configuration", configuration);

    CompilerConfiguration configuratorConfig = new CompilerConfiguration();
    ImportCustomizer customizer = new ImportCustomizer();
    customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
    configuratorConfig.addCompilationCustomizers(customizer);

    GroovyShell shell = new GroovyShell(binding, configuratorConfig);
    try {
        shell.evaluate(configScript);
    } catch (Exception e) {
        throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e);
    }
}
 
Example 2
Project: powsybl-core   File: GroovyScriptPostProcessor.java   View source code 6 votes vote down vote up
@Override
public void process(Network network, ComputationManager computationManager) throws Exception {
    if (Files.exists(script)) {
        LOGGER.debug("Execute groovy post processor {}", script);
        try (Reader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
            CompilerConfiguration conf = new CompilerConfiguration();

            Binding binding = new Binding();
            binding.setVariable("network", network);
            binding.setVariable("computationManager", computationManager);

            GroovyShell shell = new GroovyShell(binding, conf);
            shell.evaluate(reader);
        }
    }
}
 
Example 3
Project: powsybl-core   File: AbstractLoadFlowRulesEngineTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    network = createNetwork();
    ComputationManager computationManager = Mockito.mock(ComputationManager.class);
    LoadFlow loadFlow = Mockito.mock(LoadFlow.class);
    LoadFlowFactory loadFlowFactory = Mockito.mock(LoadFlowFactory.class);
    Mockito.when(loadFlowFactory.create(Mockito.any(Network.class), Mockito.any(ComputationManager.class), Mockito.anyInt()))
            .thenReturn(loadFlow);
    LoadFlowResult loadFlowResult = Mockito.mock(LoadFlowResult.class);
    Mockito.when(loadFlowResult.isOk())
            .thenReturn(true);
    Mockito.when(loadFlow.getName()).thenReturn("load flow mock");
    Mockito.when(loadFlow.run())
            .thenReturn(loadFlowResult);
    LoadFlowActionSimulatorObserver observer = createObserver();
    GroovyCodeSource src = new GroovyCodeSource(new InputStreamReader(getClass().getResourceAsStream(getDslFile())), "test", GroovyShell.DEFAULT_CODE_BASE);
    actionDb = new ActionDslLoader(src).load(network);
    engine = new LoadFlowActionSimulator(network, computationManager, new LoadFlowActionSimulatorConfig(LoadFlowFactory.class, 3, false), observer) {
        @Override
        protected LoadFlowFactory newLoadFlowFactory() {
            return loadFlowFactory;
        }
    };
}
 
Example 4
Project: cas-5.1.0   File: ReturnMappedAttributeReleasePolicy.java   View source code 6 votes vote down vote up
private static Object getGroovyAttributeValue(final String groovyScript,
                                              final Map<String, Object> resolvedAttributes) {
    try {
        final Binding binding = new Binding();
        final GroovyShell shell = new GroovyShell(binding);
        binding.setVariable("attributes", resolvedAttributes);
        binding.setVariable("logger", LOGGER);

        LOGGER.debug("Executing groovy script [{}] with attributes binding of [{}]",
                StringUtils.abbreviate(groovyScript, groovyScript.length() / 2), resolvedAttributes);
        final Object res = shell.evaluate(groovyScript);
        return res;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
 
Example 5
Project: sponge   File: GroovyKnowledgeBaseInterpreter.java   View source code 6 votes vote down vote up
@Override
protected void prepareInterpreter() {
    ImportCustomizer importCustomizer = new ImportCustomizer();

    PROCESSOR_CLASSES
            .forEach((interfaceClass, scriptClass) -> addImport(importCustomizer, scriptClass, interfaceClass.getSimpleName()));
    addImport(importCustomizer, GroovyPlugin.class, Plugin.class.getSimpleName());

    getStandardImportClasses().forEach(cls -> addImport(importCustomizer, cls));

    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.addCompilationCustomizers(importCustomizer);

    binding = createBinding();
    shell = new GroovyShell(binding, configuration);
    scripts = Collections.synchronizedList(new ArrayList<>());

    setVariable(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    setClasspath(getEngineOperations() != null ? getEngineOperations().getEngine() : null);
}
 
Example 6
Project: xmontiarc   File: GroovyInterpreter.java   View source code 6 votes vote down vote up
public static EObject interpret(String groovyScript) {
		EDataType data =  EcorePackage.eINSTANCE.getEString();				
		Binding binding = new Binding();

		//Binding setVariable allow to pass a variable from the moonti arc model to the groovy interpreter
		//binding.setVariable(name, value);
		
		 GroovyShell shell = new GroovyShell(binding);		    
		    Object result = shell.evaluate(groovyScript);
		    
		    //Binding.getVariable get the new value of this variable. 
//		    binding.getVariable(name)

		    
		    //		data.setName(""+(rand.nextInt(100)+1));
		data.setName(""+result);
		return data;
	}
 
Example 7
Project: geoxygene   File: ScriptingPrimitiveRenderer.java   View source code 6 votes vote down vote up
private GroovyShell getGroovyShell() {
  if (this.groovySh == null) {
    // add some default imports to the script
    ImportCustomizer defaultImports = new ImportCustomizer();
    defaultImports
        .addStarImports("fr.ign.cogit.geoxygene.appli.render.primitive");
    defaultImports
        .addStarImports("fr.ign.cogit.geoxygene.appli.render.operator");
    defaultImports.addStarImports("fr.ign.cogit.geoxygene.appli.render.gl");
    defaultImports.addStarImports("fr.ign.cogit.geoxygene.appli.render");
    defaultImports.addStarImports("fr.ign.cogit.geoxygene.function");
    defaultImports.addStaticStars("org.lwjgl.opengl.GL11");
    defaultImports.addStaticStars("java.lang.Math");
    defaultImports.addStarImports("javax.vecmath");
    defaultImports.addStarImports("java.awt");
    final CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(defaultImports);
    final Binding binding = this.getBinding();

    this.groovySh = new GroovyShell(binding, config);
  }
  return this.groovySh;
}
 
Example 8
Project: eldemo   File: RunPerform.java   View source code 6 votes vote down vote up
public static void runGroovy(int xmax, int ymax, int zmax) {
    Binding binding = new Binding();
    GroovyShell shell = new GroovyShell(binding);
    String expression = "x + y*2 - z";
    Integer result = 0;
    Date start = new Date();
    for (int xval = 0; xval < xmax; xval++) {
        for (int yval = 0; yval < ymax; yval++) {
            for (int zval = 0; zval <= zmax; zval++) {
                binding.setVariable("x", xval);
                binding.setVariable("y", yval);
                binding.setVariable("z", zval);
                Integer cal = (Integer) shell.evaluate(expression);
                result += cal;
            }
        }
    }
    Date end = new Date();
    System.out.println("Groovy:time is : " + (end.getTime() - start.getTime()) + ",result is " + result);
}
 
Example 9
Project: mdw   File: TestCaseScript.java   View source code 6 votes vote down vote up
/**
 * Matches according to GPath.
 */
public Closure<Boolean> gpath(final String condition) throws TestException {
    return new Closure<Boolean>(this, this) {
        @Override
        public Boolean call(Object request) {
            try {
                GPathResult gpathRequest = new XmlSlurper().parseText(request.toString());
                Binding binding = getBinding();
                binding.setVariable("request", gpathRequest);
                return (Boolean) new GroovyShell(binding).evaluate(condition);
            }
            catch (Exception ex) {
                ex.printStackTrace(getTestCaseRun().getLog());
                getTestCaseRun().getLog().println("Failed to parse request as XML/JSON. Stub response: " + AdapterActivity.MAKE_ACTUAL_CALL);
                return false;
            }
        }
    };
}
 
Example 10
Project: mdw   File: TestCaseScript.java   View source code 6 votes vote down vote up
/**
 * performs groovy substitutions with this as delegate and inherited bindings
 */
protected String substitute(String before) {
    if (before.indexOf("${") == -1)
        return before;
    // escape all $ not followed by curly braces on same line
    before = before.replaceAll("\\$(?!\\{)", "\\\\\\$");
    // escape all regex -> ${~
    before = before.replaceAll("\\$\\{~", "\\\\\\$\\{~");
    // escape all escaped newlines
    before = before.replaceAll("\\\\n", "\\\\\\\\\\n");
    before = before.replaceAll("\\\\r", "\\\\\\\\\\r");
    // escape all escaped quotes
    before = before.replaceAll("\\\"", "\\\\\"");

    CompilerConfiguration compilerCfg = new CompilerConfiguration();
    compilerCfg.setScriptBaseClass(DelegatingScript.class.getName());
    GroovyShell shell = new GroovyShell(TestCaseScript.class.getClassLoader(), getBinding(), compilerCfg);
    DelegatingScript script = (DelegatingScript) shell.parse("return \"\"\"" + before + "\"\"\"");
    script.setDelegate(TestCaseScript.this);
    // restore escaped \$ to $ for comparison
    return script.run().toString().replaceAll("\\\\$", "\\$");
}
 
Example 11
Project: mdw   File: StandaloneTestCaseRun.java   View source code 6 votes vote down vote up
/**
 * Standalone execution for Designer and Gradle.
 */
public void run() {
    startExecution();

    CompilerConfiguration compilerConfig = new CompilerConfiguration(System.getProperties());
    compilerConfig.setScriptBaseClass(TestCaseScript.class.getName());
    Binding binding = new Binding();
    binding.setVariable("testCaseRun", this);

    ClassLoader classLoader = this.getClass().getClassLoader();
    GroovyShell shell = new GroovyShell(classLoader, binding, compilerConfig);
    shell.setProperty("out", getLog());
    setupContextClassLoader(shell);
    try {
        shell.run(new GroovyCodeSource(getTestCase().file()), new String[0]);
        finishExecution(null);
    }
    catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
 
Example 12
Project: mdw   File: StandaloneTestCaseRun.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void setupContextClassLoader(GroovyShell shell) {
    final Thread current = Thread.currentThread();
    @SuppressWarnings("rawtypes")
    class DoSetContext implements PrivilegedAction {
        ClassLoader classLoader;
        public DoSetContext(ClassLoader loader) {
            classLoader = loader;
        }
        public Object run() {
            current.setContextClassLoader(classLoader);
            return null;
        }
    }
    AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}
 
Example 13
Project: mdw   File: CrossmapActivity.java   View source code 6 votes vote down vote up
/**
 * Returns the builder object for creating new output variable value.
 */
protected void runScript(String mapperScript, Slurper slurper, Builder builder)
        throws ActivityException, TransformerException {

    CompilerConfiguration compilerConfig = new CompilerConfiguration();
    compilerConfig.setScriptBaseClass(CrossmapScript.class.getName());

    Binding binding = new Binding();
    binding.setVariable("runtimeContext", getRuntimeContext());
    binding.setVariable(slurper.getName(), slurper.getInput());
    binding.setVariable(builder.getName(), builder);
    GroovyShell shell = new GroovyShell(getPackage().getCloudClassLoader(), binding, compilerConfig);
    Script gScript = shell.parse(mapperScript);
    // gScript.setProperty("out", getRuntimeContext().get);
    gScript.run();
}
 
Example 14
Project: dsl   File: CheckRuleDsl.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    List<String> rules = Lists.newArrayList();
    rules.add("S <= 10");
    rules.add("S + A <= 20");
    rules.add("S + A + BP <= 55");
    rules.add("C >= 5");

    Binding binding = new Binding();
    binding.setVariable("S", 5.0);
    binding.setVariable("A", 5.0);
    binding.setVariable("BP", 30.0);
    binding.setVariable("B", 30.0);
    binding.setVariable("C", 30.0);
    GroovyShell shell = new GroovyShell(binding);
    for (String rule : rules) {
        Object result = shell.evaluate(rule);
        System.out.println(result);
    }
}
 
Example 15
Project: intellij-ce-playground   File: DependentGroovycRunner.java   View source code 6 votes vote down vote up
private static void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
  Binding binding = new Binding();
  binding.setVariable("configuration", configuration);

  CompilerConfiguration configuratorConfig = new CompilerConfiguration();
  ImportCustomizer customizer = new ImportCustomizer();
  customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
  configuratorConfig.addCompilationCustomizers(customizer);

  try {
    new GroovyShell(binding, configuratorConfig).evaluate(configScript);
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 16
Project: ontrack-plugin   File: AbstractDSLLauncher.java   View source code 6 votes vote down vote up
@Override
public Object run(String dsl, Binding binding) {
    CompilerConfiguration compilerConfiguration = prepareCompilerConfiguration();
    ClassLoader classLoader = prepareClassLoader(AbstractDSLLauncher.class.getClassLoader());
    GroovyCodeSource groovyCodeSource = prepareGroovyCodeSource(dsl);

    // Groovy shell
    GroovyShell shell = new GroovyShell(
            classLoader,
            new Binding(),
            compilerConfiguration
    );

    // Groovy script
    Script groovyScript = shell.parse(groovyCodeSource);

    // Binding
    groovyScript.setBinding(binding);

    // Runs the script
    return run(groovyScript);
}
 
Example 17
Project: FinanceAnalytics   File: SimulationUtils.java   View source code 6 votes vote down vote up
/**
 * Runs a Groovy DSL script and returns the value returned by the script.
 * @param scriptReader For reading the script text
 * @param expectedType The expected type of the return value
 * @param parameters Parameters used by the script, null or empty if the script doesn't need any
 * @param <T> The expected type of the return value
 * @return The return value of the script, not null
 */
private static <T> T runGroovyDslScript(Reader scriptReader, Class<T> expectedType, Map<String, Object> parameters) {
  Map<String, Object> timeoutArgs = ImmutableMap.<String, Object>of("value", 2);
  ASTTransformationCustomizer customizer = new ASTTransformationCustomizer(timeoutArgs, TimedInterrupt.class);
  CompilerConfiguration config = new CompilerConfiguration();
  config.addCompilationCustomizers(customizer);
  config.setScriptBaseClass(SimulationScript.class.getName());
  Map<String, Object> bindingMap = parameters == null ? Collections.<String, Object>emptyMap() : parameters;
  //copy map to ensure that binding is mutable (for use in registerAliases)
  Binding binding = new Binding(Maps.newHashMap(bindingMap));
  registerAliases(binding);
  GroovyShell shell = new GroovyShell(binding, config);
  Script script = shell.parse(scriptReader);
  Object scriptOutput = script.run();
  if (scriptOutput == null) {
    throw new IllegalArgumentException("Script " + scriptReader + " didn't return an object");
  }
  if (expectedType.isInstance(scriptOutput)) {
    return expectedType.cast(scriptOutput);
  } else {
    throw new IllegalArgumentException("Script '" + scriptReader + "' didn't create an object of the expected type. " +
        "expected type: " + expectedType.getName() + ", " +
        "actual type: " + scriptOutput.getClass().getName() + ", " +
        "actual value: " + scriptOutput);
  }
}
 
Example 18
Project: stendhal   File: ConditionAndActionPortalFactory.java   View source code 6 votes vote down vote up
/**
 * Extract the quest name from a context.
 * 
 * @param ctx
 *            The configuration context.
 * @return The quest name.
 * @throws IllegalArgumentException
 *             If the quest attribute is missing.
 */
protected ChatCondition getCondition(final ConfigurableFactoryContext ctx) {
	String value = ctx.getString("condition", null);
	if (value == null) {
		return null;
	}
	Binding groovyBinding = new Binding();
	final GroovyShell interp = new GroovyShell(groovyBinding);
	try {
		String code = "import games.stendhal.server.entity.npc.condition.*;\r\n"
			+ value;
		return (ChatCondition) interp.evaluate(code);
	} catch (CompilationFailedException e) {
		throw new IllegalArgumentException(e);
	}
}
 
Example 19
Project: stendhal   File: ConditionAndActionPortalFactory.java   View source code 6 votes vote down vote up
/**
 * Extract the quest name from a context.
 * 
 * @param ctx
 *            The configuration context.
 * @return The quest name.
 * @throws IllegalArgumentException
 *             If the quest attribute is missing.
 */
protected ChatAction getAction(final ConfigurableFactoryContext ctx) {
	String value = ctx.getString("action", null);
	if (value == null) {
		return null;
	}
	Binding groovyBinding = new Binding();
	final GroovyShell interp = new GroovyShell(groovyBinding);
	try {
		String code = "import games.stendhal.server.entity.npc.action.*;\r\n"
			+ value;
		return (ChatAction) interp.evaluate(code);
	} catch (CompilationFailedException e) {
		throw new IllegalArgumentException(e);
	}
}
 
Example 20
Project: zeppelin   File: GroovyInterpreter.java   View source code 6 votes vote down vote up
@Override
public void open() {
  CompilerConfiguration conf = new CompilerConfiguration();
  conf.setDebug(true);
  shell = new GroovyShell(conf);
  String classes = getProperty("GROOVY_CLASSES");
  if (classes == null || classes.length() == 0) {
    try {
      File jar = new File(
          GroovyInterpreter.class.getProtectionDomain().getCodeSource().getLocation().toURI()
              .getPath());
      classes = new File(jar.getParentFile(), "classes").toString();
    } catch (Exception e) {
    }
  }
  log.info("groovy classes classpath: " + classes);
  if (classes != null && classes.length() > 0) {
    File fClasses = new File(classes);
    if (!fClasses.exists()) {
      fClasses.mkdirs();
    }
    shell.getClassLoader().addClasspath(classes);
  }
}
 
Example 21
Project: groovy   File: Groovy.java   View source code 6 votes vote down vote up
private void configureCompiler() {
    if (scriptBaseClass!=null) {
        configuration.setScriptBaseClass(scriptBaseClass);
    }
    if (indy) {
        configuration.getOptimizationOptions().put("indy", Boolean.TRUE);
        configuration.getOptimizationOptions().put("int", Boolean.FALSE);
    }
    if (configscript!=null) {
        Binding binding = new Binding();
        binding.setVariable("configuration", configuration);

        CompilerConfiguration configuratorConfig = new CompilerConfiguration();
        ImportCustomizer customizer = new ImportCustomizer();
        customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
        configuratorConfig.addCompilationCustomizers(customizer);

        GroovyShell shell = new GroovyShell(binding, configuratorConfig);
        File confSrc = new File(configscript);
        try {
            shell.evaluate(confSrc);
        } catch (IOException e) {
            throw new BuildException("Unable to configure compiler using configuration file: "+confSrc, e);
        }
    }
}
 
Example 22
Project: groovy   File: GroovyAssert.java   View source code 6 votes vote down vote up
/**
 * Asserts that the given script fails when it is evaluated
 * and that a particular type of exception is thrown.
 *
 * @param clazz the class of the expected exception
 * @param script  the script that should fail
 * @return the caught exception
 */
public static Throwable shouldFail(Class clazz, String script) {
    Throwable th = null;
    try {
        GroovyShell shell = new GroovyShell();
        shell.evaluate(script, genericScriptName());
    } catch (GroovyRuntimeException gre) {
        th = ScriptBytecodeAdapter.unwrap(gre);
    } catch (Throwable e) {
        th = e;
    }

    if (th == null) {
        fail("Script should have failed with an exception of type " + clazz.getName());
    } else if (!clazz.isInstance(th)) {
        fail("Script should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + th);
    }
    return th;
}
 
Example 23
Project: groovy   File: GroovyAssert.java   View source code 6 votes vote down vote up
/**
 * Asserts that the given script fails when it is evaluated
 *
 * @param script the script expected to fail
 * @return the caught exception
 */
public static Throwable shouldFail(String script) {
    boolean failed = false;
    Throwable th = null;
    try {
        GroovyShell shell = new GroovyShell();
        shell.evaluate(script, genericScriptName());
    } catch (GroovyRuntimeException gre) {
        failed = true;
        th = ScriptBytecodeAdapter.unwrap(gre);
    } catch (Throwable e) {
        failed = true;
        th = e;
    }
    assertTrue("Script should have failed", failed);
    return th;
}
 
Example 24
Project: groovy   File: CachingGroovyEngine.java   View source code 6 votes vote down vote up
/**
 * Initialize the engine.
 */
public void initialize(final BSFManager mgr, String lang, Vector declaredBeans) throws BSFException {
    super.initialize(mgr, lang, declaredBeans);
    ClassLoader parent = mgr.getClassLoader();
    if (parent == null)
        parent = GroovyShell.class.getClassLoader();
    setLoader(mgr, parent);
    execScripts = new HashMap<Object, Class>();
    evalScripts = new HashMap<Object, Class>();
    context = shell.getContext();
    // create a shell
    // register the mgr with object name "bsf"
    context.setVariable("bsf", new BSFFunctions(mgr, this));
    int size = declaredBeans.size();
    for (int i = 0; i < size; i++) {
        declareBean((BSFDeclaredBean) declaredBeans.elementAt(i));
    }
}
 
Example 25
Project: groovy   File: GroovyMain.java   View source code 6 votes vote down vote up
private static void setupContextClassLoader(GroovyShell shell) {
    final Thread current = Thread.currentThread();
    class DoSetContext implements PrivilegedAction {
        ClassLoader classLoader;

        public DoSetContext(ClassLoader loader) {
            classLoader = loader;
        }

        public Object run() {
            current.setContextClassLoader(classLoader);
            return null;
        }
    }

    AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}
 
Example 26
Project: groovy   File: GroovyMain.java   View source code 6 votes vote down vote up
/**
 * Process the input files.
 */
private void processFiles() throws CompilationFailedException, IOException, URISyntaxException {
    GroovyShell groovy = new GroovyShell(conf);
    setupContextClassLoader(groovy);

    Script s = groovy.parse(getScriptSource(isScriptFile, script));

    if (args.isEmpty()) {
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter writer = new PrintWriter(System.out)) {

            processReader(s, reader, writer);
        }
    } else {
        Iterator i = args.iterator();
        while (i.hasNext()) {
            String filename = (String) i.next();
            //TODO: These are the arguments for -p and -i.  Why are we searching using Groovy script extensions?
            // Where is this documented?
            File file = huntForTheScriptFile(filename);
            processFile(s, file);
        }
    }
}
 
Example 27
Project: groovy   File: Groovy1567_Bug.java   View source code 6 votes vote down vote up
public void testGroovyScriptEngineVsGroovyShell() throws IOException, ResourceException, ScriptException {
    // @todo refactor this path
    File currentDir = new File("./src/test/groovy/bugs");
    String file = "bug1567_script.groovy";

    Binding binding = new Binding();
    GroovyShell shell = new GroovyShell(binding);
    String[] test = null;
    Object result = shell.run(new File(currentDir, file), test);

    String[] roots = new String[]{currentDir.getAbsolutePath()};
    GroovyScriptEngine gse = new GroovyScriptEngine(roots);
    binding = new Binding();
    // a MME was ensued here stating no 't.start()' was available
    // in the script
    gse.run(file, binding);
}
 
Example 28
Project: groovy   File: SeansBug.java   View source code 6 votes vote down vote up
public void testMarkupBug() throws Exception {
    String[] lines =
            {
                    "package groovy.xml",
                    "",
                    "b = new MarkupBuilder()",
                    "",
                    "b.root1(a:5, b:7) { ",
                    "    elem1('hello1') ",
                    "    elem2('hello2') ",
                    "    elem3(x:7) ",
                    "}"};
    String code = asCode(lines);
    GroovyShell shell = new GroovyShell();
    shell.evaluate(code);
}
 
Example 29
Project: groovy   File: PlatformLineWriterTest.java   View source code 6 votes vote down vote up
public void testPlatformLineWriter() throws IOException, ClassNotFoundException {
    String LS = System.getProperty("line.separator");
    Binding binding = new Binding();
    binding.setVariable("first", "Tom");
    binding.setVariable("last", "Adams");
    StringWriter stringWriter = new StringWriter();
    Writer platformWriter = new PlatformLineWriter(stringWriter);
    GroovyShell shell = new GroovyShell(binding);
    platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString());
    platformWriter.flush();
    assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
    stringWriter = new StringWriter();
    platformWriter = new PlatformLineWriter(stringWriter);
    platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString());
    platformWriter.flush();
    assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
}
 
Example 30
Project: Pushjet-Android   File: ApiGroovyCompiler.java   View source code 6 votes vote down vote up
private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.1")) < 0) {
        throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + "");
    }
    Binding binding = new Binding();
    binding.setVariable("configuration", configuration);

    CompilerConfiguration configuratorConfig = new CompilerConfiguration();
    ImportCustomizer customizer = new ImportCustomizer();
    customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
    configuratorConfig.addCompilationCustomizers(customizer);

    GroovyShell shell = new GroovyShell(binding, configuratorConfig);
    try {
        shell.evaluate(configScript);
    } catch (Exception e) {
        throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e);
    }
}
 
Example 31
Project: COMP6237   File: GroovyConsoleSlide.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(final ActionEvent e) {
	if (e.getActionCommand().equals("run")) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				final JButton btn = (JButton) e.getSource();
				btn.setText("Running");
				btn.setEnabled(false);
				try {
					outputPane.setText("");
					final GroovyShell shell = new GroovyShell();
					final Script script = shell.parse(textArea.getText());
					script.run();
				} finally {
					btn.setText("Run");
					btn.setEnabled(true);
				}
			}
		}).start();
		;
	}
}
 
Example 32
Project: COMP6237   File: GroovySlide.java   View source code 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 33
Project: streamline   File: GroovyTest.java   View source code 6 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 34
Project: streamline   File: GroovyTest.java   View source code 6 votes vote down vote up
@Test(expected = groovy.lang.MissingPropertyException.class)
public void testGroovyShell_goodBindingFollowedByBadBinding_Exception() 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);

    Assert.assertTrue(binding.hasVariable("x"));

    binding = new Binding();
    binding.setProperty("x1", 5);
    binding.setProperty("y1", 3);
    script.setBinding(binding);

    Assert.assertFalse(binding.hasVariable("x"));

    script.run();  // throws exception because no bindings for x, y
}
 
Example 35
Project: grafikon   File: MainFrame.java   View source code 6 votes vote down vote up
private void initAndPreload(SplashScreenInfo info) {
    // preload FileLoadSave
    info.setText(getInfoText("Registering LS..."));
    LSFileFactory.getInstance();
    LSLibraryFactory.getInstance();

    // initialize groovy
    info.setText(getInfoText("Initializing Groovy..."));
    new GroovyShell().parse("");

    // initialize javascript
    info.setText(getInfoText("Initializing JavaScript..."));
    new ScriptEngineManager().getEngineByName("javascript");

    // preload file dialogs
    info.setText(getInfoText("Preloading dialogs..."));
    FileChooserFactory fcf = FileChooserFactory.getInstance();
    fcf.initialize();
}
 
Example 36
Project: Genji   File: GroovyScriptExecuter.java   View source code 6 votes vote down vote up
/**
 * Execute a plain Groovy shell script
 * @param theScript the Groovy script to be evaluated
 * @param inputBinding the parameters passed to the script
 * @return a map with key/value pairs as result
 */
public static Map<String, Object> executeGroovyScript(String theScript, Binding inputBinding) {

	TScriptsBean scriptBean = ScriptAdminBL.loadByClassName(theScript);

	String scriptCode = null;
	Map<String, Object> result = new HashMap<String, Object>();

	if (scriptBean != null) {
		scriptCode = scriptBean.getSourceCode();

		GroovyShell shell = new GroovyShell(inputBinding);

		result.put("result", shell.evaluate(scriptCode));
	} else {
		result.put("error", "Can't load script "  + theScript);
	}

	return result;
}
 
Example 37
Project: Skylark   File: GroovyPlugin.java   View source code 6 votes vote down vote up
private GroovyShell getShell(Binding binding, GroovyInterceptor sandbox, GenericUserMessageEvent event) {
	binding.setVariable("eval", getEvalFunction(binding, sandbox, event));
	binding.setVariable("commands", new DynamicCommandHandler(this, event));
	CompilerConfiguration cc = new CompilerConfiguration();
	cc.addCompilationCustomizers(
			new SandboxTransformer(),
			new ASTTransformationCustomizer(ImmutableMap.of("value", TIMEOUT), TimedInterrupt.class),
			new ImportCustomizer()
				.addStarImports("java.lang.reflect")
				.addImports(HttpRequest.class.getName())
				.addImports(CommandCall.class.getName())
	);
	GroovyShell shell = new GroovyShell(manager.pluginClassLoader, binding, cc);
	sandbox.register();
	return shell;
}
 
Example 38
Project: vertx-lang-groovy   File: IntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void testInvokeRawMethod() throws Exception {
  ListMethods itf = list -> {
    JsonObject combined = new JsonObject();
    list.forEach(combined::mergeIn);
    return combined;
  };
  CompilerConfiguration config = new CompilerConfiguration();
  Properties props = new Properties();
  props.setProperty("groovy.disabled.global.ast.transformations", "io.vertx.lang.groovy.VertxTransformation");
  config.configure(props);
  GroovyShell shell = new GroovyShell(config);
  shell.setProperty("itf", itf);
  Object o = shell.evaluate("return itf.jsonList([new io.vertx.core.json.JsonObject().put('foo', 'foo_value'), new io.vertx.core.json.JsonObject().put('bar', 'bar_value')])");
  JsonObject result = (JsonObject) o;
  assertEquals(result, new JsonObject().put("foo", "foo_value").put("bar", "bar_value"));
}
 
Example 39
Project: netTransformer   File: ScriptAssertion.java   View source code 6 votes vote down vote up
@Override
public AssertionResult doAssert(InputSource source) {
    Document xmlDocument;
    try {
        xmlDocument = builder.parse(source);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Binding binding = new Binding();
    binding.setVariable("document", xmlDocument);
    GroovyShell shell = new GroovyShell(binding);

    Object value = shell.evaluate(script);
    if (value instanceof Boolean){
        if ((Boolean)value){
            return new AssertionResult(assertionName, AssertionType.SUCCESS);
        } else {
            return new AssertionResult(assertionName, AssertionType.FAILED);
        }
    } else {
        throw new RuntimeException("value of type "+value.getClass()+" is returned from groovy script");
    }

}
 
Example 40
Project: freemind_1.0.0_20140624_214725   File: ScriptEditorPanelTest.java   View source code 6 votes vote down vote up
public boolean executeScript(int pIndex, PrintStream outStream,
		ErrorHandler pErrorHandler) {
	Binding binding = new Binding();
	binding.setVariable("c", null);
	binding.setVariable("node", null);
	GroovyShell shell = new GroovyShell(binding);

	String script = getScript(pIndex).getScript();
	// redirect output:
	PrintStream oldOut = System.out;
	Object value;
	try {
		System.setOut(outStream);
		value = shell.evaluate(script);
	} finally {
		System.setOut(oldOut);
	}
	return true;
}