Search code examples
gradleartifactory

How to download a jar from artifactory with gradle to project directory?


What is the correct way to write a gradle task which downloads a .jar(or any other) file from artifactory to project directory(if file does not already exists)?

For example, I have a project with path /root/project with file /root/project/build.gradle inside. I want to download generator.jar from artifactory (com/company/project/generator/1.0) to /root/project directory if /root/project/generator.jar is not present.


Solution

  • tasks.register("downloadGeneratorJar") {
        group = 'Download'
        description = 'Downloads generator.jar'
    
    doLast {
        def f = new File('generator.jar')
        if (!f.exists()) {
            URL artifactoryUrl = new URL('myurl')
            HttpURLConnection myURLConnection = (HttpURLConnection)artifactoryUrl.openConnection()
    
            String userCredentials = gradle.ext.developerUser + ":" + gradle.ext.developerPassword
            String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()))
    
            myURLConnection.setRequestProperty ("Authorization", basicAuth)
            InputStream is = myURLConnection.getInputStream()
    
            new FileOutputStream(f).withCloseable { outputStream ->
                int read
                byte[] bytes = new byte[1024]
    
                while ((read = is.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read)
                }
            }
        }
    }
    }