Search in sources :

Example 6 with Binding

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

the class GroovyBeanDefinitionReader method loadBeanDefinitions.

/**
	 * Load bean definitions from the specified Groovy script or XML file.
	 * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds
	 * of resources will be parsed as Groovy scripts.
	 * @param encodedResource the resource descriptor for the Groovy script or XML file,
	 * allowing specification of an encoding to use for parsing the file
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    // Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader
    String filename = encodedResource.getResource().getFilename();
    if (StringUtils.endsWithIgnoreCase(filename, ".xml")) {
        return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource);
    }
    Closure beans = new Closure(this) {

        public Object call(Object[] args) {
            invokeBeanDefiningClosure((Closure) args[0]);
            return null;
        }
    };
    Binding binding = new Binding() {

        @Override
        public void setVariable(String name, Object value) {
            if (currentBeanDefinition != null) {
                applyPropertyToBeanDefinition(name, value);
            } else {
                super.setVariable(name, value);
            }
        }
    };
    binding.setVariable("beans", beans);
    int countBefore = getRegistry().getBeanDefinitionCount();
    try {
        GroovyShell shell = new GroovyShell(getResourceLoader().getClassLoader(), binding);
        shell.evaluate(encodedResource.getReader(), "beans");
    } catch (Throwable ex) {
        throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(), new Location(encodedResource.getResource()), null, ex));
    }
    return getRegistry().getBeanDefinitionCount() - countBefore;
}
Also used : Binding(groovy.lang.Binding) BeanDefinitionParsingException(org.springframework.beans.factory.parsing.BeanDefinitionParsingException) Closure(groovy.lang.Closure) GroovyObject(groovy.lang.GroovyObject) Problem(org.springframework.beans.factory.parsing.Problem) GString(groovy.lang.GString) GroovyShell(groovy.lang.GroovyShell) Location(org.springframework.beans.factory.parsing.Location)

Example 7 with Binding

use of groovy.lang.Binding in project cas by apereo.

the class ScriptingUtils method executeGroovyShellScript.

/**
 * Execute groovy shell script t.
 *
 * @param <T>       the type parameter
 * @param script    the script
 * @param variables the variables
 * @param clazz     the clazz
 * @return the t
 */
public static <T> T executeGroovyShellScript(final String script, final Map<String, Object> variables, final Class<T> clazz) {
    try {
        final Binding binding = new Binding();
        final GroovyShell shell = new GroovyShell(binding);
        if (variables != null && !variables.isEmpty()) {
            variables.forEach(binding::setVariable);
        }
        if (!binding.hasVariable("logger")) {
            binding.setVariable("logger", LOGGER);
        }
        LOGGER.debug("Executing groovy script [{}] with variables [{}]", script, binding.getVariables());
        final Object result = shell.evaluate(script);
        if (!clazz.isAssignableFrom(result.getClass())) {
            throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
        }
        return (T) result;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : Binding(groovy.lang.Binding) GroovyObject(groovy.lang.GroovyObject) GroovyShell(groovy.lang.GroovyShell)

Example 8 with Binding

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

the class RulesetDeployment method registerRulesGroovy.

public boolean registerRulesGroovy(Ruleset ruleset, Assets assetsFacade, Users usersFacade) {
    try {
        // TODO Implement sandbox
        // new DenyAll().register();
        Script script = groovyShell.parse(ruleset.getRules());
        Binding binding = new Binding();
        RulesBuilder rulesBuilder = new RulesBuilder();
        binding.setVariable("LOG", RulesEngine.RULES_LOG);
        binding.setVariable("rules", rulesBuilder);
        binding.setVariable("assets", assetsFacade);
        binding.setVariable("users", usersFacade);
        script.setBinding(binding);
        script.run();
        for (Rule rule : rulesBuilder.build()) {
            RulesEngine.LOG.info("Registering rule: " + rule.getName());
            rules.register(rule);
        }
        RulesEngine.LOG.info("Evaluated ruleset deployment: " + ruleset);
        return true;
    } catch (Exception e) {
        RulesEngine.LOG.log(Level.SEVERE, "Error evaluating ruleset: " + ruleset, e);
        setError(e);
        return false;
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) Rule(org.jeasy.rules.api.Rule)

Example 9 with Binding

use of groovy.lang.Binding in project fess by codelibs.

the class GroovyUtil method evaluate.

public static Object evaluate(final String template, final Map<String, Object> paramMap) {
    final Map<String, Object> bindingMap = new HashMap<>(paramMap);
    bindingMap.put("container", SingletonLaContainerFactory.getContainer());
    final GroovyShell groovyShell = new GroovyShell(new Binding(bindingMap));
    try {
        return groovyShell.evaluate(template);
    } catch (final Exception e) {
        logger.warn("Failed to evalue groovy script: " + template + " => " + paramMap, e);
        return null;
    } finally {
        final GroovyClassLoader loader = groovyShell.getClassLoader();
        //            StreamUtil.of(loader.getLoadedClasses()).forEach(c -> {
        //                try {
        //                    GroovySystem.getMetaClassRegistry().removeMetaClass(c);
        //                } catch (Throwable t) {
        //                    logger.warn("Failed to delete " + c, t);
        //                }
        //            });
        loader.clearCache();
    }
}
Also used : Binding(groovy.lang.Binding) GroovyClassLoader(groovy.lang.GroovyClassLoader) HashMap(java.util.HashMap) GroovyShell(groovy.lang.GroovyShell)

Example 10 with Binding

use of groovy.lang.Binding in project cuba by cuba-platform.

the class DbUpdaterImpl method executeGroovyScript.

@Override
protected boolean executeGroovyScript(final ScriptResource file) {
    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) {
                postUpdateScripts.put(closure, file);
                postUpdate.add(closure);
            }

            @Override
            public List<Closure> getUpdates() {
                return postUpdate.getUpdates();
            }
        });
    }
    try {
        scripting.evaluateGroovy(file.getContent(), bind, ScriptExecutionPolicy.DO_NOT_USE_COMPILE_CACHE);
    } catch (Exception e) {
        throw new RuntimeException(ERROR + "Error executing Groovy script " + file.name + "\n" + e.getMessage(), e);
    }
    return !postUpdateScripts.containsValue(file);
}
Also used : Binding(groovy.lang.Binding) PostUpdateScripts(com.haulmont.cuba.core.sys.PostUpdateScripts) Closure(groovy.lang.Closure) List(java.util.List) DbInitializationException(com.haulmont.cuba.core.sys.DbInitializationException)

Aggregations

Binding (groovy.lang.Binding)219 GroovyShell (groovy.lang.GroovyShell)77 Script (groovy.lang.Script)58 Test (org.junit.Test)39 IOException (java.io.IOException)30 File (java.io.File)24 HashMap (java.util.HashMap)24 Closure (groovy.lang.Closure)23 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)23 Map (java.util.Map)21 GroovyService (eu.esdihumboldt.util.groovy.sandbox.GroovyService)13 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)13 ImportCustomizer (org.codehaus.groovy.control.customizers.ImportCustomizer)12 MissingPropertyException (groovy.lang.MissingPropertyException)11 GroovyClassLoader (groovy.lang.GroovyClassLoader)10 InputStreamReader (java.io.InputStreamReader)10 StringWriter (java.io.StringWriter)10 Writer (java.io.Writer)10 InstanceBuilder (eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)9