Search in sources :

Example 61 with Binding

use of groovy.lang.Binding in project com.revolsys.open by revolsys.

the class ScriptRunner method run.

public void run() {
    if (this.scriptFile == null) {
    } else if (this.scriptFile.exists() && this.scriptFile.isFile()) {
        final String fileExtension = FileUtil.getFileNameExtension(this.scriptFile);
        try {
            if ("java".equals(fileExtension)) {
                final String scriptClassName = FileUtil.getBaseName(this.scriptFile);
                final URIJavaFileObject scriptJavaFile = new URIJavaFileObject(this.scriptFile, Kind.SOURCE);
                final JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
                final JavaFileManager fileManager = new InMemoryJavaFileManager(scriptJavaFile);
                final CompilationTask compilationTask = javaCompiler.getTask(null, fileManager, null, null, null, Collections.singleton(scriptJavaFile));
                compilationTask.call();
                final ClassLoader classLoader = fileManager.getClassLoader(null);
                final Class<?> scriptClass;
                try {
                    scriptClass = classLoader.loadClass(scriptClassName);
                } catch (final ClassNotFoundException e) {
                    showErrorDialog(// 
                    "must contain the class:<br />" + "<code>public class " + scriptClassName + // 
                    "</code><br />" + "in the default package.");
                    return;
                }
                final Method mainMethod;
                try {
                    mainMethod = scriptClass.getDeclaredMethod("main", String[].class);
                } catch (final NoSuchMethodException e) {
                    showErrorDialog("must contain the method:<br />" + // 
                    "<code>public static void main(String[] args)</code><br />" + // 
                    " in the class:<br />" + "<code>" + scriptClassName + "</code>");
                    return;
                }
                try {
                    mainMethod.invoke(null, (Object) NULL_MAIN_ARGS);
                } catch (final InvocationTargetException e) {
                    final Throwable targetException = e.getTargetException();
                    showErrorDialog(scriptClass, targetException);
                } catch (final Throwable e) {
                    showErrorDialog(scriptClass, e);
                    return;
                }
            } else {
                final Binding binding = new Binding();
                final GroovyShell shell = new GroovyShell(binding);
                shell.run(this.scriptFile, NULL_MAIN_ARGS);
            }
        } catch (final Throwable e) {
            showErrorDialog(getClass(), e);
        }
    } else {
        showErrorDialog("Does not exist");
    }
}
Also used : Binding(groovy.lang.Binding) JavaFileManager(javax.tools.JavaFileManager) JavaCompiler(javax.tools.JavaCompiler) Method(java.lang.reflect.Method) CompilationTask(javax.tools.JavaCompiler.CompilationTask) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyShell(groovy.lang.GroovyShell)

Example 62 with Binding

use of groovy.lang.Binding in project mdw-designer by CenturyLinkCloud.

the class GroovyTestCaseScript method adapter.

/**
 * responder closure call is delayed until stub server calls back
 */
public TestCaseAdapterStub adapter(Closure<Boolean> matcher, Closure<String> responder, Closure<?> init) throws TestException {
    final TestCaseAdapterStub adapterStub = new TestCaseAdapterStub(matcher, responder);
    if (init != null) {
        init.setResolveStrategy(Closure.DELEGATE_FIRST);
        init.setDelegate(adapterStub);
        init.call();
    }
    if (responder == null) {
        final TestCaseRun testCaseRun = getTestCaseRun();
        adapterStub.setResponder(new Closure<String>(this, adapterStub) {

            @Override
            public String call(Object request) {
                // binding for request
                if (adapterStub.getResponse().indexOf("${") >= 0) {
                    try {
                        Binding binding = getBinding();
                        if (request.toString().startsWith("{")) {
                            Object req = new JsonSlurper().parseText(request.toString());
                            binding.setVariable("request", req);
                        } else {
                            GPathResult gpathRequest = new XmlSlurper().parseText(request.toString());
                            binding.setVariable("request", gpathRequest);
                        }
                        CompilerConfiguration compilerCfg = new CompilerConfiguration();
                        compilerCfg.setScriptBaseClass(DelegatingScript.class.getName());
                        GroovyShell shell = new GroovyShell(GroovyTestCaseScript.class.getClassLoader(), binding, compilerCfg);
                        shell.setProperty("out", testCaseRun.log);
                        DelegatingScript script = (DelegatingScript) shell.parse("return \"\"\"" + adapterStub.getResponse() + "\"\"\"");
                        script.setDelegate(GroovyTestCaseScript.this);
                        return script.run().toString();
                    } catch (Exception ex) {
                        getTestCaseRun().log.println("Cannot perform stub substitutions for request: " + request);
                        ex.printStackTrace(getTestCaseRun().log);
                    }
                }
                return adapterStub.getResponse();
            }
        });
    }
    return adapterStub;
}
Also used : Binding(groovy.lang.Binding) JsonSlurper(groovy.json.JsonSlurper) XmlSlurper(groovy.util.XmlSlurper) GroovyShell(groovy.lang.GroovyShell) IOException(java.io.IOException) MbengException(com.qwest.mbeng.MbengException) DelegatingScript(groovy.util.DelegatingScript) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) JSONObject(org.json.JSONObject) GPathResult(groovy.util.slurpersupport.GPathResult)

Example 63 with Binding

use of groovy.lang.Binding in project mdw-designer by CenturyLinkCloud.

the class GroovyTestCaseScript method gpath.

/**
 * 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) {
                getTestCaseRun().log.println("Failed to parse request as XML/JSON. Stub response: " + AdapterActivity.MAKE_ACTUAL_CALL);
                return false;
            }
        }
    };
}
Also used : Binding(groovy.lang.Binding) Closure(groovy.lang.Closure) XmlSlurper(groovy.util.XmlSlurper) JSONObject(org.json.JSONObject) GPathResult(groovy.util.slurpersupport.GPathResult) GroovyShell(groovy.lang.GroovyShell) IOException(java.io.IOException) MbengException(com.qwest.mbeng.MbengException)

Example 64 with Binding

use of groovy.lang.Binding in project streamline by hortonworks.

the class GroovyTest method testGroovyShell_goodBindingFollowedByBadBinding_Exception.

@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"));
    // throws exception because no bindings for x, y
    script.run();
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) GroovyShell(groovy.lang.GroovyShell) Test(org.junit.Test)

Example 65 with Binding

use of groovy.lang.Binding in project streamline by hortonworks.

the class GroovyScript method evaluate.

@Override
public O evaluate(StreamlineEvent event) throws ScriptException {
    LOG.debug("Evaluating [{}] with [{}]", expression, event);
    groovy.lang.Script parsedScript = getParsedScript();
    O evaluatedResult = null;
    if (event != null) {
        try {
            Binding binding = createBinding(event);
            parsedScript.setBinding(binding);
            LOG.debug("Set script binding to [{}]", event);
            evaluatedResult = (O) parsedScript.run();
            LOG.debug("Expression [{}] evaluated to [{}]", expression, evaluatedResult);
        } catch (groovy.lang.MissingPropertyException e) {
            LOG.debug("Missing property: Expression [{}] params [{}]", expression, event);
            throw new ScriptException(e);
        }
    }
    return evaluatedResult;
}
Also used : Binding(groovy.lang.Binding) ScriptException(javax.script.ScriptException)

Aggregations

Binding (groovy.lang.Binding)213 GroovyShell (groovy.lang.GroovyShell)76 Script (groovy.lang.Script)55 Test (org.junit.Test)41 IOException (java.io.IOException)29 File (java.io.File)24 HashMap (java.util.HashMap)23 Closure (groovy.lang.Closure)22 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)22 Map (java.util.Map)20 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)13 ImportCustomizer (org.codehaus.groovy.control.customizers.ImportCustomizer)12 GroovyService (eu.esdihumboldt.util.groovy.sandbox.GroovyService)11 MissingPropertyException (groovy.lang.MissingPropertyException)11 GroovyClassLoader (groovy.lang.GroovyClassLoader)10 StringWriter (java.io.StringWriter)10 InstanceBuilder (eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)9 InputStreamReader (java.io.InputStreamReader)9 Writer (java.io.Writer)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)9