Search in sources :

Example 86 with Script

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

the class ScenarioPlugin method createScenario.

public static Scenario createScenario(String pathString) {
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    compilerConfiguration.setSourceEncoding("UTF-8");
    compilerConfiguration.setScriptBaseClass("info.deskchan.groovy_support.Scenario");
    Path path = Paths.get(pathString);
    compilerConfiguration.setClasspath(path.getParent().toString());
    GroovyShell groovyShell = new GroovyShell(compilerConfiguration);
    List<String> scriptLines = null;
    try {
        scriptLines = Files.readAllLines(path, Charset.forName("UTF-8"));
    } catch (Exception e) {
        pluginProxy.log("Invalid path specified for scenario");
        return null;
    }
    StringBuilder scriptText = new StringBuilder();
    String[] buffers = new String[1];
    for (int u = 0; u < buffers.length; u++) buffers[u] = null;
    for (int i = 0; i < scriptLines.size(); i++) {
        String line = scriptLines.get(i).trim();
        switch(line.charAt(0)) {
            case '<':
                scriptLines.set(i, line.substring(1).trim() + " = receive()");
                break;
            case '>':
                scriptLines.set(i, "say('" + line.substring(1).trim() + "')");
                break;
            case '$':
                {
                    List<String> matches = new ArrayList<String>();
                    Matcher m = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1|[^\\s]+").matcher(line.substring(1));
                    while (m.find() && matches.size() < 4) {
                        matches.add(m.group());
                    }
                    if (matches.size() == 0) {
                        scriptLines.remove(i);
                        i--;
                        continue;
                    }
                    StringBuilder sb = new StringBuilder("sendMessage(");
                    for (int u = 0; u < matches.size(); u++) {
                        String arg = matches.get(u);
                        if (arg.charAt(0) != '"' && arg.charAt(0) != '\'') {
                            if (u > 0)
                                sb.append(arg.replace("\"", "\\\""));
                            else
                                sb.append('"' + arg.replace("\"", "\\\"") + '"');
                        } else
                            sb.append(arg);
                        sb.append(',');
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(')');
                    scriptLines.set(i, sb.toString());
                }
                break;
        }
        scriptText.append(scriptLines.get(i));
        scriptText.append("\n");
    }
    Script script = groovyShell.parse(scriptText.toString());
    return (Scenario) script;
}
Also used : Path(java.nio.file.Path) Script(groovy.lang.Script) Matcher(java.util.regex.Matcher) GroovyShell(groovy.lang.GroovyShell) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Example 87 with Script

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

the class GroovyTransformation method evaluate.

@Override
protected Object evaluate(String transformationIdentifier, TransformationEngine engine, ListMultimap<String, PropertyValue> variables, String resultName, PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log) throws TransformationException, NoResultException {
    // determine if instances should be used in variables or their values
    boolean useInstanceVariables = getOptionalParameter(PARAM_INSTANCE_VARIABLES, Value.of(false)).as(Boolean.class);
    // instance builder
    InstanceBuilder builder = createBuilder(resultProperty);
    // create the script binding
    List<? extends Entity> varDefs = null;
    if (getCell().getSource() != null) {
        varDefs = getCell().getSource().get(ENTITY_VARIABLE);
    }
    Binding binding = createGroovyBinding(variables.get(ENTITY_VARIABLE), varDefs, getCell(), getTypeCell(), builder, useInstanceVariables, log, getExecutionContext(), resultProperty.getDefinition().getPropertyType());
    Object result;
    try {
        GroovyService service = getExecutionContext().getService(GroovyService.class);
        Script groovyScript = GroovyUtil.getScript(this, binding, service);
        // evaluate the script
        result = evaluate(groovyScript, builder, resultProperty.getDefinition().getPropertyType(), service, log);
    } catch (TransformationException | NoResultException e) {
        throw e;
    } catch (Throwable e) {
        throw new TransformationException("Error evaluating the cell script", e);
    }
    if (result == null) {
        throw new NoResultException();
    }
    return result;
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) TransformationException(eu.esdihumboldt.hale.common.align.transformation.function.TransformationException) NoResultException(eu.esdihumboldt.hale.common.align.transformation.function.impl.NoResultException) GroovyService(eu.esdihumboldt.util.groovy.sandbox.GroovyService) InstanceBuilder(eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)

Example 88 with Script

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

the class GroovyFilter method match.

@Override
public boolean match(Instance instance, Map<Object, Object> context) {
    GroovyService service = getGroovyService();
    Binding binding = new Binding();
    // helper functions
    binding.setVariable(GroovyConstants.BINDING_HELPER_FUNCTIONS, HelperFunctions.createDefault(null));
    // instance
    binding.setVariable("instance", instance);
    // context
    binding.setVariable("withContext", SynchronizedContextProvider.getContextClosure(context));
    // log
    binding.setVariable(GroovyConstants.BINDING_LOG, new LogWrapper(log));
    Script script = getScript(service, binding);
    try {
        return service.evaluate(script, new ResultProcessor<Boolean>() {

            @Override
            public Boolean process(Script script, Object returnValue) throws Exception {
                if (returnValue != null && returnValue.equals(true)) {
                    return true;
                }
                return false;
            }
        });
    } catch (Exception e) {
        throw new IllegalStateException("Error evaluating Groovy filter", e);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) GroovyService(eu.esdihumboldt.util.groovy.sandbox.GroovyService) DefaultGroovyService(eu.esdihumboldt.util.groovy.sandbox.DefaultGroovyService)

Example 89 with Script

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

the class SnippetReaderImpl method loadSnippet.

/**
 * Load a snippet script.
 *
 * @param source the source of the script
 * @param serviceProvider the service provider
 * @param encoding the encoding
 * @return the loaded script
 * @throws Exception if loading or parsing the script fails
 */
public static Script loadSnippet(LocatableInputSupplier<? extends InputStream> source, ServiceProvider serviceProvider, Charset encoding) throws Exception {
    GroovyService service = serviceProvider.getService(GroovyService.class);
    Binding binding = null;
    String script;
    try (InputStream in = source.getInput()) {
        script = IOUtils.toString(in, encoding);
    }
    Script result = service.parseScript(script, binding);
    return result;
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) InputStream(java.io.InputStream) GroovyService(eu.esdihumboldt.util.groovy.sandbox.GroovyService)

Example 90 with Script

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

the class GroovyRetypePage method validate.

@Override
protected boolean validate(String document) {
    super.validate(document);
    Type targetType = (Type) CellUtil.getFirstEntity(getWizard().getUnfinishedCell().getTarget());
    Type sourceType = (Type) CellUtil.getFirstEntity(getWizard().getUnfinishedCell().getSource());
    if (sourceType == null || targetType == null) {
        // not yet selected (NewRelationWizard)
        return false;
    }
    InstanceBuilder builder = new InstanceBuilder(false);
    Instance instance = testValues.get(sourceType.getDefinition());
    if (instance == null) {
        // use an empty instance as input for the script
        instance = new DefaultInstance(sourceType.getDefinition().getDefinition(), DataSet.SOURCE);
    }
    FamilyInstance source = new FamilyInstanceImpl(instance);
    Cell cell = getWizard().getUnfinishedCell();
    CellLog log = new CellLog(new DefaultTransformationReporter("dummy", false), cell);
    ExecutionContext context = new DummyExecutionContext(HaleUI.getServiceProvider());
    Binding binding = GroovyRetype.createBinding(source, cell, builder, log, context, targetType.getDefinition().getDefinition());
    GroovyService service = HaleUI.getServiceProvider().getService(GroovyService.class);
    Script script = null;
    try {
        script = service.parseScript(document, binding);
        GroovyUtil.evaluateAll(script, builder, targetType.getDefinition().getDefinition(), service, log);
    } catch (final Exception e) {
        return handleValidationResult(script, e);
    }
    return handleValidationResult(script, null);
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) FamilyInstance(eu.esdihumboldt.hale.common.instance.model.FamilyInstance) Instance(eu.esdihumboldt.hale.common.instance.model.Instance) DefaultInstance(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance) DefaultTransformationReporter(eu.esdihumboldt.hale.common.align.transformation.report.impl.DefaultTransformationReporter) GroovyService(eu.esdihumboldt.util.groovy.sandbox.GroovyService) FamilyInstanceImpl(eu.esdihumboldt.hale.common.align.transformation.function.impl.FamilyInstanceImpl) Type(eu.esdihumboldt.hale.common.align.model.Type) ExecutionContext(eu.esdihumboldt.hale.common.align.transformation.function.ExecutionContext) DefaultInstance(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance) FamilyInstance(eu.esdihumboldt.hale.common.instance.model.FamilyInstance) Cell(eu.esdihumboldt.hale.common.align.model.Cell) CellLog(eu.esdihumboldt.hale.common.align.transformation.report.impl.CellLog) InstanceBuilder(eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)

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