Over a million developers have joined DZone.

Gradle Goodness: Create Checksums for Archives

DZone's Guide to

Gradle Goodness: Create Checksums for Archives

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

If we want to create a checksum for a file in Gradle we can use the ANT checksum task. We assign the file name to the file property of the task. Then the checksum task will generate a file with the checksum in the same directory.

Suppose we have a Java project and want to generate a checksum for the JAR file that is generated with the jar task. We can add an extra action to the jar task with the doLast() method. We pass a closure to this method and in the closure we define the action to create a checksum. The file name of the JAR file is accessible via the archivePath property:

apply plugin: 'java'

archivesBaseName = 'checksum-sample'

jar.doLast { task ->
    ant.checksum file: task.archivePath

When we invoke the jar task we get an extra file in the build/libs directory with the name checksum-sample.jar.MD5. This file contains the checksum for the file checksum-sample.jar.

We can make sure in our Gradle build file that all archive tasks (like Zip, Jar, War) generate a checksum file for the archive file of that task. In the following build file we use the withType() method in the afterEvaluate() method to add the checksum task to all tasks of type Zip. This means also task types that extend the Zip task, like Jar, War and Ear, will get the extra action. We also create extra archives in our project to show we don't have to configure them explicitly with the checksum task, but that Gradle will add the action automatically.

apply plugin: 'java'

archivesBaseName = 'checksum-sample'

task sourceJar(type: Jar) {
    from sourceSets.main.allSource
    classifier = 'sources'

task javadocJar(type: Jar, dependsOn: 'javadoc') {
    from javadoc.destinationDir
    classifier = 'javadoc'

artifacts {
    archives sourceJar, javadocJar

tasks.withType(Zip) { task ->
    task.doLast {
        ant.checksum file: it.archivePath

When we invoke the assemble task and look at the file that are generated we get the following command-line output:

$ gradle assemble
:processResources UP-TO-DATE
Total time: 4.161 secs
$ ls -1 build/libs




Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}