public GroovyResult execute(GroovyResult result, final Script groovyScript, final Map<String, Object> variables) { if (variables != null) { final Binding binding = groovyScript.getBinding(); for (final Map.Entry<String, Object> entry : variables.entrySet()) { binding.setVariable(entry.getKey(), entry.getValue()); } } if (result == null) { result = new GroovyResult(); } Object res = null; try { res = groovyScript.run(); } catch (final Exception ex) { log.info("Groovy-Execution-Exception: " + ex.getMessage(), ex); return new GroovyResult(ex); } result.setResult(res); return result; }
@Override public void compileToDir(ScriptSource source, ClassLoader classLoader, File classesDir, File metadataDir, CompileOperation<?> extractingTransformer, Class<? extends Script> scriptBaseClass, Action<? super ClassNode> verifier) { Timer clock = Timers.startTimer(); GFileUtils.deleteDirectory(classesDir); GFileUtils.mkdirs(classesDir); CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass); configuration.setTargetDirectory(classesDir); try { compileScript(source, classLoader, configuration, metadataDir, extractingTransformer, verifier); } catch (GradleException e) { GFileUtils.deleteDirectory(classesDir); GFileUtils.deleteDirectory(metadataDir); throw e; } logger.debug("Timing: Writing script to cache at {} took: {}", classesDir.getAbsolutePath(), clock.getElapsed()); }
public Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException { synchronized (this.scriptClassMonitor) { if (this.scriptClass == null || scriptSource.isModified()) { this.scriptClass = this.groovyClassLoader.parseClass(scriptSource.getScriptAsString()); if (Script.class.isAssignableFrom(this.scriptClass)) { // A Groovy script, probably creating an instance: let's execute it. Object result = executeScript(this.scriptClass); this.scriptResultClass = (result != null ? result.getClass() : null); } else { this.scriptResultClass = this.scriptClass; } } return this.scriptResultClass; } }
/** * Returns the builder object for creating new output variable value. */ protected void runScript(String mapperScript, Slurper slurper, Builder builder) throws ActivityException, TransformerException { CompilerConfiguration compilerConfig = new CompilerConfiguration(); compilerConfig.setScriptBaseClass(CrossmapScript.class.getName()); Binding binding = new Binding(); binding.setVariable("runtimeContext", getRuntimeContext()); binding.setVariable(slurper.getName(), slurper.getInput()); binding.setVariable(builder.getName(), builder); GroovyShell shell = new GroovyShell(getPackage().getCloudClassLoader(), binding, compilerConfig); Script gScript = shell.parse(mapperScript); // gScript.setProperty("out", getRuntimeContext().get); gScript.run(); }
private synchronized GenericKeyedObjectPool<String, Script> getPool() { if (pool == null) { GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig(); poolConfig.setMaxTotalPerKey(-1); poolConfig.setMaxIdlePerKey(globalConfig.getGroovyEvaluationPoolMaxIdle()); pool = new GenericKeyedObjectPool<>( new BaseKeyedPooledObjectFactory<String, Script>() { @Override public Script create(String key) throws Exception { return createScript(key); } @Override public PooledObject<Script> wrap(Script value) { return new DefaultPooledObject<>(value); } }, poolConfig ); } return pool; }
/** * Loads a precompiled script with the supplied ID. The script class file must * be stored in the pre-compiled scripts folder (see {@link Configuration#getFolderCompiledScripts()}. * * The method will return null if such a folder does not exist or if it does not contain * the desired script. * @param id * @return */ public static Script loadScript(final String id) { String fileName = id+".class"; Script cached = cache.get(fileName); if (cached != null) { return cached; } try { URLClassLoader cl = getURLClassLoader(); if (cl != null) { Script script = InvokerHelper.createScript(cl.loadClass(fileName), new Binding()); cache.put(fileName, script); return script; } } catch (ClassNotFoundException | RuntimeException | MalformedURLException e) { // do nothing and just build the class from the text } return null; }
@Override public Object run(String dsl, Binding binding) { CompilerConfiguration compilerConfiguration = prepareCompilerConfiguration(); ClassLoader classLoader = prepareClassLoader(AbstractDSLLauncher.class.getClassLoader()); GroovyCodeSource groovyCodeSource = prepareGroovyCodeSource(dsl); // Groovy shell GroovyShell shell = new GroovyShell( classLoader, new Binding(), compilerConfiguration ); // Groovy script Script groovyScript = shell.parse(groovyCodeSource); // Binding groovyScript.setBinding(binding); // Runs the script return run(groovyScript); }
/** * Runs a Groovy DSL script and returns the value returned by the script. * @param scriptReader For reading the script text * @param expectedType The expected type of the return value * @param parameters Parameters used by the script, null or empty if the script doesn't need any * @param <T> The expected type of the return value * @return The return value of the script, not null */ private static <T> T runGroovyDslScript(Reader scriptReader, Class<T> expectedType, Map<String, Object> parameters) { Map<String, Object> timeoutArgs = ImmutableMap.<String, Object>of("value", 2); ASTTransformationCustomizer customizer = new ASTTransformationCustomizer(timeoutArgs, TimedInterrupt.class); CompilerConfiguration config = new CompilerConfiguration(); config.addCompilationCustomizers(customizer); config.setScriptBaseClass(SimulationScript.class.getName()); Map<String, Object> bindingMap = parameters == null ? Collections.<String, Object>emptyMap() : parameters; //copy map to ensure that binding is mutable (for use in registerAliases) Binding binding = new Binding(Maps.newHashMap(bindingMap)); registerAliases(binding); GroovyShell shell = new GroovyShell(binding, config); Script script = shell.parse(scriptReader); Object scriptOutput = script.run(); if (scriptOutput == null) { throw new IllegalArgumentException("Script " + scriptReader + " didn't return an object"); } if (expectedType.isInstance(scriptOutput)) { return expectedType.cast(scriptOutput); } else { throw new IllegalArgumentException("Script '" + scriptReader + "' didn't create an object of the expected type. " + "expected type: " + expectedType.getName() + ", " + "actual type: " + scriptOutput.getClass().getName() + ", " + "actual value: " + scriptOutput); } }
/** * Post process every stored request just before it get saved to disk * * @param sampler recorded http-request (sampler) * @param tree HashTree (XML like data structure) that represents exact recorded sampler */ public void processScenario(HTTPSamplerBase sampler, HashTree tree, Arguments userVariables, JMeterRecorder recorder) { Binding binding = new Binding(); binding.setVariable(ScriptBindingConstants.LOGGER, LOG); binding.setVariable(ScriptBindingConstants.SAMPLER, sampler); binding.setVariable(ScriptBindingConstants.TREE, tree); binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext()); binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance()); binding.setVariable(ScriptBindingConstants.USER_VARIABLES, userVariables); binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader); Script compiledProcessScript = ScriptEngine.getScript(getScenarioProcessorScript()); if (compiledProcessScript == null) { return; } compiledProcessScript.setBinding(binding); LOG.info("Run compiled script"); try { compiledProcessScript.run(); } catch (Throwable throwable) { LOG.error(throwable.getMessage(), throwable); } }
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException { LOG.debug("Evaluating Groovy expression: {1}", expression); try { final ObjectCache<String, Script> scriptCache = threadScriptCache.get(); Script script = scriptCache.get(expression); if (script == null) { script = GROOVY_SHELL.parse(expression); scriptCache.put(expression, script); } final Binding binding = new Binding(); for (final Entry<String, ?> entry : values.entrySet()) { binding.setVariable(entry.getKey(), entry.getValue()); } script.setBinding(binding); return script.run(); } catch (final Exception ex) { throw new ExpressionEvaluationException("Evaluating script with Groovy failed.", ex); } }
@SuppressWarnings("unchecked") Script getGroovyScript(String id, String scriptText) /*throws SQLException*/ { if (shell == null) { throw new RuntimeException("Groovy Shell is not initialized: null"); } try { Class<Script> clazz = scriptCache.get(scriptText); if (clazz == null) { String scriptName = id + "_" + Long.toHexString(scriptText.hashCode()) + ".groovy"; clazz = (Class<Script>) shell.parse(scriptText, scriptName).getClass(); scriptCache.put(scriptText, clazz); } Script script = (Script) clazz.newInstance(); return script; } catch (Throwable t) { throw new RuntimeException("Failed to parse groovy script: " + t, t); } }
/** * Evaluate an expression. */ public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException { try { Class scriptClass = evalScripts.get(script); if (scriptClass == null) { scriptClass = loader.parseClass(script.toString(), source); evalScripts.put(script, scriptClass); } else { LOG.fine("eval() - Using cached script..."); } //can't cache the script because the context may be different. //but don't bother loading parsing the class again Script s = InvokerHelper.createScript(scriptClass, context); return s.run(); } catch (Exception e) { throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e); } }
/** * 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()) { try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out)) { processReader(s, reader, writer); } } 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); } } }
/** * 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(); } }
public Object build(Script script) { // this used to be synchronized, but we also used to remove the // metaclass. Since adding the metaclass is now a side effect, we // don't need to ensure the meta-class won't be observed and don't // need to hide the side effect. MetaClass scriptMetaClass = script.getMetaClass(); script.setMetaClass(new FactoryInterceptorMetaClass(scriptMetaClass, this)); script.setBinding(this); Object oldScriptName = getProxyBuilder().getVariables().get(SCRIPT_CLASS_NAME); try { getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, script.getClass().getName()); return script.run(); } finally { if(oldScriptName != null) { getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, oldScriptName); } else { getProxyBuilder().getVariables().remove(SCRIPT_CLASS_NAME); } } }
protected void executeScript(Class scriptClass, Permission missingPermission) { try { Script script = InvokerHelper.createScript(scriptClass, new Binding()); script.run(); //InvokerHelper.runScript(scriptClass, null); } catch (AccessControlException ace) { if (missingPermission != null && missingPermission.implies(ace.getPermission())) { return; } else { fail(ace.toString()); } } if (missingPermission != null) { fail("Should catch an AccessControlException"); } }
public GroovyFieldDelegate initWithScript(Script groovyScript) { this.groovyScript = groovyScript; Object result = groovyScript.run(); @SuppressWarnings("rawtypes") Map<?, ?> methodMap = (result instanceof Map) ? ((Map) result) : Collections.emptyMap(); gameStarted = getClosure(methodMap, "gameStarted"); ballLost = getClosure(methodMap, "ballLost"); gameEnded = getClosure(methodMap, "gameEnded"); tick = getClosure(methodMap, "tick"); processCollision = getClosure(methodMap, "processCollision"); flippersActivated = getClosure(methodMap, "flippersActivated"); allDropTargetsInGroupHit = getClosure(methodMap, "allDropTargetsInGroupHit"); allRolloversInGroupActivated = getClosure(methodMap, "allRolloversInGroupActivated"); ballInSensorRange = getClosure(methodMap, "ballInSensorRange"); isFieldActive = getClosure(methodMap, "isFieldActive"); return this; }
public static GroovyFieldDelegate createFromScript(String script, ClassLoader classLoader) { CompilerConfiguration config = new CompilerConfiguration(); SecureASTCustomizer secureAst = new SecureASTCustomizer(); secureAst.setIndirectImportCheckEnabled(true); // TODO: Determine which classes should be accessible. secureAst.setImportsBlacklist(Arrays.asList("java.lang.Process")); secureAst.setReceiversClassesBlackList(Arrays.asList(String.class)); ImportCustomizer imports = new ImportCustomizer(); imports.addImport("Color", "com.dozingcatsoftware.vectorpinball.model.Color"); config.addCompilationCustomizers(secureAst, imports); try (GroovyClassLoader gcl = new GroovyClassLoader(classLoader, config)) { @SuppressWarnings("unchecked") Class<? extends Script> groovyScriptClass = gcl.parseClass(script); return (new GroovyFieldDelegate()).initWithScript(groovyScriptClass.newInstance()); } catch (IOException | InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } }
public void compileToDir(ScriptSource source, ClassLoader classLoader, File classesDir, Transformer transformer, Class<? extends Script> scriptBaseClass, Verifier verifier) { Clock clock = new Clock(); GFileUtils.deleteDirectory(classesDir); GFileUtils.mkdirs(classesDir); CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass); configuration.setTargetDirectory(classesDir); try { compileScript(source, classLoader, configuration, classesDir, transformer, verifier); } catch (GradleException e) { GFileUtils.deleteDirectory(classesDir); throw e; } logger.debug("Timing: Writing script to cache at {} took: {}", classesDir.getAbsolutePath(), clock.getTime()); }
public <T extends Script> Class<? extends T> loadFromDir(ScriptSource source, ClassLoader classLoader, File scriptCacheDir, Class<T> scriptBaseClass) { if (new File(scriptCacheDir, EMPTY_SCRIPT_MARKER_FILE_NAME).isFile()) { return emptyScriptGenerator.generate(scriptBaseClass); } try { URLClassLoader urlClassLoader = new URLClassLoader(WrapUtil.toArray(scriptCacheDir.toURI().toURL()), classLoader); return urlClassLoader.loadClass(source.getClassName()).asSubclass(scriptBaseClass); } catch (Exception e) { File expectedClassFile = new File(scriptCacheDir, source.getClassName() + ".class"); if (!expectedClassFile.exists()) { throw new GradleException(String.format("Could not load compiled classes for %s from cache. Expected class file %s does not exist.", source.getDisplayName(), expectedClassFile.getAbsolutePath()), e); } throw new GradleException(String.format("Could not load compiled classes for %s from cache.", source.getDisplayName()), e); } }
public <T extends Script> Class<? extends T> compile(ScriptSource source, ClassLoader classLoader, Transformer transformer, Class<T> scriptBaseClass, Verifier verifier) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("source.filename", source.getFileName()); properties.put("source.hash", HashUtil.createCompactMD5(source.getResource().getText())); String cacheName = String.format("scripts/%s/%s/%s", source.getClassName(), scriptBaseClass.getSimpleName(), transformer.getId()); PersistentCache cache = cacheRepository.cache(cacheName) .withProperties(properties) .withValidator(validator) .withDisplayName(String.format("%s class cache for %s", transformer.getId(), source.getDisplayName())) .withInitializer(new ProgressReportingInitializer(progressLoggerFactory, new CacheInitializer(source, classLoader, transformer, verifier, scriptBaseClass))) .open(); // This isn't quite right. The cache will be closed at the end of the build, releasing the shared lock on the classes. Instead, the cache for a script should be // closed once we no longer require the script classes. This may be earlier than the end of the current build, or it may used across multiple builds caches.add(cache); File classesDir = classesDir(cache); return scriptCompilationHandler.loadFromDir(source, classLoader, classesDir, scriptBaseClass); }
public void compileToDir(ScriptSource source, ClassLoader classLoader, File classesDir, Transformer transformer, Class<? extends Script> scriptBaseClass) { Clock clock = new Clock(); GFileUtils.deleteDirectory(classesDir); GFileUtils.mkdirs(classesDir); CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass); configuration.setTargetDirectory(classesDir); try { compileScript(source, classLoader, configuration, classesDir, transformer); } catch (GradleException e) { GFileUtils.deleteDirectory(classesDir); throw e; } logger.debug("Timing: Writing script to cache at {} took: {}", classesDir.getAbsolutePath(), clock.getTime()); }
public <T extends Script> Class<? extends T> loadFromDir(ScriptSource source, ClassLoader classLoader, File scriptCacheDir, Class<T> scriptBaseClass) { if (new File(scriptCacheDir, EMPTY_SCRIPT_MARKER_FILE_NAME).isFile()) { return emptyScriptGenerator.generate(scriptBaseClass); } try { URLClassLoader urlClassLoader = new URLClassLoader(WrapUtil.toArray(scriptCacheDir.toURI().toURL()), classLoader); return urlClassLoader.loadClass(source.getClassName()).asSubclass(scriptBaseClass); } catch (Exception e) { File expectedClassFile = new File(scriptCacheDir, source.getClassName()+".class"); if(!expectedClassFile.exists()){ throw new GradleException(String.format("Could not load compiled classes for %s from cache. Expected class file %s does not exist.", source.getDisplayName(), expectedClassFile.getAbsolutePath()), e); } throw new GradleException(String.format("Could not load compiled classes for %s from cache.", source.getDisplayName()), e); } }
public <T extends Script> Class<? extends T> compile(ScriptSource source, ClassLoader classLoader, Transformer transformer, Class<T> scriptBaseClass) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("source.filename", source.getFileName()); properties.put("source.hash", HashUtil.createCompactMD5(source.getResource().getText())); String cacheName = String.format("scripts/%s/%s/%s", source.getClassName(), scriptBaseClass.getSimpleName(), transformer.getId()); PersistentCache cache = cacheRepository.cache(cacheName) .withProperties(properties) .withValidator(validator) .withDisplayName(String.format("%s class cache for %s", transformer.getId(), source.getDisplayName())) .withInitializer(new ProgressReportingInitializer(progressLoggerFactory, new CacheInitializer(source, classLoader, transformer, scriptBaseClass))) .open(); // This isn't quite right. The cache will be closed at the end of the build, releasing the shared lock on the classes. Instead, the cache for a script should be // closed once we no longer require the script classes. This may be earlier than the end of the current build, or it may used across multiple builds caches.add(cache); File classesDir = classesDir(cache); return scriptCompilationHandler.loadFromDir(source, classLoader, classesDir, scriptBaseClass); }
/** * Initializes the API that the 'runtime' scripts will rely upon. * IF this is not called by the application then this is called automatically * the first time that a script is evaluated. */ public void initializeApi() { if( initialized ) { return; } for( Script script : api ) { if( log.isDebugEnabled() ) { log.debug("evaluating API script:" + script); } //script.setBinding(localBindings(bindings, source)); Object result = script.run(); if( log.isDebugEnabled() ) log.debug("result:" + result); } }
public Object eval( InputStream is, String s ) { if( log.isDebugEnabled() ) { log.debug( "evaluating:" + s ); } Script script = compile(is, s); int before = context.getVariables().size(); Object result = script.run(); if( log.isTraceEnabled() ) log.trace("result:" + result); if( before != context.getVariables().size() ) { log.warn("Binding count increased executing:" + s + " keys:" + context.getVariables().keySet()); } return result; }
@Override public GPathResult locate(GPathResult root, OfflineOptions options) throws Exception { boolean domain = Type.of(root) == Type.DOMAIN; Script script = (Script) ( domain ? DOMAIN_SCRIPT_CLASS.newInstance() : STANDALONE_OR_HOST_SCRIPT_CLASS.newInstance() ); script.setProperty("root", root); if (domain) { String defaultSocketBindingGroup = options.defaultProfile + "-sockets"; if ("default".equals(options.defaultProfile)) { defaultSocketBindingGroup = "standard-sockets"; } script.setProperty("defaultSocketBindingGroup", defaultSocketBindingGroup); } return (GPathResult) script.run(); }
@Override public SwampScriptInvokationResult invoke(SwampBinding binding) { Validate.notNull(binding, "Binding cannot be null."); GroovyInvokationResult result = new GroovyInvokationResult(); try { Script invokableScript = compiledScript.getClass().newInstance(); invokableScript.setBinding((GroovyBinding) binding); Object resultObject = invokableScript.run(); result.setVariables(new HashMap<>(binding.getVariableMap())); result.getVariables().put(SCRIPT_RESULT, resultObject); } catch (Exception e) { throw new IllegalStateException(e); } return result; }
@Override public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("run")) { new Thread(new Runnable() { @Override public void run() { final JButton btn = (JButton) e.getSource(); btn.setText("Running"); btn.setEnabled(false); try { outputPane.setText(""); final GroovyShell shell = new GroovyShell(); final Script script = shell.parse(textArea.getText()); script.run(); } finally { btn.setText("Run"); btn.setEnabled(true); } } }).start(); ; } }
@Override public Component getComponent(int width, int height) throws IOException { final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height)); base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS)); final Binding sharedData = new Binding(); final GroovyShell shell = new GroovyShell(sharedData); sharedData.setProperty("slidePanel", base); final Script script = shell.parse(new InputStreamReader(GroovySlide.class.getResourceAsStream("test.groovy"))); script.run(); // final RSyntaxTextArea textArea = new RSyntaxTextArea(20, 60); // textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_GROOVY); // textArea.setCodeFoldingEnabled(true); // final RTextScrollPane sp = new RTextScrollPane(textArea); // base.add(sp); return base; }
@Test public void testGroovyShell() throws Exception { GroovyShell groovyShell = new GroovyShell(); final String s = "x > 2 && y > 1"; Script script = groovyShell.parse(s); Binding binding = new Binding(); binding.setProperty("x",5); binding.setProperty("y",3); script.setBinding(binding); Object result = script.run(); Assert.assertEquals(true, result); log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s, script.getBinding().getProperty("x"), script.getBinding().getProperty("y"), result); binding.setProperty("y",0); result = script.run(); Assert.assertEquals(false, result); log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s, binding.getProperty("x"), binding.getProperty("y"), result); }
@Test(expected = groovy.lang.MissingPropertyException.class) public void testGroovyShell_goodBindingFollowedByBadBinding_Exception() throws Exception { GroovyShell groovyShell = new GroovyShell(); final String s = "x > 2 && y > 1"; Script script = groovyShell.parse(s); Binding binding = new Binding(); binding.setProperty("x", 5); binding.setProperty("y", 3); script.setBinding(binding); Object result = script.run(); Assert.assertEquals(true, result); Assert.assertTrue(binding.hasVariable("x")); binding = new Binding(); binding.setProperty("x1", 5); binding.setProperty("y1", 3); script.setBinding(binding); Assert.assertFalse(binding.hasVariable("x")); script.run(); // throws exception because no bindings for x, y }
public Script getScript(String scriptBaseClass, String scriptSource) { Class<? extends Script> scriptClass; synchronized (scriptCache) { ensureInitializedOrReloaded(); ScriptCacheElement cacheKey = new ScriptCacheElement(scriptBaseClass, scriptSource); ScriptCacheElement cacheElement = scriptCache.get(cacheKey); if (cacheElement != null) { scriptClass = cacheElement.getScriptClass(); } else { String scriptName = generatedScriptName(scriptSource, scriptCache.size()); scriptClass = compileScript(scriptBaseClass, scriptSource, scriptName); cacheKey.setScriptName(scriptName); cacheKey.setScriptClass(scriptClass); scriptCache.put(cacheKey, cacheKey); } } try { return scriptClass.newInstance(); } catch (Exception e) { throw new GroovyRuntimeException("Failed to create Script instance for class: "+ scriptClass + ". Reason: " + e, e); } }
@SuppressWarnings("unchecked") protected Class<Script> compileScript(final String scriptBaseClass, String scriptSource, final String scriptName) { final String script = preProcessScript(scriptSource); GroovyCodeSource codeSource = AccessController.doPrivileged((PrivilegedAction<GroovyCodeSource>) () -> new GroovyCodeSource(script, scriptName, getScriptCodeBase())); String currentScriptBaseClass = compilerConfiguration.getScriptBaseClass(); try { if (scriptBaseClass != null) { compilerConfiguration.setScriptBaseClass(scriptBaseClass); } return groovyClassLoader.parseClass(codeSource, false); } finally { compilerConfiguration.setScriptBaseClass(currentScriptBaseClass); } }
@Override public void run(JobToRun job) { RunnerFilterChain<JobStoryRunContext> chain = createFilterChain(); StoryFilterChainAdapter adapter = new StoryFilterChainAdapter(job, chain); DslBuilderAndRun.setFilterChainCurrentThread(adapter); try { Class<?> clazz = Class.forName(job.getStoryClassName()); if (! (clazz.getSuperclass().getName().equals("groovy.lang.Script"))){ throw new RuntimeException(job.getStoryClassName() + " is not a groovy script"); } Script script = (Script)clazz.newInstance(); script.run(); } catch (Exception e) { throw new RuntimeException(e); } }
private void runScript(String script) throws Exception { Vertx vertx = Vertx.vertx(); try { GroovyShell gcl = new GroovyShell(); Script s = gcl.parse(new File(script)); Binding binding = new Binding(); binding.setProperty("test", this); binding.setProperty("vertx", vertx); s.setBinding(binding); s.run(); } finally { CountDownLatch latch = new CountDownLatch(1); vertx.close(v -> { latch.countDown(); }); latch.await(); } }
@Test public void testDefaultSleep() throws Exception { final Script script = createScript("sleep(1000);", new HashMap<String, Object>()); final AtomicInteger counter = new AtomicInteger(0); Fiber fiber = new Fiber(scheduler, new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { counter.incrementAndGet(); script.run(); counter.incrementAndGet(); } }); fiber.start(); fiber.join(); Assert.assertEquals(counter.intValue(), 2); }
@Test public void testClosuresSleep() throws Exception { final SleepMethodSupport sleepMethodSupport = new SleepMethodSupport(); HashMap<String, Object> args = new HashMap<String, Object>() { { put("sleepMethodSupport", sleepMethodSupport); put("_sleep", new MethodClosure(sleepMethodSupport, "_sleep")); } }; final Script script = createScript("sleep(1000);_sleep(1000);sleepMethodSupport._sleep(1000)", args); final AtomicInteger counter = new AtomicInteger(0); Fiber fiber = new Fiber(scheduler, new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { counter.incrementAndGet(); script.run(); counter.incrementAndGet(); } }); fiber.start(); fiber.join(); Assert.assertEquals(counter.intValue(), 2); }
private void scanGroovyScriptBindings(AutoRegisterScript auto, Class<?> scriptClass) throws InvalidPluginException { Binding binding = new Binding(); Script script = InvokerHelper.createScript(scriptClass, binding); script.run(); for (Object variable : binding.getVariables().keySet()) { Object value = binding.getVariable(variable.toString()); if (value == null) { continue; } if (ArrayList.class.isAssignableFrom(value.getClass())) { scanArrayOfObjectOrClass(auto, value); } else { scanObjectOrClass(auto, value); } } }
public void buildScriptMember(final String name) { Object member = getMember(name); if (!(member instanceof Script)) return; final Script script = (Script) member; // special case: view gets executed in the UI thread always if (GriffonViewClass.TYPE.equals(name)) { getMvcGroupManager().getApplication().getUIThreadManager().runInsideUISync(new Runnable() { @Override public void run() { scriptResults.put(name, getBuilder().build(script)); } }); } else { scriptResults.put(name, getBuilder().build(script)); } }