Search in sources :

Example 51 with Binding

use of groovy.lang.Binding in project ratpack by ratpack.

the class GroovySnippetExecuter method execute.

@Override
public void execute(TestCodeSnippet snippet) throws Exception {
    CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(new CompilationCustomizer(CompilePhase.CONVERSION) {

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
            if (compileStatic) {
                classNode.addAnnotation(new AnnotationNode(new ClassNode(CompileStatic.class)));
            }
        }
    });
    ClassLoader classLoader = new URLClassLoader(new URL[] {}, getClass().getClassLoader());
    GroovyShell groovyShell = new GroovyShell(classLoader, new Binding(), config);
    List<String> importsAndSnippet = extractImports(snippet.getSnippet());
    String imports = importsAndSnippet.get(0);
    String snippetMinusImports = fixture.transform(importsAndSnippet.get(1));
    String fullSnippet = imports + fixture.pre() + snippetMinusImports + fixture.post();
    Script script;
    try {
        script = groovyShell.parse(fullSnippet, snippet.getClassName());
    } catch (MultipleCompilationErrorsException e) {
        Message error = e.getErrorCollector().getError(0);
        if (error instanceof SyntaxErrorMessage) {
            // noinspection ThrowableResultOfMethodCallIgnored
            System.out.println(snippet.getSnippet());
            throw new CompileException(e, ((SyntaxErrorMessage) error).getCause().getLine());
        } else {
            throw e;
        }
    }
    ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(groovyShell.getClassLoader());
        fixture.around(script::run);
    } finally {
        Thread.currentThread().setContextClassLoader(previousContextClassLoader);
    }
}
Also used : Binding(groovy.lang.Binding) ClassNode(org.codehaus.groovy.ast.ClassNode) Script(groovy.lang.Script) Message(org.codehaus.groovy.control.messages.Message) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) CompileStatic(groovy.transform.CompileStatic) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) GroovyShell(groovy.lang.GroovyShell) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) CompilationCustomizer(org.codehaus.groovy.control.customizers.CompilationCustomizer)

Example 52 with Binding

use of groovy.lang.Binding in project ofbiz-framework by apache.

the class GroovyUtil method eval.

/**
 * Evaluate a Groovy condition or expression
 * @param expression The expression to evaluate
 * @param context The context to use in evaluation (re-written)
 * @see <a href="StringUtil.html#convertOperatorSubstitutions(java.lang.String)">StringUtil.convertOperatorSubstitutions(java.lang.String)</a>
 * @return Object The result of the evaluation
 * @throws CompilationFailedException
 */
@SuppressWarnings("unchecked")
public static Object eval(String expression, Map<String, Object> context) throws CompilationFailedException {
    Object o;
    if (expression == null || expression.equals("")) {
        Debug.logError("Groovy Evaluation error. Empty expression", module);
        return null;
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("Evaluating -- " + expression, module);
        Debug.logVerbose("Using Context -- " + context, module);
    }
    try {
        GroovyShell shell = new GroovyShell(getBinding(context, expression));
        o = shell.evaluate(StringUtil.convertOperatorSubstitutions(expression));
        if (Debug.verboseOn()) {
            Debug.logVerbose("Evaluated to -- " + o, module);
        }
        // read back the context info
        Binding binding = shell.getContext();
        context.putAll(binding.getVariables());
    } catch (CompilationFailedException e) {
        Debug.logError(e, "Groovy Evaluation error.", module);
        throw e;
    }
    return o;
}
Also used : Binding(groovy.lang.Binding) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyShell(groovy.lang.GroovyShell)

Example 53 with Binding

use of groovy.lang.Binding in project spring-integration by spring-projects.

the class GroovyControlBusFactoryBean method createHandler.

@Override
protected MessageHandler createHandler() {
    Binding binding = new ManagedBeansBinding(this.getBeanFactory());
    GroovyCommandMessageProcessor processor = new GroovyCommandMessageProcessor(binding, message -> {
        Map<String, Object> variables = new HashMap<>();
        variables.put("headers", message.getHeaders());
        return variables;
    });
    if (this.customizer != null) {
        processor.setCustomizer(this.customizer);
    }
    if (this.beanClassLoader != null) {
        processor.setBeanClassLoader(this.beanClassLoader);
    }
    if (getBeanFactory() != null) {
        processor.setBeanFactory(getBeanFactory());
    }
    return this.configureHandler(new ServiceActivatingHandler(processor));
}
Also used : Binding(groovy.lang.Binding) HashMap(java.util.HashMap) GroovyCommandMessageProcessor(org.springframework.integration.groovy.GroovyCommandMessageProcessor) ServiceActivatingHandler(org.springframework.integration.handler.ServiceActivatingHandler)

Example 54 with Binding

use of groovy.lang.Binding in project spring-integration by spring-projects.

the class GroovyScriptPayloadMessageProcessorTests method testBindingOverwriteWithContext.

// INT-2567
@Test
public void testBindingOverwriteWithContext() throws Exception {
    final String defaultValue = "default";
    Binding binding = new Binding() {

        @Override
        public Object getVariable(String name) {
            try {
                return super.getVariable(name);
            } catch (MissingPropertyException e) {
            // ignore
            }
            return defaultValue;
        }
    };
    ScriptVariableGenerator scriptVariableGenerator = new DefaultScriptVariableGenerator(Collections.singletonMap("spam", (Object) "bucket"));
    Message<?> message = MessageBuilder.withPayload("\"spam is $spam, foo is $foo\"").build();
    processor = new GroovyCommandMessageProcessor(binding, scriptVariableGenerator);
    Object result = processor.processMessage(message);
    assertEquals("spam is bucket, foo is default", result.toString());
}
Also used : Binding(groovy.lang.Binding) ScriptVariableGenerator(org.springframework.integration.scripting.ScriptVariableGenerator) DefaultScriptVariableGenerator(org.springframework.integration.scripting.DefaultScriptVariableGenerator) MissingPropertyException(groovy.lang.MissingPropertyException) DefaultScriptVariableGenerator(org.springframework.integration.scripting.DefaultScriptVariableGenerator) Test(org.junit.Test)

Example 55 with Binding

use of groovy.lang.Binding in project spring-integration by spring-projects.

the class GroovyScriptPayloadMessageProcessorTests method testBindingOverwrite.

// INT-2567
@Test
public void testBindingOverwrite() throws Exception {
    Binding binding = new Binding() {

        @Override
        public Object getVariable(String name) {
            throw new RuntimeException("intentional");
        }
    };
    Message<?> message = MessageBuilder.withPayload("foo").build();
    processor = new GroovyCommandMessageProcessor(binding);
    try {
        processor.processMessage(message);
        fail("Expected RuntimeException");
    } catch (Exception e) {
        Assert.assertEquals("intentional", e.getCause().getMessage());
    }
}
Also used : Binding(groovy.lang.Binding) MissingPropertyException(groovy.lang.MissingPropertyException) Test(org.junit.Test)

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