Search in sources :

Example 91 with Script

use of groovy.lang.Script in project hale by halestudio.

the class GroovyTransformationPage method validate.

@Override
protected boolean validate(String document) {
    super.validate(document);
    List<PropertyValue> values = new ArrayList<PropertyValue>();
    for (EntityDefinition var : getVariables()) {
        if (var instanceof PropertyEntityDefinition) {
            PropertyEntityDefinition property = (PropertyEntityDefinition) var;
            values.add(new PropertyValueImpl(testValues.get(property), property));
        }
    }
    Property targetProperty = (Property) CellUtil.getFirstEntity(getWizard().getUnfinishedCell().getTarget());
    if (targetProperty == null) {
        // not yet selected (NewRelationWizard)
        return false;
    }
    InstanceBuilder builder = GroovyTransformation.createBuilder(targetProperty.getDefinition());
    Cell cell = getWizard().getUnfinishedCell();
    boolean useInstanceValues = CellUtil.getOptionalParameter(cell, GroovyTransformation.PARAM_INSTANCE_VARIABLES, Value.of(false)).as(Boolean.class);
    AlignmentService as = PlatformUI.getWorkbench().getService(AlignmentService.class);
    GroovyService gs = HaleUI.getServiceProvider().getService(GroovyService.class);
    Script script = null;
    try {
        Collection<? extends Cell> typeCells = as.getAlignment().getTypeCells(cell);
        // select one matching type cell, the script has to run for all
        // matching cells
        // if there is no matching cell it may produce a npe, which is okay
        Cell typeCell = null;
        if (!typeCells.isEmpty()) {
            typeCell = typeCells.iterator().next();
        }
        CellLog log = new CellLog(new DefaultTransformationReporter("dummy", false), cell);
        ExecutionContext context = new DummyExecutionContext(HaleUI.getServiceProvider());
        groovy.lang.Binding binding;
        if (cell.getTransformationIdentifier().equals(GroovyGreedyTransformation.ID)) {
            binding = GroovyGreedyTransformation.createGroovyBinding(values, null, cell, typeCell, builder, useInstanceValues, log, context, targetProperty.getDefinition().getDefinition().getPropertyType());
        } else {
            binding = GroovyTransformation.createGroovyBinding(values, null, cell, typeCell, builder, useInstanceValues, log, context, targetProperty.getDefinition().getDefinition().getPropertyType());
        }
        script = gs.parseScript(document, binding);
        GroovyTransformation.evaluate(script, builder, targetProperty.getDefinition().getDefinition().getPropertyType(), gs, log);
    } catch (NoResultException e) {
    // continue
    } catch (final Exception e) {
        return handleValidationResult(script, e);
    }
    return handleValidationResult(script, null);
}
Also used : Script(groovy.lang.Script) ArrayList(java.util.ArrayList) DefaultTransformationReporter(eu.esdihumboldt.hale.common.align.transformation.report.impl.DefaultTransformationReporter) PropertyValue(eu.esdihumboldt.hale.common.align.transformation.function.PropertyValue) NoResultException(eu.esdihumboldt.hale.common.align.transformation.function.impl.NoResultException) GroovyService(eu.esdihumboldt.util.groovy.sandbox.GroovyService) NoResultException(eu.esdihumboldt.hale.common.align.transformation.function.impl.NoResultException) PropertyEntityDefinition(eu.esdihumboldt.hale.common.align.model.impl.PropertyEntityDefinition) EntityDefinition(eu.esdihumboldt.hale.common.align.model.EntityDefinition) ExecutionContext(eu.esdihumboldt.hale.common.align.transformation.function.ExecutionContext) PropertyEntityDefinition(eu.esdihumboldt.hale.common.align.model.impl.PropertyEntityDefinition) AlignmentService(eu.esdihumboldt.hale.ui.service.align.AlignmentService) Property(eu.esdihumboldt.hale.common.align.model.Property) Cell(eu.esdihumboldt.hale.common.align.model.Cell) CellLog(eu.esdihumboldt.hale.common.align.transformation.report.impl.CellLog) PropertyValueImpl(eu.esdihumboldt.hale.common.align.transformation.function.impl.PropertyValueImpl) InstanceBuilder(eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)

Example 92 with Script

use of groovy.lang.Script in project hale by halestudio.

the class GroovySnippets method invokeMethod.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Object invokeMethod(String name, Object args) {
    List<?> argList = new ArrayList<>(InvokerHelper.asList(args));
    try {
        Map<Object, Object> vars = new HashMap<>();
        Optional<?> firstMap = argList.stream().filter(v -> v instanceof Map).findFirst();
        if (firstMap.isPresent()) {
            vars.putAll((Map) firstMap.get());
            argList.remove(firstMap.get());
        }
        Script script = loadScript(name, vars);
        if (script == null) {
            throw new IllegalArgumentException(MessageFormat.format("Snippet with identifer \"{0}\" not found.", name));
        }
        if (argList.isEmpty()) {
            // run script
            return script.run();
        } else if (argList.size() == 1 && argList.get(0) instanceof Closure) {
            // run closure on script
            Closure cl = (Closure) argList.get(0);
            cl.setDelegate(script);
            cl.setResolveStrategy(Closure.OWNER_FIRST);
            return cl.call();
        }
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return super.invokeMethod(name, args);
}
Also used : List(java.util.List) InvokerHelper(org.codehaus.groovy.runtime.InvokerHelper) Map(java.util.Map) Optional(java.util.Optional) Closure(groovy.lang.Closure) GroovyObjectSupport(groovy.lang.GroovyObjectSupport) HashMap(java.util.HashMap) ServiceProvider(eu.esdihumboldt.hale.common.core.service.ServiceProvider) Binding(groovy.lang.Binding) Script(groovy.lang.Script) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) Script(groovy.lang.Script) Closure(groovy.lang.Closure) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap)

Example 93 with Script

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

the class AbstractScripting method createScript.

protected Script createScript(String text) {
    StringBuilder sb = new StringBuilder();
    for (String importItem : imports) {
        sb.append("import ").append(importItem).append("\n");
    }
    Matcher matcher = IMPORT_PATTERN.matcher(text);
    String result;
    if (matcher.find()) {
        StringBuffer s = new StringBuffer();
        matcher.appendReplacement(s, sb + "$0");
        result = matcher.appendTail(s).toString();
    } else {
        Matcher packageMatcher = PACKAGE_PATTERN.matcher(text);
        if (packageMatcher.find()) {
            StringBuffer s = new StringBuffer();
            packageMatcher.appendReplacement(s, "$0\n" + sb);
            result = packageMatcher.appendTail(s).toString();
        } else {
            result = sb.append(text).toString();
        }
    }
    CompilerConfiguration cc = new CompilerConfiguration();
    cc.setClasspath(groovyClassPath);
    cc.setRecompileGroovySource(true);
    GroovyShell shell = new GroovyShell(javaClassLoader, new Binding(), cc);
    // noinspection UnnecessaryLocalVariable
    Script script = shell.parse(result);
    return script;
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) Matcher(java.util.regex.Matcher) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyShell(groovy.lang.GroovyShell)

Example 94 with Script

use of groovy.lang.Script in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngine method eval.

Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException {
    this.checkClearCache();
    context.setAttribute("context", context, ScriptContext.ENGINE_SCOPE);
    java.io.Writer writer = context.getWriter();
    context.setAttribute("out", writer instanceof PrintWriter ? writer : new PrintWriter(writer), ScriptContext.ENGINE_SCOPE);
    Binding binding = new Binding() {

        public Object getVariable(String name) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    return context.getAttribute(name, scope);
                }
                throw new MissingPropertyException(name, getClass());
            }
        }

        public void setVariable(String name, Object value) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                context.setAttribute(name, value, scope);
            }
        }
    };
    try {
        Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
        Method[] methods = scriptClass.getMethods();
        Map<String, MethodClosure> closures = new HashMap<String, MethodClosure>();
        for (Method m : methods) {
            String name = m.getName();
            closures.put(name, new MethodClosure(scriptObject, name));
        }
        globalClosures.putAll(closures);
        final MetaClass oldMetaClass = scriptObject.getMetaClass();
        scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {

            public Object invokeMethod(Object object, String name, Object args) {
                if (args == null) {
                    return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                } else if (args instanceof Tuple) {
                    return invokeMethod(object, name, ((Tuple) args).toArray());
                } else if (args instanceof Object[]) {
                    return invokeMethod(object, name, (Object[]) args);
                } else {
                    return invokeMethod(object, name, new Object[] { args });
                }
            }

            public Object invokeMethod(Object object, String name, Object[] args) {
                try {
                    return super.invokeMethod(object, name, args);
                } catch (MissingMethodException mme) {
                    return callGlobal(name, args, context);
                }
            }

            public Object invokeStaticMethod(Object object, String name, Object[] args) {
                try {
                    return super.invokeStaticMethod(object, name, args);
                } catch (MissingMethodException mme) {
                    return callGlobal(name, args, context);
                }
            }
        });
        return scriptObject.run();
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) GroovyCompiledScript(org.codehaus.groovy.jsr223.GroovyCompiledScript) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MissingPropertyException(groovy.lang.MissingPropertyException) Method(java.lang.reflect.Method) MethodClosure(org.codehaus.groovy.runtime.MethodClosure) MissingPropertyException(groovy.lang.MissingPropertyException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) MetaClass(groovy.lang.MetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) Tuple(groovy.lang.Tuple) PrintWriter(java.io.PrintWriter)

Example 95 with Script

use of groovy.lang.Script in project groovy by apache.

the class GroovyMain method processFiles.

/**
 * 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);
        }
    }
}
Also used : Script(groovy.lang.Script) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) File(java.io.File) GroovyShell(groovy.lang.GroovyShell) PrintWriter(java.io.PrintWriter)

Aggregations

Script (groovy.lang.Script)123 Binding (groovy.lang.Binding)59 GroovyShell (groovy.lang.GroovyShell)23 IOException (java.io.IOException)21 Test (org.junit.Test)16 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)13 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)13 File (java.io.File)12 Map (java.util.Map)12 GroovyService (eu.esdihumboldt.util.groovy.sandbox.GroovyService)11 InstanceBuilder (eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)9 GroovityClassLoader (com.disney.groovity.compile.GroovityClassLoader)8 Closure (groovy.lang.Closure)8 PrintWriter (java.io.PrintWriter)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)8 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)8 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)8 MissingMethodException (groovy.lang.MissingMethodException)7