private GroovyShell createEngine(AbstractBuild<?, ?> build, TaskListener listener) { ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader; ScriptSandbox sandbox = null; CompilerConfiguration cc = new CompilerConfiguration(); cc.addCompilationCustomizers( new ImportCustomizer() .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model")); ExtendedEmailPublisher publisher = build.getProject().getPublishersList().get(ExtendedEmailPublisher.class); if (publisher.getDescriptor().isSecurityEnabled()) { cc.addCompilationCustomizers(new SandboxTransformer()); sandbox = new ScriptSandbox(); } Binding binding = new Binding(); binding.setVariable("build", build); binding.setVariable("project", build.getParent()); binding.setVariable("rooturl", publisher.getDescriptor().getHudsonUrl()); binding.setVariable("out", listener.getLogger()); GroovyShell shell = new GroovyShell(cl, binding, cc); if (sandbox != null) { sandbox.register(); } return shell; }
@Override public void compileToDir( ScriptSource source, ClassLoader classLoader, File classesDir, File metadataDir, CompileOperation<?> extractingTransformer, Class<? extends Script> scriptBaseClass, Action<? super ClassNode> verifier) { Clock clock = new Clock(); GFileUtils.deleteDirectory(classesDir); GFileUtils.mkdirs(classesDir); CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass); configuration.setTargetDirectory(classesDir); try { compileScript( source, classLoader, configuration, classesDir, metadataDir, extractingTransformer, verifier); } catch (GradleException e) { GFileUtils.deleteDirectory(classesDir); GFileUtils.deleteDirectory(metadataDir); throw e; } logger.debug( "Timing: Writing script to cache at {} took: {}", classesDir.getAbsolutePath(), clock.getTime()); }
private boolean executePresendScript( AbstractBuild<?, ?> build, BuildListener listener, MimeMessage msg, EmailTrigger trigger, Map<String, EmailTrigger> triggered) throws RuntimeException { boolean cancel = false; presendScript = new ContentBuilder().transformText(presendScript, this, build, listener); if (StringUtils.isNotBlank(presendScript)) { listener.getLogger().println("Executing pre-send script"); ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader; ScriptSandbox sandbox = null; CompilerConfiguration cc = new CompilerConfiguration(); cc.addCompilationCustomizers( new ImportCustomizer() .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model")); if (ExtendedEmailPublisher.DESCRIPTOR.isSecurityEnabled()) { debug(listener.getLogger(), "Setting up sandbox for pre-send script"); cc.addCompilationCustomizers(new SandboxTransformer()); sandbox = new ScriptSandbox(); } Binding binding = new Binding(); binding.setVariable("build", build); binding.setVariable("msg", msg); binding.setVariable("logger", listener.getLogger()); binding.setVariable("cancel", cancel); binding.setVariable("trigger", trigger); binding.setVariable("triggered", Collections.unmodifiableMap(triggered)); GroovyShell shell = new GroovyShell(cl, binding, cc); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); if (sandbox != null) { sandbox.register(); } try { Object output = shell.evaluate(presendScript); if (output != null) { pw.println("Result: " + output); cancel = ((Boolean) shell.getVariable("cancel")).booleanValue(); debug(listener.getLogger(), "Pre-send script set cancel to %b", cancel); } } catch (SecurityException e) { listener .getLogger() .println("Pre-send script tried to access secured objects: " + e.getMessage()); } catch (Throwable t) { t.printStackTrace(pw); listener.getLogger().println(out.toString()); // should we cancel the sending of the email??? } debug(listener.getLogger(), out.toString()); } return !cancel; }
public static CompilerConfiguration generateCompilerConfigurationFromOptions(CommandLine cli) throws IOException { // // Setup the configuration data CompilerConfiguration configuration = new CompilerConfiguration(); if (cli.hasOption("classpath")) { configuration.setClasspath(cli.getOptionValue("classpath")); } if (cli.hasOption('d')) { configuration.setTargetDirectory(cli.getOptionValue('d')); } if (cli.hasOption("encoding")) { configuration.setSourceEncoding(cli.getOptionValue("encoding")); } if (cli.hasOption("basescript")) { configuration.setScriptBaseClass(cli.getOptionValue("basescript")); } // joint compilation parameters if (cli.hasOption('j')) { Map<String, Object> compilerOptions = new HashMap<String, Object>(); String[] opts = cli.getOptionValues("J"); compilerOptions.put("namedValues", opts); opts = cli.getOptionValues("F"); compilerOptions.put("flags", opts); configuration.setJointCompilationOptions(compilerOptions); } if (cli.hasOption("indy")) { configuration.getOptimizationOptions().put("int", false); configuration.getOptimizationOptions().put("indy", true); } if (cli.hasOption("configscript")) { String path = cli.getOptionValue("configscript"); File groovyConfigurator = new File(path); 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); shell.evaluate(groovyConfigurator); } return configuration; }
private static GroovyClassLoader getGroovyClassLoader() { GroovySystem.getMetaClassRegistry() .setMetaClassCreationHandle(new ExpandoMetaClassCreationHandle()); CompilerConfiguration config = new CompilerConfiguration(); config.setDebug(true); config.setVerbose(true); ClassLoader parent = ClassLoader.getSystemClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); loader.setShouldRecompile(true); return loader; }
private void runCompiler(String[] commandLine) { // hand crank it so we can add our own compiler configuration try { Options options = FileSystemCompiler.createCompilationOptions(); CommandLineParser cliParser = new DefaultParser(); CommandLine cli; cli = cliParser.parse(options, commandLine); configuration = FileSystemCompiler.generateCompilerConfigurationFromOptions(cli); configuration.setScriptExtensions(getScriptExtensions()); String tmpExtension = getScriptExtension(); if (tmpExtension.startsWith("*.")) tmpExtension = tmpExtension.substring(1); configuration.setDefaultScriptExtension(tmpExtension); // Load the file name list String[] filenames = FileSystemCompiler.generateFileNamesFromOptions(cli); boolean fileNameErrors = filenames == null; fileNameErrors = fileNameErrors || !FileSystemCompiler.validateFiles(filenames); if (targetBytecode != null) { configuration.setTargetBytecode(targetBytecode); } if (!fileNameErrors) { FileSystemCompiler.doCompilation( configuration, makeCompileUnit(), filenames, forceLookupUnnamedFiles); } } catch (Exception re) { Throwable t = re; if ((re.getClass() == RuntimeException.class) && (re.getCause() != null)) { // unwrap to the real exception t = re.getCause(); } StringWriter writer = new StringWriter(); new ErrorReporter(t, false).write(new PrintWriter(writer)); String message = writer.toString(); taskSuccess = false; if (errorProperty != null) { getProject().setNewProperty(errorProperty, "true"); } if (failOnError) { log.error(message); throw new BuildException("Compilation Failed", t, getLocation()); } else { log.error(message); } } }
public GroovyEngine(ServiceDispatcher dispatcher) { super(dispatcher); try { String scriptBaseClass = ServiceConfigUtil.getEngineParameter("groovy", "scriptBaseClass"); if (scriptBaseClass != null) { CompilerConfiguration conf = new CompilerConfiguration(); conf.setScriptBaseClass(scriptBaseClass); groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader(), conf); } } catch (GenericConfigException gce) { Debug.logWarning( gce, "Error retrieving the configuration for the groovy service engine: ", module); } }
@Inject public GroovyScriptEngineService(Settings settings) { super(settings); ImportCustomizer imports = new ImportCustomizer(); imports.addStarImports("org.joda.time"); imports.addStaticStars("java.lang.Math"); CompilerConfiguration config = new CompilerConfiguration(); config.addCompilationCustomizers(imports); this.sandboxed = settings.getAsBoolean(GROOVY_SCRIPT_SANDBOX_ENABLED, true); if (this.sandboxed) { config.addCompilationCustomizers( GroovySandboxExpressionChecker.getSecureASTCustomizer(settings)); } this.loader = new GroovyClassLoader(settings.getClassLoader(), config); }
protected boolean isSourceNewer(ScriptCacheEntry entry) throws ResourceException { if (entry == null) return true; long now = 0; for (String scriptName : entry.dependencies) { ScriptCacheEntry depEntry = scriptCache.get(scriptName); if (depEntry.sourceNewer) return true; if (now == 0) { now = System.currentTimeMillis(); } long nextSourceCheck = depEntry.lastCheck + config.getMinimumRecompilationInterval(); if (nextSourceCheck > now) continue; long lastMod = getLastModified(scriptName); if (depEntry.lastModified < lastMod) { depEntry = new ScriptCacheEntry(depEntry, lastMod, true); scriptCache.put(scriptName, depEntry); return true; } else { depEntry = new ScriptCacheEntry(depEntry, now, false); scriptCache.put(scriptName, depEntry); } } return false; }
ClassManager( PluginContext context, ResourceKind kind, Class<T> baseClass, Class<? extends Script> baseScriptClass) { CompilerConfiguration config = new CompilerConfiguration(); config.setRecompileGroovySource(true); config.setScriptBaseClass(GroovyScriptCommand.class.getName()); // this.context = context; this.baseScriptClass = baseScriptClass; this.config = config; this.baseClass = baseClass; this.kind = kind; }
protected ClassVisitor createClassVisitor() { CompilerConfiguration config = getConfiguration(); int computeMaxStackAndFrames = ClassWriter.COMPUTE_MAXS; if (CompilerConfiguration.isPostJDK7(config.getTargetBytecode()) || Boolean.TRUE.equals(config.getOptimizationOptions().get("indy"))) { computeMaxStackAndFrames += ClassWriter.COMPUTE_FRAMES; } return new ClassWriter(computeMaxStackAndFrames) { private ClassNode getClassNode(String name) { // try classes under compilation CompileUnit cu = getAST(); ClassNode cn = cu.getClass(name); if (cn != null) return cn; // try inner classes cn = cu.getGeneratedInnerClass(name); if (cn != null) return cn; // try class loader classes try { cn = ClassHelper.make(cu.getClassLoader().loadClass(name, false, true), false); } catch (Exception e) { throw new GroovyBugError(e); } return cn; } private ClassNode getCommonSuperClassNode(ClassNode c, ClassNode d) { // adapted from ClassWriter code if (c.isDerivedFrom(d)) return d; if (d.isDerivedFrom(c)) return c; if (c.isInterface() || d.isInterface()) return ClassHelper.OBJECT_TYPE; do { c = c.getSuperClass(); } while (c != null && !d.isDerivedFrom(c)); if (c == null) return ClassHelper.OBJECT_TYPE; return c; } @Override protected String getCommonSuperClass(String arg1, String arg2) { ClassNode a = getClassNode(arg1.replace('/', '.')); ClassNode b = getClassNode(arg2.replace('/', '.')); return getCommonSuperClassNode(a, b).getName().replace('.', '/'); } }; }
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( new GroovyResourceLoader() { public URL loadGroovySource(String filename) throws MalformedURLException { return 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()); } } }
public FileSystemCompiler(CompilerConfiguration configuration, CompilationUnit cu) throws ConfigurationException { if (cu != null) { unit = cu; } else if (configuration.getJointCompilationOptions() != null) { unit = new JavaAwareCompilationUnit(configuration); } else { unit = new CompilationUnit(configuration); } }
/** * Indicates if a class is recompilable. Recompilable means, that the classloader will try to * locate a groovy source file for this class and then compile it again, adding the resulting * class as entry to the cache. Giving null as class is like a recompilation, so the method should * always return true here. Only classes that are implementing GroovyObject are compilable and * only if the timestamp in the class is lower than Long.MAX_VALUE. * * <p>NOTE: First the parent loaders will be asked and only if they don't return a class the * recompilation will happen. Recompilation also only happen if the source file is newer. * * @param cls the class to be tested. If null the method should return true * @return true if the class should be compiled again * @see #isSourceNewer(URL, Class) */ protected boolean isRecompilable(Class cls) { if (cls == null) return true; if (cls.getClassLoader() == this) return false; if (recompile == null && !config.getRecompileGroovySource()) return false; if (recompile != null && !recompile) return false; if (!GroovyObject.class.isAssignableFrom(cls)) return false; long timestamp = getTimeStamp(cls); if (timestamp == Long.MAX_VALUE) return false; return true; }
protected GroovyClassLoader buildClassLoaderFor() { // GROOVY-5044 if (!fork && !getIncludeantruntime()) { throw new IllegalArgumentException( "The includeAntRuntime=false option is not compatible with fork=false"); } ClassLoader parent = getIncludeantruntime() ? getClass().getClassLoader() : new AntClassLoader( new RootLoader(EMPTY_URL_ARRAY, null), getProject(), getClasspath()); if (parent instanceof AntClassLoader) { AntClassLoader antLoader = (AntClassLoader) parent; String[] pathElm = antLoader.getClasspath().split(File.pathSeparator); List<String> classpath = configuration.getClasspath(); /* * Iterate over the classpath provided to groovyc, and add any missing path * entries to the AntClassLoader. This is a workaround, since for some reason * 'directory' classpath entries were not added to the AntClassLoader' classpath. */ for (String cpEntry : classpath) { boolean found = false; for (String path : pathElm) { if (cpEntry.equals(path)) { found = true; break; } } /* * fix for GROOVY-2284 * seems like AntClassLoader doesn't check if the file * may not exist in the classpath yet */ if (!found && new File(cpEntry).exists()) { try { antLoader.addPathElement(cpEntry); } catch (BuildException e) { log.warn("The classpath entry " + cpEntry + " is not a valid Java resource"); } } } } GroovyClassLoader loader = new GroovyClassLoader(parent, configuration); if (!forceLookupUnnamedFiles) { // in normal case we don't need to do script lookups loader.setResourceLoader( new GroovyResourceLoader() { public URL loadGroovySource(String filename) throws MalformedURLException { return null; } }); } return loader; }
/** * Configures its debugging mode and classloader classpath from a given compiler configuration. * This cannot be done more than once due to limitations in {@link java.net.URLClassLoader * URLClassLoader}. */ public void configure(CompilerConfiguration configuration) { super.configure(configuration); this.debug = configuration.getDebug(); if (!this.configured && this.classLoader instanceof GroovyClassLoader) { appendCompilerConfigurationClasspathToClassLoader( configuration, (GroovyClassLoader) this.classLoader); } this.configured = true; }
/** * 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); } } }
private GroovyClassLoader createClassLoader( ClassLoader parentLoader, final boolean staticCompile, Class<? extends Script> scriptBaseClass) { final CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); if (!scriptBaseClass.equals(Script.class)) { compilerConfiguration.setScriptBaseClass(scriptBaseClass.getName()); } compilerConfiguration.addCompilationCustomizers( new CompilationCustomizer(CompilePhase.CONVERSION) { @Override public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws org.codehaus.groovy.control.CompilationFailedException { if (staticCompile) { classNode.addAnnotation(new AnnotationNode(new ClassNode(CompileStatic.class))); } classNode.addAnnotation(new AnnotationNode(new ClassNode(InheritConstructors.class))); } }); return new GroovyClassLoader(parentLoader, compilerConfiguration); }
public String call() throws RuntimeException { // if we run locally, cl!=null. Otherwise the delegating classloader will be available as // context classloader. if (cl == null) cl = Thread.currentThread().getContextClassLoader(); CompilerConfiguration cc = new CompilerConfiguration(); cc.addCompilationCustomizers( new ImportCustomizer() .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model")); GroovyShell shell = new GroovyShell(cl, new Binding(), cc); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); shell.setVariable("out", pw); try { Object output = shell.evaluate(script); if (output != null) pw.println("Result: " + output); } catch (Throwable t) { t.printStackTrace(pw); } return out.toString(); }
@Override protected ClassLoader getClassLoader() throws ServletException { if (cl == null) { final CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); compilerConfiguration.setRecompileGroovySource(true); cl = new GroovyClassLoader(super.getClassLoader(), compilerConfiguration); String scriptsPath = getServletConfig().getInitParameter("scriptsPath"); if (scriptsPath != null) { // Zemian Deng 2012/11/22 - Allow scriptsPath to set in relative to /WEB-INF folder. if (scriptsPath.startsWith("/WEB-INF")) { scriptsPath = getServletContext().getRealPath(scriptsPath); } final String scriptsPathFinal = scriptsPath; cl.setResourceLoader( new GroovyResourceLoader() { public URL loadGroovySource(final String name) throws MalformedURLException { return (URL) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { String filename = name.replace('.', '/') + compilerConfiguration.getDefaultScriptExtension(); try { final File file = new File(scriptsPathFinal + "/" + filename); if (!file.exists() || !file.isFile()) { return null; } return new URL("file:///" + scriptsPathFinal + "/" + filename); } catch (MalformedURLException e) { return null; } } }); } }); } } return cl; }
@Test public void specialScript() throws Exception { CompilerConfiguration cc = GroovySandbox.createSecureCompilerConfiguration(); cc.setScriptBaseClass(SpecialScript.class.getName()); GroovyShell shell = new GroovyShell(cc); Whitelist wl = new AbstractWhitelist() { @Override public boolean permitsMethod(Method method, Object receiver, Object[] args) { return method.getDeclaringClass() == GroovyObject.class && method.getName().equals("getProperty") && receiver instanceof SpecialScript && args[0].equals("magic"); } }; assertEquals(42, GroovySandbox.run(shell.parse("magic"), wl)); try { GroovySandbox.run(shell.parse("boring"), wl); } catch (MissingPropertyException x) { assertEquals("boring", x.getProperty()); } }
private Class doParseClass(GroovyCodeSource codeSource) { validate(codeSource); Class answer; // Was neither already loaded nor compiling, so compile and add to cache. CompilationUnit unit = createCompilationUnit(config, codeSource.getCodeSource()); if (recompile != null && recompile || recompile == null && config.getRecompileGroovySource()) { unit.addFirstPhaseOperation( TimestampAdder.INSTANCE, CompilePhase.CLASS_GENERATION.getPhaseNumber()); } SourceUnit su = null; File file = codeSource.getFile(); if (file != null) { su = unit.addSource(file); } else { URL url = codeSource.getURL(); if (url != null) { su = unit.addSource(url); } else { su = unit.addSource(codeSource.getName(), codeSource.getScriptText()); } } ClassCollector collector = createCollector(unit, su); unit.setClassgenCallback(collector); int goalPhase = Phases.CLASS_GENERATION; if (config != null && config.getTargetDirectory() != null) goalPhase = Phases.OUTPUT; unit.compile(goalPhase); answer = collector.generatedClass; String mainClass = su.getAST().getMainClassName(); for (Object o : collector.getLoadedClasses()) { Class clazz = (Class) o; String clazzName = clazz.getName(); definePackage(clazzName); setClassCacheEntry(clazz); if (clazzName.equals(mainClass)) answer = clazz; } return answer; }
/** @param args */ public static void main(String[] args) { log("Groovy Compiler Test"); final File[] files = FileFinder.newFileFinder("/tmp/groovy") .filterBuilder() .endsWithMatch(".groovy") .fileFinder() .find(); final HeliosURLClassLoader hcl = new HeliosURLClassLoader("groovy", URLHelper.toURL("/tmp/groovy")); try { CompilerConfiguration compilerConfig = new CompilerConfiguration(CompilerConfiguration.DEFAULT); compilerConfig.setScriptBaseClass(NashScript.class.getName()); GroovyShell groovyCompiler = new GroovyShell(compilerConfig); GroovyClassLoader groovyClassLoader = new GroovyClassLoader(hcl, compilerConfig); for (File f : files) { log("Compiling [%s]", f); Class<?> clazz = groovyClassLoader.parseClass(URLHelper.getTextFromFile(f)); log("Compiled: [%s], parent:[%s]", clazz.getName(), clazz.getSuperclass().getName()); Object o = clazz.newInstance(); for (Field field : clazz.getDeclaredFields()) { if (!field.getName().contains("$")) { field.setAccessible(true); Object fieldValue = field.get(o); log( "\tField: [%s], type:[%s], valueType: [%s]", field.getName(), field.getType().getName(), fieldValue.getClass().getName()); } } } } catch (Exception ex) { ex.printStackTrace(System.err); } }
void readConfig() { File config = new File(new File(rootdir), "imprempta.groovy"); if (config.exists()) { Binding binding = new Binding(); binding.setVariable("binder", this); binding.setVariable("ext", ext); CompilerConfiguration conf = new CompilerConfiguration(); conf.setVerbose(true); GroovyShell shell = new GroovyShell(binding, conf); try { String s = new Scanner(new FileInputStream(config)).useDelimiter("\\Z").next(); s = "import net.anzix.imprempta.api.*;\n" + "import net.anzix.imprempta.impl.*;\n" + "import static net.anzix.imprempta.api.Phase.*;\n\n" + s; shell.evaluate(s); } catch (IOException e) { throw new GeneratorException("Can't execute config file", e); } } }
/** * Decides if the given source is newer than a class. * * @param source the source we may want to compile * @param cls the former class * @return true if the source is newer, false else * @throws IOException if it is not possible to open an connection for the given source * @see #getTimeStamp(Class) */ protected boolean isSourceNewer(URL source, Class cls) throws IOException { long lastMod; // Special handling for file:// protocol, as getLastModified() often reports // incorrect results (-1) if (isFile(source)) { // Coerce the file URL to a File // See ClassNodeResolver.isSourceNewer for another method that replaces '|' with ':'. // WTF: Why is this done and where is it documented? String path = source.getPath().replace('/', File.separatorChar).replace('|', ':'); File file = new File(path); lastMod = file.lastModified(); } else { URLConnection conn = source.openConnection(); lastMod = conn.getLastModified(); conn.getInputStream().close(); } long classTime = getTimeStamp(cls); return classTime + config.getMinimumRecompilationInterval() < lastMod; }
/** * (Re)Compiles the given source. This method starts the compilation of a given source, if the * source has changed since the class was created. For this isSourceNewer is called. * * @param source the source pointer for the compilation * @param className the name of the class to be generated * @param oldClass a possible former class * @return the old class if the source wasn't new enough, the new class else * @throws CompilationFailedException if the compilation failed * @throws IOException if the source is not readable * @see #isSourceNewer(URL, Class) */ protected Class recompile(URL source, String className, Class oldClass) throws CompilationFailedException, IOException { if (source != null) { // found a source, compile it if newer if ((oldClass != null && isSourceNewer(source, oldClass)) || (oldClass == null)) { synchronized (sourceCache) { String name = source.toExternalForm(); sourceCache.remove(name); if (isFile(source)) { try { return parseClass( new GroovyCodeSource(new File(source.toURI()), config.getSourceEncoding())); } catch (URISyntaxException e) { // do nothing and fall back to the other version } } return parseClass(source.openStream(), name); } } } return oldClass; }
protected CompilationUnit makeCompileUnit() { Map<String, Object> options = configuration.getJointCompilationOptions(); if (options != null) { if (keepStubs) { options.put("keepStubs", Boolean.TRUE); } if (stubDir != null) { options.put("stubDir", stubDir); } else { try { File tempStubDir = FileSystemCompiler.createTempDir(); temporaryFiles.add(tempStubDir); options.put("stubDir", tempStubDir); } catch (IOException ioe) { throw new BuildException(ioe); } } return new JavaAwareCompilationUnit(configuration, buildClassLoaderFor()); } else { return new CompilationUnit(configuration, null, buildClassLoaderFor()); } }
public static CompilerConfiguration getCompilerConfiguration() { final CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); compilerConfiguration.setScriptBaseClass(ConsoleScript.class.getName()); return compilerConfiguration; }
private CompilerConfiguration createBaseCompilerConfiguration( Class<? extends Script> scriptBaseClass) { CompilerConfiguration configuration = new CompilerConfiguration(); configuration.setScriptBaseClass(scriptBaseClass.getName()); return configuration; }
/** * Parses the given file into a Java class capable of being run * * @param file the file name to parse * @return the main class defined in the given script */ public Class parseClass(File file) throws CompilationFailedException, IOException { return parseClass(new GroovyCodeSource(file, config.getSourceEncoding())); }