Search in sources :

Example 76 with Script

use of groovy.lang.Script in project groovity by disney.

the class Groovity method compileAll.

/**
 * Compile all scripts known to the configured source locators
 *
 * @param force if true, recompile all sources, if false recompile only changed sources
 */
public void compileAll(boolean force, boolean init) {
    if (inCompile.compareAndSet(false, true)) {
        try {
            compileEvents.clear();
            List<GroovitySource> sources = new ArrayList<GroovitySource>();
            // track existing views so we can keep track of files that may have since been deleted
            HashSet<String> oldViews = new HashSet<String>(((Map<String, Class<Script>>) scripts).keySet());
            for (GroovitySourceLocator sourceLocator : sourceLocators) {
                for (GroovitySource source : sourceLocator) {
                    try {
                        Matcher matcher = sourcePattern.matcher(source.getPath());
                        if (matcher.matches()) {
                            String name = matcher.group(1);
                            oldViews.remove(fixCase(name));
                            sources.add(source);
                        }
                    } catch (Exception e) {
                        log.log(Level.SEVERE, "Unable to load source " + source.getPath(), e);
                    }
                }
            }
            // remaining values in oldViews correspond to deleted files IF they are not embedded
            for (String del : oldViews) {
                Class<Script> cgs = scripts.get(del);
                final String path = getSourcePath(cgs);
                try {
                    sources.add(new GroovitySource() {

                        public String getSourceCode() throws IOException {
                            return "";
                        }

                        public String getPath() {
                            return path;
                        }

                        public long getLastModified() {
                            return System.currentTimeMillis();
                        }

                        public boolean exists() {
                            return false;
                        }
                    });
                } catch (Exception e) {
                    log.log(Level.SEVERE, "Error deleting grvt " + del, e);
                }
            }
            compile(force, init, sources.toArray(new GroovitySource[0]));
        } finally {
            inCompile.set(false);
        }
    } else {
        throw new RuntimeException("Groovy compiler is already busy, please retry later");
    }
}
Also used : Script(groovy.lang.Script) Matcher(java.util.regex.Matcher) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) GroovitySourceLocator(com.disney.groovity.source.GroovitySourceLocator) GroovitySource(com.disney.groovity.source.GroovitySource) GroovyClass(org.codehaus.groovy.tools.GroovyClass) HashSet(java.util.HashSet)

Example 77 with Script

use of groovy.lang.Script in project groovity by disney.

the class Groovity method loadGroovyClassesAndFindScript.

@SafeVarargs
@SuppressWarnings({ "rawtypes", "unchecked" })
protected final Class<Script> loadGroovyClassesAndFindScript(GroovityClassLoader loader, GroovyClass[] classes, Map<String, Class>... loadTraits) throws IllegalAccessException {
    Class<Script> scriptClass = null;
    List<Class> defined = new ArrayList<>();
    for (GroovyClass cl : classes) {
        defined.add(loader.defineClass(cl.getName(), cl.getBytes()));
    }
    for (Class c : defined) {
        if (Script.class.isAssignableFrom(c)) {
            scriptClass = c;
        // log.info("Loaded groovy script from disk "+c.getName());
        } else if (Taggable.class.isAssignableFrom(c)) {
            if (tagLib != null) {
                try {
                    tagLib.add((Taggable) c.newInstance());
                } catch (InstantiationException e) {
                    log.log(Level.SEVERE, "Could not register GroovyTag " + c.getName(), e);
                }
            }
        // log.info("Loaded supporting class from disk "+c.getName());
        }
        try {
            Annotation traitAnnotation = c.getAnnotation(Trait.class);
            if (traitAnnotation != null) {
                if (log.isLoggable(Level.FINE)) {
                    log.fine("INITING TRAIT " + c.getName());
                }
                for (Map<String, Class> traitMap : loadTraits) {
                    traitMap.put(c.getName(), c);
                }
            }
        } catch (Throwable e) {
        }
    }
    return scriptClass;
}
Also used : Script(groovy.lang.Script) GroovyClass(org.codehaus.groovy.tools.GroovyClass) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) GroovyClass(org.codehaus.groovy.tools.GroovyClass) Annotation(java.lang.annotation.Annotation)

Example 78 with Script

use of groovy.lang.Script in project groovity by disney.

the class Groovity method run.

/**
 * This is the primary method of interest - execute an individual groovity script by path using a given binding.
 * If the script returns a Writable (streaming template or GString) and a Writer is bound to "out", the value will be streamed to out,
 * otherwise the return value is passed through to the caller.
 *
 * @param scriptName the path of the script to execute, e.g. /myFolder/myScript
 * @param binding the groovy binding to use as global variable scope
 * @return the return value of the script, if any
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 * @throws IOException
 */
public Object run(final String scriptName, final Binding binding) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
    Script script = load(scriptName, binding);
    if (script != null) {
        Object rval = script.run();
        ScriptHelper scriptHelper = ((GroovityClassLoader) script.getClass().getClassLoader()).getScriptHelper();
        if (!scriptHelper.processReturn(script, rval)) {
            return rval;
        }
    }
    return null;
}
Also used : Script(groovy.lang.Script) GroovityClassLoader(com.disney.groovity.compile.GroovityClassLoader) ScriptHelper(com.disney.groovity.util.ScriptHelper)

Example 79 with Script

use of groovy.lang.Script in project groovity by disney.

the class GroovityScriptView method getSocket.

public WebSocket getSocket(Session session) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException {
    WebSocket ws = new WebSocket(session);
    Binding binding = new Binding();
    binding.setVariable("socket", ws);
    final Script script = viewFactory.load(name, binding);
    // look for "open" method on socket
    if (openMethod != null) {
        Binding oldBinding = ScriptHelper.THREAD_BINDING.get();
        try {
            ScriptHelper.THREAD_BINDING.set(binding);
            if (openMethod.getParameterCount() == 0) {
                openMethod.invoke(script);
            } else {
                openMethod.invoke(script, session);
            }
        } finally {
            if (oldBinding == null) {
                ScriptHelper.THREAD_BINDING.remove();
            } else {
                ScriptHelper.THREAD_BINDING.set(oldBinding);
            }
        }
    }
    ws.setMessageHandler(arg -> {
        synchronized (script) {
            script.getBinding().setVariable("message", arg);
            script.run();
        }
    }, messageSocketType);
    if (closeMethod != null) {
        ws.setCloseHandler(reason -> {
            Binding oldBinding = ScriptHelper.THREAD_BINDING.get();
            try {
                ScriptHelper.THREAD_BINDING.set(binding);
                if (closeMethod.getParameterCount() == 0) {
                    closeMethod.invoke(script);
                } else {
                    closeMethod.invoke(script, reason);
                }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Error closing web socket", e);
            } finally {
                if (oldBinding == null) {
                    ScriptHelper.THREAD_BINDING.remove();
                } else {
                    ScriptHelper.THREAD_BINDING.set(oldBinding);
                }
            }
        });
    }
    if (errorMethod != null) {
        ws.setErrorHandler(thrown -> {
            Binding oldBinding = ScriptHelper.THREAD_BINDING.get();
            try {
                ScriptHelper.THREAD_BINDING.set(binding);
                if (errorMethod.getParameterCount() == 0) {
                    errorMethod.invoke(script);
                } else {
                    errorMethod.invoke(script, thrown);
                }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Error handling error for web socket", e);
                logger.log(Level.SEVERE, "Original error was ", thrown);
            } finally {
                if (oldBinding == null) {
                    ScriptHelper.THREAD_BINDING.remove();
                } else {
                    ScriptHelper.THREAD_BINDING.set(oldBinding);
                }
            }
        });
    }
    return ws;
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) InvocationTargetException(java.lang.reflect.InvocationTargetException) WebSocket(com.disney.groovity.util.WebSocket)

Example 80 with Script

use of groovy.lang.Script in project groovity by disney.

the class TestExtGroovity method testThunderingHerd.

@Test
public void testThunderingHerd() throws InterruptedException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    Binding binding = new Binding();
    final Script herdScript = groovity.load("/herd", binding);
    CountDownLatch latch = new CountDownLatch(2);
    Runnable r = new Runnable() {

        @Override
        public void run() {
            herdScript.invokeMethod("getCachedThing", new Object[0]);
            latch.countDown();
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
    latch.await(1000, TimeUnit.MILLISECONDS);
    AtomicInteger executionCount = (AtomicInteger) herdScript.getProperty("cacheLoadCount");
    Assert.assertEquals(1, executionCount.get());
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

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