Skip to content
Advertisement

Gradle task to obfuscate java application with Proguard

I need to obfuscate a Java application which has dependencies to many external jars. The application consist of many modules and each module contains API and implementation jars. Basically I need to create a gradle task to obfuscate all of this jars which can be used later in the build process with Jenkins. There are many documentation on Proguard, but mostly it all covers with the Android application.

Already referred the official Proguard documentation here : Proguard Gradle Plugin

Advertisement

Answer

I could achieve this with the following gradle configurations

  • Copy all the dependent jars to a directory

    def dependsDir = "${System.getProperty('user.dir')}/dependencies/"
    task copyDepends(type: Copy) {
      from configurations.compile
      into "${dependsDir}"
    }
    
  • Create a gradle task with type proguard.gradle.ProGuardTask.The list of injars is available in a directory and iterated the name in gradle task.

    buildscript {
    repositories {
      mavenCentral()
    }
    dependencies {
      classpath 'net.sf.proguard:proguard-gradle:6.0.3'
      classpath 'net.sf.proguard:proguard-base:6.0.3'
    }
    }
     task proguard(type: proguard.gradle.ProGuardTask) {
        configuration 'proguard.conf'
        def inputDir = new File("${System.getProperty('user.dir')}/inputJars")
       def  outputDir = "${System.getProperty('user.dir')}/inputJars"
        println ("List of jars for obfuscation : ")
        inputDir.eachFileRecurse (FileType.FILES) { file ->
              println(file.getName())
              injars file
              outjars "${outputDir}/${file.getName()}"
          }
    
       libraryjars "${System.getProperty('java.home')}/lib/rt.jar"
       libraryjars "${System.getProperty('java.home')}/lib/jce.jar"
       libraryjars "${System.getProperty('user.dir')}/dependencies/"
     }
    
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement