groovy.lang.Script Java Examples

The following examples show how to use groovy.lang.Script. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GroovyTest.java    From streamline with Apache License 2.0 7 votes vote down vote up
@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);
}
 
Example #2
Source File: GroovyScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 6 votes vote down vote up
@Override
public Object compile(com.alibaba.chaosblade.exec.plugin.jvm.script.base.Script script, ClassLoader classLoader,
                      Map<String, String> configs) {
    String className = "groovy_script_" + script.getId();
    GroovyCodeSource codeSource = new GroovyCodeSource(script.getContent(), className, UNTRUSTED_CODEBASE);
    codeSource.setCachable(true);
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration()
        .addCompilationCustomizers(
            new ImportCustomizer().addStaticStars("java.lang.Math"))
        .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION));
    compilerConfiguration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true);
    GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader, compilerConfiguration);
    try {
        return groovyClassLoader.parseClass(script.getContent());
    } catch (Exception ex) {
        throw convertToScriptException("Compile script failed:" + className, script.getId(), ex);
    }
}
 
Example #3
Source File: BenchmarkGroovyExpressionEvaluation.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup()
    throws IllegalAccessException, InstantiationException {
  _concatScriptText = "firstName + ' ' + lastName";
  _concatBinding = new Binding();
  _concatScript = new GroovyShell(_concatBinding).parse(_concatScriptText);
  _concatCodeSource = new GroovyCodeSource(_concatScriptText, Math.abs(_concatScriptText.hashCode()) + ".groovy",
      GroovyShell.DEFAULT_CODE_BASE);
  _concatGCLScript = (Script) _groovyClassLoader.parseClass(_concatCodeSource).newInstance();

  _maxScriptText = "longList.max{ it.toBigDecimal() }";
  _maxBinding = new Binding();
  _maxScript = new GroovyShell(_maxBinding).parse(_maxScriptText);
  _maxCodeSource = new GroovyCodeSource(_maxScriptText, Math.abs(_maxScriptText.hashCode()) + ".groovy",
      GroovyShell.DEFAULT_CODE_BASE);
  _maxGCLScript = (Script) _groovyClassLoader.parseClass(_maxCodeSource).newInstance();
}
 
Example #4
Source File: ExpressionLanguageGroovyImpl.java    From oval with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
   LOG.debug("Evaluating Groovy expression: {1}", expression);
   try {
      final Script script = expressionCache.get().get(expression);

      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);
   }
}
 
Example #5
Source File: CachingGroovyEngine.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #6
Source File: DefaultScriptCompilationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
    }
}
 
Example #7
Source File: GremlinGroovyScriptEngine.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Traversal.Admin eval(final Bytecode bytecode, final Bindings bindings, final String traversalSource) throws ScriptException {
    // these validations occur before merging in bytecode bindings which will override existing ones. need to
    // extract the named traversalsource prior to that happening so that bytecode bindings can share the same
    // namespace as global bindings (e.g. traversalsources and graphs).
    if (traversalSource.equals(HIDDEN_G))
        throw new IllegalArgumentException("The traversalSource cannot have the name " + HIDDEN_G + " - it is reserved");

    if (bindings.containsKey(HIDDEN_G))
        throw new IllegalArgumentException("Bindings cannot include " + HIDDEN_G + " - it is reserved");

    if (!bindings.containsKey(traversalSource))
        throw new IllegalArgumentException("The bindings available to the ScriptEngine do not contain a traversalSource named: " + traversalSource);

    final Object b = bindings.get(traversalSource);
    if (!(b instanceof TraversalSource))
        throw new IllegalArgumentException(traversalSource + " is of type " + b.getClass().getSimpleName() + " and is not an instance of TraversalSource");

    final Bindings inner = new SimpleBindings();
    inner.putAll(bindings);
    inner.putAll(bytecode.getBindings());
    inner.put(HIDDEN_G, b);
    org.apache.tinkerpop.gremlin.process.traversal.Script script = GroovyTranslator.of(HIDDEN_G, typeTranslator).translate(bytecode);
    script.getParameters().ifPresent(inner::putAll);
    return (Traversal.Admin) this.eval(script.getScript(), inner);
}
 
Example #8
Source File: AbstractScripting.java    From cuba with Apache License 2.0 6 votes vote down vote up
private synchronized GenericKeyedObjectPool<String, Script> getPool() {
    if (pool == null) {
        GenericKeyedObjectPoolConfig<Script> poolConfig = new GenericKeyedObjectPoolConfig<>();
        poolConfig.setMaxTotalPerKey(-1);
        poolConfig.setMaxIdlePerKey(globalConfig.getGroovyEvaluationPoolMaxIdle());
        pool = new GenericKeyedObjectPool<>(
                new BaseKeyedPooledObjectFactory<String, Script>() {
                    @Override
                    public Script create(String key) {
                        return createScript(key);
                    }

                    @Override
                    public PooledObject<Script> wrap(Script value) {
                        return new DefaultPooledObject<>(value);
                    }
                },
                poolConfig
        );
    }
    return pool;
}
 
Example #9
Source File: FactoryBuilderSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #10
Source File: DefaultScriptCompilationHandler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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());
}
 
Example #11
Source File: GroovyExecutor.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: GroovySlide.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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;
}
 
Example #13
Source File: OperationGroovy.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * generate a property name based on the groovy script filename and store
 * the script instance in the map
 *
 * @param groovyFilename
 * @param script
 * @throws ExecutionException
 */
private void prepareScriptProperties(Runner runner, String groovyFilename, Script script) throws ExecutionException {
    // the property name is prefixed by "groovy_" followed by the script filename
    // without suffix
    // ie if we load Toto.groovy, the script instance property will be groovy_Toto
    
    int first = groovyFilename.lastIndexOf('/');
    if (first == -1) {
        first = 0;
    } else if (first > 0) {
        //remove last '/'
        first += 1;
    }
    
    groovyFilename = groovyFilename.substring(first, groovyFilename.length());
    
    int last = groovyFilename.indexOf('.');
    if (last > 0) {
        String propertyName = MTSBinding.GROOVY_VAR_PREFIX + groovyFilename.substring(0, last);
        injectedScripts.put(propertyName, script);
        GlobalLogger.instance().getSessionLogger().debug(runner, TextEvent.Topic.CORE, "injecting " + propertyName + " object for script " + groovyFilename);
    } else {
        throw new ExecutionException("cannot load groovy script " + groovyFilename + " : invalid file name");
    }
}
 
Example #14
Source File: DefaultScriptCompilationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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());
}
 
Example #15
Source File: DefaultScriptCompilationHandler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
    }
}
 
Example #16
Source File: FileCacheBackedScriptClassCompiler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
}
 
Example #17
Source File: PuzzleBuildingBlock.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
/**
 * processes all expressions and updates properties
 */
private void processExpressions() {
	boolean notificationRequired = false;
	for (Map.Entry<String, Script> entry : definitions.entrySet()) {
		String variable = entry.getKey();
		Script script = entry.getValue();
		Object value = script.run();
		if (putInternal(variable, value)) {
			notificationRequired = true;
		}
	}
	if (notificationRequired) {
		PuzzleEventDispatcher.get().notify(this);
	}
}
 
Example #18
Source File: RestrictiveGroovyInterceptor.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private boolean isScriptClass(Class<?> receiver) {
        // while-doesn't really do anything, because Groovy extracts classes
        // defined in scripts as stand-alone classes.
//		while (receiver.getEnclosingClass() != null)
//			receiver = receiver.getEnclosingClass();
        return Script.class.isAssignableFrom(receiver);
    }
 
Example #19
Source File: AsmBackedEmptyScriptGenerator.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T extends Script> Class<? extends T> generate(Class<T> type) {
    Class<?> subclass = CACHED_CLASSES.get(type);
    if (subclass == null) {
        subclass = generateEmptyScriptClass(type);
        CACHED_CLASSES.put(type, subclass);
    }
    return subclass.asSubclass(type);
}
 
Example #20
Source File: GroovyExecutor.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public GroovyResult execute(final String script, final Map<String, Object> variables)
{
  if (script == null) {
    return new GroovyResult();
  }
  final Script groovyObject = compileGroovy(script, true);
  if (groovyObject == null) {
    return new GroovyResult();
  }
  return execute(groovyObject, variables);
}
 
Example #21
Source File: CachingScriptClassCompiler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T extends Script> Class<? extends T> compile(ScriptSource source, ClassLoader classLoader, Transformer transformer, Class<T> scriptBaseClass, Verifier verifier) {
    List<Object> key = Arrays.asList(source.getClassName(), classLoader, transformer.getId(), scriptBaseClass.getName());
    Class<?> c = cachedClasses.get(key);
    if (c == null) {
        c = scriptClassCompiler.compile(source, classLoader, transformer, scriptBaseClass, verifier);
        cachedClasses.put(key, c);
    }
    return c.asSubclass(scriptBaseClass);
}
 
Example #22
Source File: SqoopCommand.java    From sqoop-on-spark with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void resolveVariables(List arg) {
  List temp = new ArrayList();
  GroovyShell gs = new GroovyShell(getBinding());
  for(Object obj:arg) {
    Script scr = gs.parse("\""+(String)obj+"\"");
    try {
      temp.add(scr.run().toString());
    }
    catch(MissingPropertyException e) {
      throw new SqoopException(ShellError.SHELL_0004, e.getMessage(), e);
    }
  }
  Collections.copy(arg, temp);
}
 
Example #23
Source File: DeploymentTest.java    From vertx-lang-groovy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployVerticleScriptInstance() throws Exception {
  Class clazz = assertScript("LifeCycleVerticleScript");
  Script script = (Script) clazz.newInstance();
  ScriptVerticle verticle = new ScriptVerticle(script);
  assertDeploy((vertx, onDeploy) ->
      vertx.deployVerticle(
          verticle,
          onDeploy));
  assertTrue(isStarted());
  assertTrue(isStopped());
}
 
Example #24
Source File: AllTestSuite.java    From groovy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void loadTest(String filename) throws CompilationFailedException, IOException {
    Class type = compile(filename);
    if (TestCase.class.isAssignableFrom(type)) {
        addTestSuite((Class<? extends TestCase>)type);
    } else if (Script.class.isAssignableFrom(type)) {
        addTest(new ScriptTestAdapter(type, EMPTY_ARGS));
    } else {
        throw new RuntimeException("Don't know how to treat " + filename + " as a JUnit test");
    }
}
 
Example #25
Source File: RouteRuleFilter.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
public Map<String,Object> filter(Map<String,Object> input) {

    Binding binding = new Binding();
    binding.setVariable("input", input);

    GroovyShell shell = new GroovyShell(binding);
    
    String filterScript = "def field = input.get('field')\n"
                                  + "if (input.field == 'buyer') { return ['losDataBusinessName':'losESDataBusiness3', 'esIndex':'potential_goods_recommend1']}\n"
                                  + "if (input.field == 'seller') { return ['losDataBusinessName':'losESDataBusiness4', 'esIndex':'potential_goods_recommend2']}\n";
    Script script = shell.parse(filterScript);
    Object ret = script.run();
    System.out.println(ret);
    return (Map<String, Object>) ret;
}
 
Example #26
Source File: TestService.java    From groovy-script-example with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Binding groovyBinding = new Binding();
    groovyBinding.setVariable("testService", new TestService());
    GroovyShell groovyShell = new GroovyShell(groovyBinding);

    String scriptContent = "import pers.doublebin.example.groovy.script.service.TestService\n" +
            "def query = new TestService().testQuery(1L);\n" +
            "query";

    /*String scriptContent = "def query = testService.testQuery(2L);\n" +
            "query";*/

    Script script = groovyShell.parse(scriptContent);
    System.out.println(script.run());
}
 
Example #27
Source File: GroovyScriptFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Class<?> getScriptedObjectType(ScriptSource scriptSource)
		throws IOException, ScriptCompilationException {

	synchronized (this.scriptClassMonitor) {
		try {
			if (this.scriptClass == null || scriptSource.isModified()) {
				// New script content...
				this.wasModifiedForTypeCheck = true;
				this.scriptClass = getGroovyClassLoader().parseClass(
						scriptSource.getScriptAsString(), scriptSource.suggestedClassName());

				if (Script.class.isAssignableFrom(this.scriptClass)) {
					// A Groovy script, probably creating an instance: let's execute it.
					Object result = executeScript(scriptSource, this.scriptClass);
					this.scriptResultClass = (result != null ? result.getClass() : null);
					this.cachedResult = new CachedResultHolder(result);
				}
				else {
					this.scriptResultClass = this.scriptClass;
				}
			}
			return this.scriptResultClass;
		}
		catch (CompilationFailedException ex) {
			this.scriptClass = null;
			this.scriptResultClass = null;
			this.cachedResult = null;
			throw new ScriptCompilationException(scriptSource, ex);
		}
	}
}
 
Example #28
Source File: GroovyExecutor.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public GroovyResult execute(final GroovyResult result, final String script, final Map<String, Object> variables)
{
  if (script == null) {
    return result;
  }
  final Script groovyObject = compileGroovy(result, script, true);
  if (groovyObject == null) {
    return result;
  }
  return execute(result, groovyObject, variables);
}
 
Example #29
Source File: GroovySocketServer.java    From groovy with Apache License 2.0 5 votes vote down vote up
GroovyClientConnection(Script script, boolean autoOutput,Socket socket) throws IOException {
    this.script = script;
    this.autoOutputFlag = autoOutput;
    this.socket = socket;
    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    writer = new PrintWriter(socket.getOutputStream());
    new Thread(this, "Groovy client connection - " + socket.getInetAddress().getHostAddress()).start();
}
 
Example #30
Source File: GroovyScriptFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> getScriptedObjectType(ScriptSource scriptSource)
		throws IOException, ScriptCompilationException {

	try {
		synchronized (this.scriptClassMonitor) {
			if (this.scriptClass == null || scriptSource.isModified()) {
				// New script content...
				this.wasModifiedForTypeCheck = true;
				this.scriptClass = getGroovyClassLoader().parseClass(
						scriptSource.getScriptAsString(), scriptSource.suggestedClassName());

				if (Script.class.isAssignableFrom(this.scriptClass)) {
					// A Groovy script, probably creating an instance: let's execute it.
					Object result = executeScript(scriptSource, this.scriptClass);
					this.scriptResultClass = (result != null ? result.getClass() : null);
					this.cachedResult = new CachedResultHolder(result);
				}
				else {
					this.scriptResultClass = this.scriptClass;
				}
			}
			return this.scriptResultClass;
		}
	}
	catch (CompilationFailedException ex) {
		throw new ScriptCompilationException(scriptSource, ex);
	}
}