Ad hoc jar file downloads via Gradle?


Here’s a quick question: I have a set of URLs for .jar files that I want to download from MavenCentral, and I’d like to download them ad hoc to a local directory at runtime. What would be the simplest way to call the URL and download the files to a local subdirectory?

Thank you.

I’d just treat them like normal dependencies and then copy them. Something like:

configurations {

adhoc }

dependencies {

adhoc ‘group:module1:1.0’

adhoc ‘group:module2:1.0’ }

task(‘copyAdhocJars’, type: Copy) << {

from configurations.adhoc

into file(‘some/adhoc/dir’)


May not be 100% correct (off the top of my head) but you get the idea…

Thank you, Gary!

Here’s one thing I’m grappling with: out of the box, when I define dependencies, they get copied to my .gradle directory, deeply buried under a complex, unique directory path for each dependency.

For example, plexus-utils-2.0.5.jar gets burined here:

C:.gradle\caches\artifacts-8\filestore\org.codehaus.plexus\plexus-utils\2.0.5\j ar\7841ba10ea46c9611ce702c3833ff9fccc8ae6eb\plexus-utils-2.0.5.jar

But in this instance, I need to get these jars either into the directory where the build.gradle file lives, or ideally in a specified sudirectory. Is there any way I can specify this in the build file?

Thanks again!

Maybe I’m misunderstanding your question, but that’s what the copyAdhocJars example is supposed to do. By putting it in a normal dependency, you’re leveraging gradle’s dependency resolution to go out and download those jars to the local cache with very little config. It’s that copyAdhocJars task that then copies the jars from the cache to wherever you want to have them reside.

That little snippet of “from configurations.adhoc” is where the magic occurs. If you look at the GroovyDoc for Configuration you’ll see that it actually extends FileCollection, and using it in a spec for the Copy task causes the configuration to be resolved and returns all the File objects for each of the corresponding downloaded jars in the cache. Then you specify “into file(’/some/adhoc/dir’)” to specify where those jars should be copied to. If you wanted to use the main project directory, you could just use “into projectDir”.

If you want that task to be implicit with some other task, then you just set copyAdhocJars up as a dependency for whatever task you want it it as a prerequisite for (e.g. “myOthertask.dependsOn copyAdhocJars”). Then it will always get called when you invoke the myOtherTask task.

Note that the “<<” above is wrong (typo). Should be "task(‘copyAdhocJars’, type: Copy) { " as you are configuring a Copy task, not defining an action for it.