Java Code Examples for org.codehaus.groovy.control.CompilerConfiguration

The following examples show how to use org.codehaus.groovy.control.CompilerConfiguration. These examples are extracted from open source projects. 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
@Test
public void testPlatformDeviceConnectionImport() {
   CapabilityRegistry registry = ServiceLocator.getInstance(CapabilityRegistry.class);

   CompilerConfiguration config = new CompilerConfiguration();
   config.setTargetDirectory(new File(TMP_DIR));
   config.addCompilationCustomizers(new DriverCompilationCustomizer(registry));

   GroovyScriptEngine engine = new GroovyScriptEngine(new ClasspathResourceConnector());
   engine.setConfig(config);
   DriverBinding binding = new DriverBinding(
           ServiceLocator.getInstance(CapabilityRegistry.class),
           new GroovyDriverFactory(engine, registry, ImmutableSet.of(new ControlProtocolPlugin()))
   );
   GroovyDriverBuilder builder = binding.getBuilder();
   assertNotNull(builder.importCapability(GroovyDrivers.PLATFORM_DEVICE_CONNECTION_CAPABILITY));
}
 
Example 2
Source Project: groovy   Source File: StaticTypesWriterController.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(final AsmClassGenerator asmClassGenerator, final GeneratorContext gcon, final ClassVisitor cv, final ClassNode cn) {
    super.init(asmClassGenerator, gcon, cv, cn);
    this.callSiteWriter = new StaticTypesCallSiteWriter(this);
    this.statementWriter = new StaticTypesStatementWriter(this);
    this.typeChooser = new StaticTypesTypeChooser();
    this.invocationWriter = new StaticInvocationWriter(this);
    this.closureWriter = new StaticTypesClosureWriter(this);
    this.lambdaWriter = new StaticTypesLambdaWriter(this);
    this.methodReferenceExpressionWriter = new StaticTypesMethodReferenceExpressionWriter(this);
    this.unaryExpressionHelper = new StaticTypesUnaryExpressionHelper(this);

    CompilerConfiguration config = cn.getCompileUnit().getConfig();
    this.binaryExprHelper = config.isIndyEnabled()
            ? new IndyStaticTypesMultiTypeDispatcher(this)
            : new StaticTypesBinaryExpressionMultiTypeDispatcher(this);
}
 
Example 3
private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.1")) < 0) {
        throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + "");
    }
    Binding binding = new Binding();
    binding.setVariable("configuration", configuration);

    CompilerConfiguration configuratorConfig = new CompilerConfiguration();
    ImportCustomizer customizer = new ImportCustomizer();
    customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
    configuratorConfig.addCompilationCustomizers(customizer);

    GroovyShell shell = new GroovyShell(binding, configuratorConfig);
    try {
        shell.evaluate(configScript);
    } catch (Exception e) {
        throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e);
    }
}
 
Example 4
Source Project: java-trader   Source File: GroovyTradletImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(TradletContext context) throws Exception {
    this.group = context.getGroup();
    this.beansContainer = context.getBeansContainer();
    this.functionClasses = loadStandardScriptFunctionClasses();
    this.functionClasses.putAll(discoverPluginScriptFunctions(beansContainer.getBean(PluginService.class)));
    logger.info("Tradlet group "+group.getId()+" discoverd functions: "+new TreeSet<>(functionClasses.keySet()));

    CompilerConfiguration scriptConfig = new CompilerConfiguration();
    scriptConfig.setTargetBytecode(CompilerConfiguration.JDK8);
    scriptConfig.setRecompileGroovySource(false);
    scriptConfig.setScriptBaseClass(GroovyScriptBase.class.getName());
    scriptLoader = new GroovyClassLoader(getClass().getClassLoader(), scriptConfig);

    initVars();

    reload(context);
}
 
Example 5
Source Project: hugegraph-loader   Source File: GroovyExecutor.java    License: Apache License 2.0 6 votes vote down vote up
public void execute(String groovyScript, HugeClient client) {
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(DelegatingScript.class.getName());
    ImportCustomizer importCustomizer = new ImportCustomizer();
    importCustomizer.addImports(HugeClient.class.getName());
    importCustomizer.addImports(SchemaManager.class.getName());
    config.addCompilationCustomizers(importCustomizer);

    GroovyShell shell = new GroovyShell(getClass().getClassLoader(),
                                        this.binding, config);

    // Groovy invoke java through the delegating script.
    DelegatingScript script = (DelegatingScript) shell.parse(groovyScript);
    script.setDelegate(client);
    script.run();
}
 
Example 6
Source Project: rdflint   Source File: CustomQueryValidator.java    License: MIT License 6 votes vote down vote up
@Override
public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) {
  if (this.getParameters().getRules() == null) {
    return;
  }
  // execute sparql & custom validation
  Graph g = Factory.createGraphMem();
  tripeSet.forEach(g::add);
  Model m = ModelFactory.createModelForGraph(g);

  this.getParameters().getRules().stream()
      .filter(r -> file.matches(r.getTarget()))
      .forEach(r -> {
        Query query = QueryFactory.create(r.getQuery());
        QueryExecution qe = QueryExecutionFactory.create(query, m);

        Binding binding = new Binding();
        binding.setVariable("rs", qe.execSelect());
        binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName()));
        GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
        shell.evaluate(r.getValid());
      });
}
 
Example 7
Source Project: groovy   Source File: AstStringCompiler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Performs the String source to {@link java.util.List} of {@link ASTNode}.
 *
 * @param script
 *      a Groovy script in String form
 * @param compilePhase
 *      the int based CompilePhase to compile it to.
 * @param statementsOnly
 * @return {@link java.util.List} of {@link ASTNode}
 */
public List<ASTNode> compile(String script, CompilePhase compilePhase, boolean statementsOnly) {
    final String scriptClassName = makeScriptClassName();
    GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptClassName + ".groovy", "/groovy/script");
    CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.getCodeSource(),
            AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) GroovyClassLoader::new));
    cu.addSource(codeSource.getName(), script);
    cu.compile(compilePhase.getPhaseNumber());

    // collect all the ASTNodes into the result, possibly ignoring the script body if desired
    List<ASTNode> result = cu.getAST().getModules().stream().reduce(new LinkedList<>(), (acc, node) -> {
        BlockStatement statementBlock = node.getStatementBlock();
        if (null != statementBlock) {
            acc.add(statementBlock);
        }
        acc.addAll(
                node.getClasses().stream()
                    .filter(c -> !(statementsOnly && scriptClassName.equals(c.getName())))
                    .collect(Collectors.toList())
        );

        return acc;
    }, (o1, o2) -> o1);

    return result;
}
 
Example 8
@Test
public void shouldApplyConfigurationChanges() {
    final CompilerConfiguration configuration = new CompilerConfiguration();

    assertEquals(10, configuration.getTolerance());
    assertNull(configuration.getScriptBaseClass());
    assertEquals(false, configuration.getDebug());

    final ConfigurationGroovyCustomizer provider = new ConfigurationGroovyCustomizer(
            "Tolerance", 3,
            "ScriptBaseClass", "Something",
            "Debug", true);

    provider.applyCustomization(configuration);

    assertEquals(3, configuration.getTolerance());
    assertEquals("Something", configuration.getScriptBaseClass());
    assertEquals(true, configuration.getDebug());
}
 
Example 9
Source Project: forbidden-apis   Source File: ForbiddenApisPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private static Class<? extends DelegatingScript> loadScript() {
  final ImportCustomizer importCustomizer = new ImportCustomizer().addStarImports(ForbiddenApisPlugin.class.getPackage().getName());
  final CompilerConfiguration configuration = new CompilerConfiguration().addCompilationCustomizers(importCustomizer);
  configuration.setScriptBaseClass(DelegatingScript.class.getName());
  configuration.setSourceEncoding(StandardCharsets.UTF_8.name());
  final URL scriptUrl = ForbiddenApisPlugin.class.getResource(PLUGIN_INIT_SCRIPT);
  if (scriptUrl == null) {
    throw new RuntimeException("Cannot find resource with script: " + PLUGIN_INIT_SCRIPT);
  }
  return AccessController.doPrivileged(new PrivilegedAction<Class<? extends DelegatingScript>>() {
    @Override
    public Class<? extends DelegatingScript> run() {
      try {
        // We don't close the classloader, as we may need it later when loading other classes from inside script:
        @SuppressWarnings("resource") final GroovyClassLoader loader =
            new GroovyClassLoader(ForbiddenApisPlugin.class.getClassLoader(), configuration);
        final GroovyCodeSource csrc = new GroovyCodeSource(scriptUrl);
        @SuppressWarnings("unchecked") final Class<? extends DelegatingScript> clazz =
            loader.parseClass(csrc, false).asSubclass(DelegatingScript.class);
        return clazz;
      } catch (Exception e) {
        throw new RuntimeException("Cannot compile Groovy script: " + PLUGIN_INIT_SCRIPT);
      }
    }
  });
}
 
Example 10
Source Project: tinkerpop   Source File: ConfigurationGroovyCustomizer.java    License: Apache License 2.0 6 votes vote down vote up
public CompilerConfiguration applyCustomization(final CompilerConfiguration compilerConfiguration) {
    final Class<CompilerConfiguration> clazz = CompilerConfiguration.class;
    final List<Method> methods = Arrays.asList(clazz.getMethods());
    for (Map.Entry<String,Object> entry : properties.entrySet()) {
        final Method method = methods.stream().filter(m -> m.getName().equals("set" + entry.getKey())).findFirst()
               .orElseThrow(() -> new IllegalStateException("Invalid setting [" + entry.getKey() + "] for CompilerConfiguration"));

        try {
            method.invoke(compilerConfiguration, entry.getValue());
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    }

    return compilerConfiguration;
}
 
Example 11
Source Project: Nicobar   Source File: Groovy2Compiler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path compilationRootDir)
    throws ScriptCompilationException, IOException {
    
    List<CompilationCustomizer> customizers = new LinkedList<CompilationCustomizer>();

    for (String klassName: this.customizerClassNames) {
        CompilationCustomizer instance = this.getCustomizerInstanceFromString(klassName, moduleClassLoader);
        if (instance != null ) {
            customizers.add(instance);
        }
    }

    CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
    config.addCompilationCustomizers(customizers.toArray(new CompilationCustomizer[0]));

     new Groovy2CompilerHelper(compilationRootDir)
        .addScriptArchive(archive)
        .withParentClassloader(moduleClassLoader) // TODO: replace JBossModuleClassLoader with generic class loader
        .withConfiguration(config)
        .compile();
    return Collections.emptySet();
}
 
Example 12
Source Project: groovy   Source File: GroovyShellTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testClassLoader() {
    Binding context = new Binding();
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(DerivedScript.class.getName());
    GroovyShell shell = new GroovyShell(context, config);
    String script = "evaluate '''\n"+
                    "class XXXX{}\n"+
                    "assert evaluate('XXXX') == XXXX\n"+
                    "'''";
    shell.evaluate(script);
 
}
 
Example 13
Source Project: tinkerpop   Source File: GremlinGroovyScriptEngine.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void createClassLoader() {
    final CompilerConfiguration conf = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
    conf.addCompilationCustomizers(this.importGroovyCustomizer.create());

    // ConfigurationCustomizerProvider is treated separately
    groovyCustomizers.stream().filter(cp -> !(cp instanceof ConfigurationGroovyCustomizer))
            .forEach(p -> conf.addCompilationCustomizers(p.create()));

    groovyCustomizers.stream().filter(cp -> cp instanceof ConfigurationGroovyCustomizer).findFirst()
            .ifPresent(cp -> ((ConfigurationGroovyCustomizer) cp).applyCustomization(conf));

    this.loader = new GremlinGroovyClassLoader(getParentLoader(), conf);
}
 
Example 14
protected CompilerConfiguration getConfiguration() {
	CompilerConfiguration config = new CompilerConfiguration();

	List<String> classpathList = new ArrayList<>();
	getClasspathList(classpathList);
	config.setClasspathList(classpathList);

	return config;
}
 
Example 15
@Override
public ScriptEngine getScriptEngine() {
  CompilerConfiguration conf = new CompilerConfiguration();
  Map<String, Boolean> optimizationOptions = conf.getOptimizationOptions();
  optimizationOptions.put(INVOKEDYNAMIC, useInvokeDynamic());
  conf.setOptimizationOptions(optimizationOptions);
  conf.setTargetBytecode(JDK8);

  GroovyClassLoader classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), conf);
  return new GroovyScriptEngineImpl(classLoader);
}
 
Example 16
public void initialize(VisitorContext context, Object node) {
	if (engine == null) {
		ScriptEngineManager factory = new ScriptEngineManager(context.getClassLoader());
		engine = factory.getEngineByName(language);
		if (engine instanceof GroovyScriptEngineImpl) {
			((GroovyScriptEngineImpl) engine).setClassLoader(new GroovyClassLoader(context.getClassLoader(),
					new CompilerConfiguration()));
		}
	}

	if (queryEngine == null) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("language", "groovy");
		List<String> includes = new LinkedList<String>();
		includes.add("query.alias.groovy");
		parameters.put("includes", includes);

		Object bean = context.getBean("org.walkmod.query.ScriptingQueryEngine", parameters);
		if (bean != null) {
			if (bean instanceof QueryEngine) {
				queryEngine = (QueryEngine) bean;
			}

		} else {
			throw new WalkModException("Query Engine not found");
		}
	}

	Map<String, Object> params = new HashMap<String, Object>();
	params.put("node", node);
	queryEngine.initialize(context, params);
}
 
Example 17
@PostConstruct
public void init(){
    GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    compilerConfiguration.setSourceEncoding("utf-8");
    compilerConfiguration.setScriptBaseClass(TestScript.class.getName());

    groovyShell = new GroovyShell(groovyClassLoader, groovyBinding, compilerConfiguration);
}
 
Example 18
Source Project: powsybl-core   Source File: AstUtilTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testPrint() {
    ASTTransformationCustomizer astCustomizer = new ASTTransformationCustomizer(new FakeTransformer());
    ImportCustomizer imports = new ImportCustomizer();
    CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(astCustomizer, imports);
    Binding binding = new Binding();
    assertNull(new GroovyShell(binding, config).evaluate("print('hello')"));
}
 
Example 19
Source Project: groovy   Source File: FileSystemCompilerTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    File dir = new File("target/test-generated-classes");
    dir.mkdirs();
    Map options = new HashMap();
    options.put("stubDir", dir);

    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.setTargetDirectory(dir);
    configuration.setVerbose(dumpClass);
    configuration.setJointCompilationOptions(options);

    compiler = new FileSystemCompiler(configuration);
}
 
Example 20
Source Project: powsybl-core   Source File: GroovyCurvesSupplier.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public List<Curve> get(Network network) {
    List<Curve> curves = new ArrayList<>();

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

    ExpressionDslLoader.prepareClosures(binding);
    extensions.forEach(e -> e.load(binding, curves::add));

    GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
    shell.evaluate(codeSource);

    return curves;
}
 
Example 21
Source Project: netbeans   Source File: ClassNodeCache.java    License: Apache License 2.0 5 votes vote down vote up
public GroovyClassLoader createResolveLoader(
        @NonNull final ClassPath allResources,
        @NonNull final CompilerConfiguration configuration) {
    GroovyClassLoader resolveLoader = resolveLoaderRef == null ? null : resolveLoaderRef.get();
    if (resolveLoader == null) {
        LOG.log(Level.FINE,"Resolver ClassLoader created.");  //NOI18N
        resolveLoader = new ParsingClassLoader(
                allResources,
                configuration,
                this);
        resolveLoaderRef = new SoftReference<>(resolveLoader);
    }
    return resolveLoader;
}
 
Example 22
Source Project: netbeans   Source File: ClassNodeCache.java    License: Apache License 2.0 5 votes vote down vote up
public ParsingClassLoader(
        @NonNull ClassPath path,
        @NonNull CompilerConfiguration config,
        @NonNull ClassNodeCache cache) {
    super(path.getClassLoader(true), config);
    this.config = config;
    this.path = path;
    this.cache = cache;
}
 
Example 23
Source Project: groovy   Source File: JavaStubCompilationUnit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configure(final CompilerConfiguration config) {
    super.configure(config);
    // GroovyClassLoader should be able to find classes compiled from java sources
    File targetDir = configuration.getTargetDirectory();
    if (targetDir != null) {
        final String classOutput = targetDir.getAbsolutePath();
        getClassLoader().addClasspath(classOutput);
    }
}
 
Example 24
Source Project: groovy   Source File: GroovyMain.java    License: Apache License 2.0 5 votes vote down vote up
public static void processConfigScripts(List<String> scripts, CompilerConfiguration conf) throws IOException {
    if (scripts.isEmpty()) return;

    GroovyShell shell = createConfigScriptsShell(conf);

    for (String script : scripts) {
        shell.evaluate(new File(script));
    }
}
 
Example 25
Source Project: groovy   Source File: FileSystemCompiler.java    License: Apache License 2.0 5 votes vote down vote up
public static void doCompilation(CompilerConfiguration configuration, CompilationUnit unit, String[] filenames, boolean lookupUnnamedFiles) throws Exception {
    File tmpDir = null;
    // if there are any joint compilation options set stubDir if not set
    try {
        if (configuration.getJointCompilationOptions() != null
                && !configuration.getJointCompilationOptions().containsKey("stubDir")) {
            tmpDir = DefaultGroovyStaticMethods.createTempDir(null, "groovy-generated-", "-java-source");
            configuration.getJointCompilationOptions().put("stubDir", tmpDir);
        }

        FileSystemCompiler compiler = new FileSystemCompiler(configuration, unit);

        if (lookupUnnamedFiles) {
            for (String filename : filenames) {
                File file = new File(filename);
                if (file.isFile()) {
                    URL url = file.getAbsoluteFile().getParentFile().toURI().toURL();
                    compiler.unit.getClassLoader().addURL(url);
                }
            }
        } else {
            compiler.unit.getClassLoader()
                    .setResourceLoader(filename -> null);
        }
        compiler.compile(filenames);
    } finally {
        try {
            if (tmpDir != null) deleteRecursive(tmpDir);
        } catch (Throwable t) {
            System.err.println("error: could not delete temp files - " + tmpDir.getPath());
        }
    }
}
 
Example 26
Source Project: groovy   Source File: GroovyClassLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * creates a GroovyClassLoader.
 *
 * @param parent                    the parent class loader
 * @param config                    the compiler configuration
 * @param useConfigurationClasspath determines if the configurations classpath should be added
 */
public GroovyClassLoader(ClassLoader parent, CompilerConfiguration config, boolean useConfigurationClasspath) {
    super(EMPTY_URL_ARRAY, parent);
    if (config == null) config = CompilerConfiguration.DEFAULT;
    this.config = config;
    if (useConfigurationClasspath) {
        for (String path : config.getClasspath()) {
            this.addClasspath(path);
        }
    }

    initSourceEncoding(config);
}
 
Example 27
Source Project: groovy   Source File: GroovySunClassLoader.java    License: Apache License 2.0 5 votes vote down vote up
private void loadAbstract(int parsingOptions) throws IOException {
    try (final InputStream asStream = GroovySunClassLoader.class.getClassLoader().getResourceAsStream(resName("org.codehaus.groovy.runtime.callsite.AbstractCallSite"))) {
        ClassReader reader = new ClassReader(asStream);
        final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        final ClassVisitor cv = new ClassVisitor(CompilerConfiguration.ASM_API_VERSION, cw) {
            public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
                super.visit(version, access, name, signature, "sun/reflect/GroovyMagic", interfaces);
            }
        };
        reader.accept(cv, parsingOptions);
        define(cw.toByteArray(), "org.codehaus.groovy.runtime.callsite.AbstractCallSite");
    }
}
 
Example 28
Source Project: groovy   Source File: JavaAwareCompilationUnit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configure(final CompilerConfiguration configuration) {
    super.configure(configuration);
    // GroovyClassLoader should be able to find classes compiled from java sources
    File targetDir = this.configuration.getTargetDirectory();
    if (targetDir != null) {
        final String classOutput = targetDir.getAbsolutePath();
        getClassLoader().addClasspath(classOutput);
    }
}
 
Example 29
Source Project: cuba   Source File: DbUpdaterEngine.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean executeGroovyScript(ScriptResource file) {
    try {
        ClassLoader classLoader = getClass().getClassLoader();
        CompilerConfiguration cc = new CompilerConfiguration();
        cc.setRecompileGroovySource(true);

        Binding bind = new Binding();
        bind.setProperty("ds", getDataSource());
        bind.setProperty("log", LoggerFactory.getLogger(String.format("%s$%s", DbUpdaterEngine.class.getName(),
                StringUtils.removeEndIgnoreCase(file.getName(), ".groovy"))));
        if (!StringUtils.endsWithIgnoreCase(file.getName(), "." + UPGRADE_GROOVY_EXTENSION)) {
            bind.setProperty("postUpdate", new PostUpdateScripts() {
                @Override
                public void add(Closure closure) {
                    super.add(closure);

                    log.warn("Added post update action will be ignored for data store [{}]", storeNameToString(storeName));
                }
            });
        }

        GroovyShell shell = new GroovyShell(classLoader, bind, cc);
        Script script = shell.parse(file.getContent());
        script.run();
    } catch (Exception e) {
        throw new RuntimeException(
                String.format("%sError executing Groovy script %s\n%s", ERROR, file.name, e.getMessage()), e);
    }
    return true;
}
 
Example 30
Source Project: groovy   Source File: GroovyShellTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test for GROOVY-6615
 * @throws Exception
 */
public void testScriptWithCustomBodyMethod() throws Exception {
    Binding context = new Binding();
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(BaseScriptCustomBodyMethod.class.getName());
    GroovyShell shell = new GroovyShell(context, config);
    Object result = shell.evaluate("'I like ' + cheese");
    assertEquals("I like Cheddar", result);
}