Java Code Examples for groovy.lang.GroovyShell#parse()

The following examples show how to use groovy.lang.GroovyShell#parse() . 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: GroovyExecutor.java    From hugegraph-loader with Apache License 2.0 6 votes vote down vote up
public void execute(String groovyScript, HugeClient client) {
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(DelegatingScript.class.getName());
    ImportCustomizer importCustomizer = new ImportCustomizer();
    importCustomizer.addImports(HugeClient.class.getName());
    importCustomizer.addImports(SchemaManager.class.getName());
    config.addCompilationCustomizers(importCustomizer);

    GroovyShell shell = new GroovyShell(getClass().getClassLoader(),
                                        this.binding, config);

    // Groovy invoke java through the delegating script.
    DelegatingScript script = (DelegatingScript) shell.parse(groovyScript);
    script.setDelegate(client);
    script.run();
}
 
Example 3
Source File: TestCaseScript.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * performs groovy substitutions with this as delegate and inherited bindings
 */
protected String substitute(String before) {
    if (!before.contains("${"))
        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 4
Source File: GroovyMain.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Process the input files.
 */
private void processFiles() throws CompilationFailedException, IOException, URISyntaxException {
    GroovyShell groovy = new GroovyShell(Thread.currentThread().getContextClassLoader(), 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);
            writer.flush();
        }
    } else {
        for (String filename : args) {
            //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 5
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 6
Source File: GroovyRunner.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
private GroovyRunner<T> setScript(String source) throws ScriptException {
    try {
        GroovyShell shell = new GroovyShell(binding);
        script = shell.parse(source);
        return this;
    } catch (CompilationFailedException e) {
        throw new ScriptException("Script compile failed: " + e.getMessage());
    }
}
 
Example 7
Source File: TestService.java    From groovy-script-example with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Binding groovyBinding = new Binding();
    groovyBinding.setVariable("testService", new TestService());
    GroovyShell groovyShell = new GroovyShell(groovyBinding);

    String scriptContent = "import pers.doublebin.example.groovy.script.service.TestService\n" +
            "def query = new TestService().testQuery(1L);\n" +
            "query";

    /*String scriptContent = "def query = testService.testQuery(2L);\n" +
            "query";*/

    Script script = groovyShell.parse(scriptContent);
    System.out.println(script.run());
}
 
Example 8
Source File: GroovyTest.java    From phoenix.webui.framework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
	{
		Binding binding = new Binding();
		binding.setVariable("language", "Groovy");
		
		GroovyShell shell = new GroovyShell(binding);
		
		GroovyScriptEngine engine = new GroovyScriptEngine(new URL[]{GroovyTest.class.getClassLoader().getResource("/")});
		Script script = shell.parse(GroovyTest.class.getClassLoader().getResource("random.groovy").toURI());
		
//		System.out.println(script);
//		script.invokeMethod("new SuRenRandom()", null);
//		script.evaluate("new SuRenRandom()");
//		engine.run("random.groovy", binding);
		
		InputStream stream = GroovyTest.class.getClassLoader().getResource("random.groovy").openStream();
		StringBuffer buf = new StringBuffer();
		byte[] bf = new byte[1024];
		int len = -1;
		while((len = stream.read(bf)) != -1)
		{
			buf.append(new String(bf, 0, len));
		}
		buf.append("\n");
		
		for(int i = 0; i < 30; i++)
		{
			System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomPhoneNum()"));
			System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomEmail()"));
			System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomZipCode()"));
		}
	}
 
Example 9
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 10
Source File: GroovyRunner.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
private GroovyRunner<T> setScript(String source) throws ScriptException {
    try {
        GroovyShell shell = new GroovyShell(binding);
        script = shell.parse(source);
        return this;
    } catch (CompilationFailedException e) {
        throw new ScriptException("Script compile failed: " + e.getMessage());
    }
}
 
Example 11
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 12
Source File: CrossmapActivity.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes 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().getClassLoader(), binding, compilerConfig);
    Script gScript = shell.parse(mapperScript);
    gScript.run();
}
 
Example 13
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 14
Source File: DbUpdaterEngine.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected boolean executeGroovyScript(ScriptResource file) {
    try {
        ClassLoader classLoader = getClass().getClassLoader();
        CompilerConfiguration cc = new CompilerConfiguration();
        cc.setRecompileGroovySource(true);

        Binding bind = new Binding();
        bind.setProperty("ds", getDataSource());
        bind.setProperty("log", LoggerFactory.getLogger(String.format("%s$%s", DbUpdaterEngine.class.getName(),
                StringUtils.removeEndIgnoreCase(file.getName(), ".groovy"))));
        if (!StringUtils.endsWithIgnoreCase(file.getName(), "." + UPGRADE_GROOVY_EXTENSION)) {
            bind.setProperty("postUpdate", new PostUpdateScripts() {
                @Override
                public void add(Closure closure) {
                    super.add(closure);

                    log.warn("Added post update action will be ignored for data store [{}]", storeNameToString(storeName));
                }
            });
        }

        GroovyShell shell = new GroovyShell(classLoader, bind, cc);
        Script script = shell.parse(file.getContent());
        script.run();
    } catch (Exception e) {
        throw new RuntimeException(
                String.format("%sError executing Groovy script %s\n%s", ERROR, file.name, e.getMessage()), e);
    }
    return true;
}
 
Example 15
Source File: SqoopCommand.java    From sqoop-on-spark with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void resolveVariables(List arg) {
  List temp = new ArrayList();
  GroovyShell gs = new GroovyShell(getBinding());
  for(Object obj:arg) {
    Script scr = gs.parse("\""+(String)obj+"\"");
    try {
      temp.add(scr.run().toString());
    }
    catch(MissingPropertyException e) {
      throw new SqoopException(ShellError.SHELL_0004, e.getMessage(), e);
    }
  }
  Collections.copy(arg, temp);
}
 
Example 16
Source File: HM.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public static Script load( String scriptPath ) throws Exception {
    GroovyShell gsh = new GroovyShell();
    return gsh.parse(new File(scriptPath));
}
 
Example 17
Source File: GroovyExpressionMatcher.java    From warnings-ng-plugin with MIT License 3 votes vote down vote up
/**
 * Compiles the script.
 *
 * @return the compiled script
 * @throws CompilationFailedException
 *         if the script contains compile errors
 */
public Script compile() throws CompilationFailedException {
    Binding binding = new Binding();
    GroovyShell shell = new GroovyShell(GroovySandbox.createSecureClassLoader(GroovyExpressionMatcher.class.getClassLoader()),
            binding, GroovySandbox.createSecureCompilerConfiguration());
    return shell.parse(script);
}