Search in sources :

Example 36 with Script

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

the class GroovyExpression method evaluate.

public <T> T evaluate(Exchange exchange, Class<T> type) {
    Script script = instantiateScript(exchange);
    script.setBinding(createBinding(exchange));
    Object value = script.run();
    return exchange.getContext().getTypeConverter().convertTo(type, value);
}
Also used : Script(groovy.lang.Script)

Example 37 with Script

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

the class InvokerHelper method createScript.

public static Script createScript(Class scriptClass, Binding context) {
    Script script;
    if (scriptClass == null) {
        script = new NullScript(context);
    } else {
        try {
            if (Script.class.isAssignableFrom(scriptClass)) {
                try {
                    Constructor constructor = scriptClass.getConstructor(Binding.class);
                    script = (Script) constructor.newInstance(context);
                } catch (NoSuchMethodException e) {
                    // Fallback for non-standard "Script" classes.
                    script = (Script) scriptClass.newInstance();
                    script.setBinding(context);
                }
            } else {
                final GroovyObject object = (GroovyObject) scriptClass.newInstance();
                // it could just be a class, so let's wrap it in a Script
                // wrapper; though the bindings will be ignored
                script = new Script(context) {

                    public Object run() {
                        Object argsToPass = EMPTY_MAIN_ARGS;
                        try {
                            Object args = getProperty("args");
                            if (args instanceof String[]) {
                                argsToPass = args;
                            }
                        } catch (MissingPropertyException e) {
                        // They'll get empty args since none exist in the context.
                        }
                        object.invokeMethod("main", argsToPass);
                        return null;
                    }
                };
                Map variables = context.getVariables();
                MetaClass mc = getMetaClass(object);
                for (Object o : variables.entrySet()) {
                    Map.Entry entry = (Map.Entry) o;
                    String key = entry.getKey().toString();
                    // assume underscore variables are for the wrapper script
                    setPropertySafe(key.startsWith("_") ? script : object, mc, key, entry.getValue());
                }
            }
        } catch (Exception e) {
            throw new GroovyRuntimeException("Failed to create Script instance for class: " + scriptClass + ". Reason: " + e, e);
        }
    }
    return script;
}
Also used : Script(groovy.lang.Script) Constructor(java.lang.reflect.Constructor) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) MissingPropertyException(groovy.lang.MissingPropertyException) GString(groovy.lang.GString) MissingPropertyException(groovy.lang.MissingPropertyException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) MissingMethodException(groovy.lang.MissingMethodException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SpreadMapEvaluatingException(groovy.lang.SpreadMapEvaluatingException) IOException(java.io.IOException) GroovyObject(groovy.lang.GroovyObject) MetaClass(groovy.lang.MetaClass) GroovyObject(groovy.lang.GroovyObject) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) SpreadMap(groovy.lang.SpreadMap)

Example 38 with Script

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

the class Groovy2365Bug method testDeadlock.

public void testDeadlock() {
    String path = createData();
    try {
        for (int i = 0; i != 100; ++i) {
            final GroovyClassLoader groovyLoader = new GroovyClassLoader();
            groovyLoader.addClasspath(path);
            Class _script1Class = null;
            try {
                _script1Class = groovyLoader.loadClass("Script1", true, true);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            final Class script1Class = _script1Class;
            // setup two threads to try a deadlock
            // thread one: newInstance script foo
            final boolean[] completed = new boolean[2];
            Thread thread1 = new Thread() {

                public void run() {
                    try {
                        Script script = (Script) script1Class.newInstance();
                        script.run();
                        completed[0] = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            Thread thread2 = new Thread() {

                public void run() {
                    try {
                        Class cls = groovyLoader.loadClass("Script2", true, true);
                        Script script = (Script) cls.newInstance();
                        script.run();
                        completed[1] = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            // let's see if we get a deadlock
            thread2.start();
            thread1.start();
            try {
                thread1.join(5000);
                thread2.join(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            assertTrue("Potentially deadlock", completed[0] && completed[1]);
        }
    } finally {
        ResourceGroovyMethods.deleteDir(new File(path));
    }
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) Script(groovy.lang.Script) File(java.io.File)

Example 39 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(conf);
    setupContextClassLoader(groovy);
    Script s = groovy.parse(getScriptSource(isScriptFile, script));
    if (args.isEmpty()) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);
        try {
            processReader(s, reader, writer);
        } finally {
            reader.close();
            writer.close();
        }
    } else {
        Iterator i = args.iterator();
        while (i.hasNext()) {
            String filename = (String) i.next();
            //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) Iterator(java.util.Iterator) GroovyShell(groovy.lang.GroovyShell)

Example 40 with Script

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

the class GroovySocketServer method run.

/**
    * Runs this server. There is typically no need to call this method, as the object's constructor
    * creates a new thread and runs this object automatically. 
    */
public void run() {
    try {
        ServerSocket serverSocket = new ServerSocket(url.getPort());
        while (true) {
            // Create one script per socket connection.
            // This is purposefully not caching the Script
            // so that the script source file can be changed on the fly,
            // as each connection is made to the server.
            //FIXME: Groovy has other mechanisms specifically for watching to see if source code changes.
            // We should probably be using that here.
            // See also the comment about the fact we recompile a script that can't change.
            Script script = groovy.parse(source);
            new GroovyClientConnection(script, autoOutput, serverSocket.accept());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Script(groovy.lang.Script) ServerSocket(java.net.ServerSocket) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Aggregations

Script (groovy.lang.Script)42 Binding (groovy.lang.Binding)21 IOException (java.io.IOException)12 GroovyShell (groovy.lang.GroovyShell)10 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)9 MissingMethodException (groovy.lang.MissingMethodException)6 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)5 PrintWriter (java.io.PrintWriter)5 Closure (groovy.lang.Closure)4 GroovyClassLoader (groovy.lang.GroovyClassLoader)4 MetaClass (groovy.lang.MetaClass)4 MissingPropertyException (groovy.lang.MissingPropertyException)4 File (java.io.File)4 UrlMapping (grails.web.mapping.UrlMapping)3 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)3 Tuple (groovy.lang.Tuple)3 Method (java.lang.reflect.Method)3 List (java.util.List)3 CompiledScript (javax.script.CompiledScript)3 ScriptException (javax.script.ScriptException)3