org.codehaus.groovy.control.CompilerConfiguration Java Examples
The following examples show how to use
org.codehaus.groovy.control.CompilerConfiguration.
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 |
@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: ForbiddenApisPlugin.java From forbidden-apis with Apache License 2.0 | 6 votes |
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 #3
Source File: StaticTypesWriterController.java From groovy with Apache License 2.0 | 6 votes |
@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 #4
Source File: ApiGroovyCompiler.java From pushfish-android with BSD 2-Clause "Simplified" License | 6 votes |
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: ConfigurationCustomizerProviderTest.java From tinkerpop with Apache License 2.0 | 6 votes |
@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 #6
Source File: GroovyTradletImpl.java From java-trader with Apache License 2.0 | 6 votes |
@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 #7
Source File: GroovyExecutor.java From hugegraph-loader with Apache License 2.0 | 6 votes |
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 #8
Source File: CustomQueryValidator.java From rdflint with MIT License | 6 votes |
@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 #9
Source File: ConfigurationGroovyCustomizer.java From tinkerpop with Apache License 2.0 | 6 votes |
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 #10
Source File: Groovy2Compiler.java From Nicobar with Apache License 2.0 | 6 votes |
@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 #11
Source File: AstStringCompiler.java From groovy with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: ClassNodeCache.java From netbeans with Apache License 2.0 | 5 votes |
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 #13
Source File: ScriptProcessor.java From walkmod-core with GNU Lesser General Public License v3.0 | 5 votes |
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 #14
Source File: ClassNodeCache.java From netbeans with Apache License 2.0 | 5 votes |
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 #15
Source File: JavaStubCompilationUnit.java From groovy with Apache License 2.0 | 5 votes |
@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 #16
Source File: GroovyCurvesSupplier.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@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 #17
Source File: GroovyScriptController.java From groovy-script-example with Apache License 2.0 | 5 votes |
@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 File: GremlinGroovyScriptEngine.java From tinkerpop with Apache License 2.0 | 5 votes |
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 #19
Source File: GroovyMain.java From groovy with Apache License 2.0 | 5 votes |
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 #20
Source File: FileSystemCompiler.java From groovy with Apache License 2.0 | 5 votes |
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 #21
Source File: GroovyClassLoader.java From groovy with Apache License 2.0 | 5 votes |
/** * 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 #22
Source File: GroovySunClassLoader.java From groovy with Apache License 2.0 | 5 votes |
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 #23
Source File: JavaAwareCompilationUnit.java From groovy with Apache License 2.0 | 5 votes |
@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 #24
Source File: DbUpdaterEngine.java From cuba with Apache License 2.0 | 5 votes |
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 #25
Source File: GroovyShellTest.java From groovy with Apache License 2.0 | 5 votes |
/** * 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); }
Example #26
Source File: CompilerTest.java From groovy with Apache License 2.0 | 5 votes |
protected void setUp() throws Exception { File dir = new File("target/test-generated-classes"); dir.mkdirs(); CompilerConfiguration config = new CompilerConfiguration(); config.setTargetDirectory(dir); config.setDebug(dumpClass); compiler = new Compiler(config); }
Example #27
Source File: CachingGroovyEngine.java From groovy with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private void setLoader(final BSFManager mgr, final ClassLoader finalParent) { this.loader = (GroovyClassLoader) AccessController.doPrivileged((PrivilegedAction) () -> { CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setClasspath(mgr.getClassPath()); return new GroovyClassLoader(finalParent, configuration); }); }
Example #28
Source File: ScriptCompilationExecuter.java From groovy with Apache License 2.0 | 5 votes |
public long execute() throws Exception { ClassLoader cl = new URLClassLoader(classpath, ClassLoader.getSystemClassLoader().getParent()); GroovyClassLoader gcl = new GroovyClassLoader(cl); CompilationUnit cu = new CompilationUnit(new CompilerConfiguration(), null, gcl, new GroovyClassLoader(this.getClass().getClassLoader())); for (File source : sources) { cu.addSource(source); } long sd = System.nanoTime(); cu.compile(CompilePhase.CLASS_GENERATION.getPhaseNumber()); long dur = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - sd); return dur; }
Example #29
Source File: JavaShell.java From groovy with Apache License 2.0 | 5 votes |
/** * Initializes a newly created {@code JavaShell} object * * @param parentClassLoader the parent class loader for delegation */ public JavaShell(ClassLoader parentClassLoader) { jscl = new JavaShellClassLoader( EMPTY_URL_ARRAY, null == parentClassLoader ? JavaShell.class.getClassLoader() : parentClassLoader ); locale = Locale.ENGLISH; charset = Charset.forName(CompilerConfiguration.DEFAULT.getSourceEncoding()); }
Example #30
Source File: TypeCheckingContext.java From groovy with Apache License 2.0 | 5 votes |
public ErrorCollector pushErrorCollector() { CompilerConfiguration config = Optional.ofNullable(getErrorCollector()) .map(ErrorCollector::getConfiguration).orElseGet(() -> getSource().getConfiguration()); ErrorCollector collector = new ErrorCollector(config); pushErrorCollector(collector); return collector; }