Java Code Examples for org.codehaus.groovy.control.CompilerConfiguration#addCompilationCustomizers()

The following examples show how to use org.codehaus.groovy.control.CompilerConfiguration#addCompilationCustomizers() . 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: TestGroovyCapabilityBindings.java    From arcusplatform with Apache License 2.0 7 votes vote down vote up
@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 File: GroovyScriptEngineFactory.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private GroovyScriptEngine create() {
  // custom the configuration of the compiler
  CompilerConfiguration cc = new CompilerConfiguration();
  cc.setTargetDirectory(new File(applicationDirectories.getTemporaryDirectory(), "groovy-classes"));
  cc.setSourceEncoding("UTF-8");
  cc.setScriptBaseClass(ScriptWithCleanup.class.getName());
  cc.addCompilationCustomizers(secureASTCustomizer());
  GroovyClassLoader gcl = new GroovyClassLoader(classLoader, cc);

  engine = new GroovyScriptEngine(gcl);

  // HACK: For testing
  log.info("Created engine: {}", engine);

  return engine;
}
 
Example 3
Source File: Groovy2Compiler.java    From Nicobar with 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 4
Source File: ApiGroovyCompiler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 5
Source File: MarkupTemplateEngine.java    From groovy with Apache License 2.0 6 votes vote down vote up
public MarkupTemplateEngine(final ClassLoader parentLoader, final TemplateConfiguration tplConfig, final TemplateResolver resolver) {
    compilerConfiguration = new CompilerConfiguration();
    templateConfiguration = tplConfig;
    compilerConfiguration.addCompilationCustomizers(new TemplateASTTransformer(tplConfig));
    compilerConfiguration.addCompilationCustomizers(
            new ASTTransformationCustomizer(Collections.singletonMap("extensions", "groovy.text.markup.MarkupTemplateTypeCheckingExtension"), CompileStatic.class));
    if (templateConfiguration.isAutoNewLine()) {
        compilerConfiguration.addCompilationCustomizers(
                new CompilationCustomizer(CompilePhase.CONVERSION) {
                    @Override
                    public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
                        new AutoNewLineTransformer(source).visitClass(classNode);
                    }
                }
        );
    }
    groovyClassLoader = AccessController.doPrivileged((PrivilegedAction<TemplateGroovyClassLoader>) () -> new TemplateGroovyClassLoader(parentLoader, compilerConfiguration));
    if (DEBUG_BYTECODE) {
        compilerConfiguration.setBytecodePostprocessor(BytecodeDumper.STANDARD_ERR);
    }
    templateResolver = resolver == null ? new DefaultTemplateResolver() : resolver;
    templateResolver.configure(groovyClassLoader, templateConfiguration);
}
 
Example 6
Source File: Groovy.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void configureCompiler() {
    if (scriptBaseClass != null) {
        configuration.setScriptBaseClass(scriptBaseClass);
    }
    if (configscript != null) {
        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);
        File confSrc = new File(configscript);
        try {
            shell.evaluate(confSrc);
        } catch (IOException e) {
            throw new BuildException("Unable to configure compiler using configuration file: " + confSrc, e);
        }
    }
}
 
Example 7
Source File: GroovySandbox.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private CompilerConfiguration getSandboxConfiguration() throws IOException {
	ImportCustomizer imports = new ImportCustomizer();
	SecureASTCustomizer secure = new SecureASTCustomizer();
	secure.setClosuresAllowed(true);
	secure.setMethodDefinitionAllowed(true);
	String[] staticImportsWhitelist = new String[] {};
	secure.setStaticImportsWhitelist(Arrays.asList(staticImportsWhitelist));
	secure.setIndirectImportCheckEnabled(true);

	// add also Object.class
	secure.setImportsWhitelist(getStringClasses("", CLASSES_WHITELIST, addedClasses, new Class[] { Object.class }));

	List<String> staticImportMethods = getStaticImportMethods(CLASSES_WHITELIST, addedClasses);
	addPredefinedMethods(staticImportMethods);
	secure.setStaticImportsWhitelist(staticImportMethods);

	secure.setConstantTypesClassesWhiteList(getClasses(CONSTANT_TYTPE_CLASSES_WHITELIST, CLASSES_WHITELIST, addedClasses));
	// add also Object.class
	secure.setReceiversClassesWhiteList(getClasses(CLASSES_WHITELIST, addedClasses, new Class[] { Object.class }));

	CompilerConfiguration res = new CompilerConfiguration();
	res.addCompilationCustomizers(imports, secure);
	return res;
}
 
Example 8
Source File: GroovyExecutor.java    From hugegraph-loader with 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 9
Source File: ApiGroovyCompiler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 10
Source File: GroovyService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
    ImportCustomizer importCustomizer = new ImportCustomizer();
    importCustomizer.addStarImports("net.dv8tion.jda.api.entities");

    configuration = new CompilerConfiguration();
    configuration.addCompilationCustomizers(importCustomizer);

    sharedData = new Binding();
    sharedData.setProperty("ctx", context);
}
 
Example 11
Source File: GroovyStaticScriptEngine.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected static CompilerConfiguration createStaticConfiguration() {
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    ASTTransformationCustomizer astTransformationCustomizer = new ASTTransformationCustomizer(
            Collections.singletonMap("extensions", Collections.singletonList("EngineVariablesExtension.groovy")),
            CompileStatic.class, "org.codehaus.groovy.transform.sc.StaticCompileTransformation");
    compilerConfiguration.addCompilationCustomizers(astTransformationCustomizer);
    return compilerConfiguration;
}
 
Example 12
Source File: AstUtilTest.java    From powsybl-core with 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 13
Source File: GremlinGroovyScriptEngine.java    From tinkerpop with 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
Source File: CustomGroovyShellFactory.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public GroovyShell createGroovyShell(Exchange exchange) {
    ImportCustomizer importCustomizer = new ImportCustomizer();
    importCustomizer.addStaticStars("org.wildfly.camel.test.groovy.subA.CustomUtils");
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.addCompilationCustomizers(importCustomizer);
    ClassLoader classLoader = exchange.getContext().getApplicationContextClassLoader();
    return new GroovyShell(classLoader, configuration);
}
 
Example 15
Source File: GroovyScriptUtils.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
public static CompilerConfiguration getCompilerConfiguration(boolean enableScriptSandbox) {
    CompilerConfiguration config = new CompilerConfiguration();
    if (enableScriptSandbox) {
        config.addCompilationCustomizers(new SandboxTransformer());
    }
    return config;
}
 
Example 16
Source File: Groovy2CompilerHelperTest.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Compile with custom config
 * @throws Exception
 */
@Test
public void testCompileWithCompilerCustomizer() throws Exception {
    Path scriptRootPath = GroovyTestResourceUtil.findRootPathForScript(TestScript.HELLO_WORLD);
    PathScriptArchive scriptArchive = new PathScriptArchive.Builder(scriptRootPath)
        .setRecurseRoot(false)
        .addFile(TestScript.HELLO_WORLD.getScriptPath())
        .build();

    TestCompilationCustomizer customizer = new TestCompilationCustomizer();

    CompilerConfiguration compilerConfig = new CompilerConfiguration();
    compilerConfig.addCompilationCustomizers(customizer);

    Set<GroovyClass> compiledClasses = new Groovy2CompilerHelper(Files.createTempDirectory("Groovy2CompilerHelperTest"))
        .addScriptArchive(scriptArchive)
        .withConfiguration(compilerConfig)
        .compile();

    assertTrue(customizer.isExecuted(), "customizer has not been executed");
    assertFalse(CollectionUtils.isEmpty(compiledClasses));

    TestByteLoadingClassLoader testClassLoader = new TestByteLoadingClassLoader(getClass().getClassLoader(), compiledClasses);
    Class<?> loadedClass = testClassLoader.loadClass(TestScript.HELLO_WORLD.getClassName());
    assertNotNull(loadedClass);
    Object instance = loadedClass.newInstance();
    Method method = loadedClass.getMethod("getMessage");
    String message = (String)method.invoke(instance);
    assertEquals(message, "Hello, World!");
}
 
Example 17
Source File: TestGroovyCapabilityBindings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
public void testCompile() throws Exception {
   CompilerConfiguration config = new CompilerConfiguration();
   config.setTargetDirectory(new File(TMP_DIR));
   config.addCompilationCustomizers(new DriverCompilationCustomizer(ServiceLocator.getInstance(CapabilityRegistry.class)));
   org.codehaus.groovy.tools.Compiler compiler = new org.codehaus.groovy.tools.Compiler(config);
   compiler.compile(new File("src/test/resources/Metadata.capability"));
   ClassLoader loader = new ClassLoader() {

      @Override
      protected Class<?> findClass(String name) throws ClassNotFoundException {
         File f = new File(TMP_DIR + "/" + name.replaceAll("\\.", "/") + ".class");
         if(!f.exists()) {
            throw new ClassNotFoundException();
         }
         try (FileInputStream is = new FileInputStream(f)) {
            byte [] bytes = IOUtils.toByteArray(is);
            return defineClass(name, bytes, 0, bytes.length);
         }
         catch(Exception e) {
            throw new ClassNotFoundException("Unable to load " + name, e);
         }
      }

   };
   Class<?> metadataClass = loader.loadClass("Metadata");
   System.out.println(metadataClass);
   System.out.println("Superclass: " + metadataClass.getSuperclass());
   System.out.println("Interfaces: " + Arrays.asList(metadataClass.getInterfaces()));
   System.out.println("Methods: ");
   for(Method m: Arrays.asList(metadataClass.getMethods())) {
      System.out.println("\t" + m);
   }

   GroovyCapabilityBuilder builder =
         new GroovyCapabilityBuilder(ServiceLocator.getInstance(CapabilityRegistry.class))
            .withName("Metadata");
   CapabilityEnvironmentBinding binding = new CapabilityEnvironmentBinding(builder);
   Script s = (Script) metadataClass.getConstructor(Binding.class).newInstance(binding);
   s.setMetaClass(new CapabilityScriptMetaClass(s.getClass()));
   s.getMetaClass().initialize();
   s.setBinding(binding);
   s.run();
   System.out.println("Definition: " + builder.create().getCapabilityDefinition());
}
 
Example 18
Source File: TestGroovyDriverBindings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
//   @Ignore
   public void testCompile() throws Exception {
      CapabilityRegistry registry = ServiceLocator.getInstance(CapabilityRegistry.class);

      CompilerConfiguration config = new CompilerConfiguration();
      config.setTargetDirectory(new File(TMP_DIR));
      config.addCompilationCustomizers(new DriverCompilationCustomizer(registry));
      org.codehaus.groovy.tools.Compiler compiler = new org.codehaus.groovy.tools.Compiler(config);
      compiler.compile(new File("src/test/resources/Metadata.driver"));
      ClassLoader loader = new ClassLoader() {

         @Override
         protected Class<?> findClass(String name) throws ClassNotFoundException {
            File f = new File(TMP_DIR + "/" + name.replaceAll("\\.", "/") + ".class");
            if(!f.exists()) {
               throw new ClassNotFoundException();
            }
            try (FileInputStream is = new FileInputStream(f)) {
               byte [] bytes = IOUtils.toByteArray(is);
               return defineClass(name, bytes, 0, bytes.length);
            }
            catch(Exception e) {
               throw new ClassNotFoundException("Unable to load " + name, e);
            }
         }

      };
      Class<?> metadataClass = loader.loadClass("Metadata");
      System.out.println(metadataClass);
      System.out.println("Superclass: " + metadataClass.getSuperclass());
      System.out.println("Interfaces: " + Arrays.asList(metadataClass.getInterfaces()));
      System.out.println("Methods: ");
      for(Method m: Arrays.asList(metadataClass.getMethods())) {
         System.out.println("\t" + m);
      }

      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()))
      );
      Script s = (Script) metadataClass.getConstructor(Binding.class).newInstance(binding);
      s.setMetaClass(new DriverScriptMetaClass(s.getClass()));
      s.setBinding(binding);
      s.run();
      System.out.println("Definition: " + binding.getBuilder().createDefinition());
   }
 
Example 19
Source File: GroovyMain.java    From groovy with Apache License 2.0 3 votes vote down vote up
private static GroovyShell createConfigScriptsShell(CompilerConfiguration conf) {
    Binding binding = new Binding();
    binding.setVariable("configuration", conf);

    CompilerConfiguration configuratorConfig = new CompilerConfiguration();
    ImportCustomizer customizer = new ImportCustomizer();

    customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");

    configuratorConfig.addCompilationCustomizers(customizer);

    return new GroovyShell(binding, configuratorConfig);
}