How to configure a task to run it multiple times in gradle - gradle

I need to run jsonSchema2Pojo multiple times for different file sources and target packages. Under each folder it has more than one json files.
task 1 {
jsonSchema2Pojo {
Source = files(“src/main/resource/1”)
targetPackage = “com.Test.employee ”
---
task 2 {
jsonSchema2Pojo {
Source = files (“src/main/resource/2”)
targetPackage = “com.Test2.department”
}
}
It only generate Java class for the first task

Related

How to skip JS/CSS concatenation and minification if the source files have not changed?

I have some build tasks that concatenate Javascript and CSS files then subsequently minifies the concatenated files.
This process takes a majority of my build time.
I'd like to skip the concat + minfi tasks if the original JavaScript and CSS files have not subsequently been modified between builds.
We opted to use yuicompressor because
this is what our old Ant builds used previously
it supports JS and CSS.
we didn't find an equivalent Gradle plugin that performed minification for JS and CSS.
it has been proven in production and so better-the-devil-you-know
Is there a plugin that exists for skipping tasks if files/folders have not changed, or is there another way that we can achieve this?
I wondered whether using a Copy task to copy the source JS and CSS to a temporary folder could be leveraged, so that if the source files haven't changed the copy is not performed, then chain off the copy task only if it was performed?
I include a copy of the relevant sections of our build. We're using the war plugin and hook into the build process by triggering the minify tasks, i.e.
war.dependsOn(minifyCss)
war.dependsOn(minifyJs)
Where those tasks are in our minify.gradle file
def minJsFile = new File("${rootDir}/../ExampleProject/web/assets/js/all-min.js")
def allJsFile = new File("${rootDir}/../ExampleProject/web/assets/js/all.js")
def jsSrcFilePaths = [
"${rootDir}/../ExampleProject/web/assets/js/jquery-ui-1.12-2.1/external/jquery/jquery.js",
..
"${rootDir}/../ExampleProject/web/assets/js/plugins/jquery.magnific-popup/jquery.magnific-popup.js"]
def minCssFile = new File("${rootDir}/../ExampleProject/web/assets/css/all-min.css")
def allCssFile = new File("${rootDir}/../ExampleProject/web/assets/css/all.css")
def cssSrcFilePaths = [
"${rootDir}/../ExampleProject/web/assets/css/bootstrap/bootstrap.min.css",
..
"${rootDir}/../ExampleProject/web/assets/css/plugins/magnific-popup/magnific-popup.css"
]
tasks.register( "concatenateJs") {
group "vsminify"
description = "Combines js files in to all.js"
doLast{
jsSrcFilePaths.each{
logger.info(it)
allJsFile.append(new File(it).getText())
}
}
}
tasks.register( "cleanJs") {
group "vsminify"
description = "Cleans generated all.js and all-min.js"
doLast{
logger.info("delete ${minJsFile}")
minJsFile.delete()
logger.info("delete ${allJsFile}")
allJsFile.delete()
}
}
tasks.register( "concatenateCss") {
group "vsminify"
description = "Combines css files in to all.css"
doLast{
cssSrcFilePaths.each{
logger.info(it)
allCssFile.append(new File(it).getText())
}
}
}
tasks.register( "cleanCss") {
group "vsminify"
description = "Cleans generated all.css and all-min.css"
doLast{
logger.info("delete ${minCssFile}")
minCssFile.delete()
logger.info("delete ${allCssFile}")
allCssFile.delete()
}
}
tasks.register( "minifyJs", Exec) {
dependsOn 'concatenateJs'
group "vsminify"
description = "Minifies all.js to all-min.js"
commandLine "java", "-classpath", "${rootDir}/../ExampleProject/libs/yuicompressor-2.4.8.jar", "com.yahoo.platform.yui.compressor.YUICompressor", "${rootDir}/../ExampleProject/web/assets/js/all.js", "-o", "${rootDir}/../ExampleProject/web/assets/js/all-min.js", "--charset", "utf-8"
}
tasks.register( "minifyCss", Exec) {
dependsOn 'concatenateCss'
group "vsminify"
description = "Minifies all.css to all-min.css"
commandLine "java", "-classpath", "${rootDir}/../ExampleProject/libs/yuicompressor-2.4.8.jar", "com.yahoo.platform.yui.compressor.YUICompressor", "${rootDir}/../ExampleProject/web/assets/css/all.css", "-o", "${rootDir}/../ExampleProject/web/assets/css/all-min.css", "--charset", "utf-8"
}
//We don't have the clean source code so need to attach our dependecy here.
clean.dependsOn(cleanCss)
clean.dependsOn(cleanJs)
//This is run as part of the build process (we don't have the war task source so need to assign it here)
//We know war is called as part of build so it's indirectly getting called.
war.dependsOn(minifyCss)
war.dependsOn(minifyJs)

xjc, generate java classes from xsd (using URL) in gradle 7.2

I use plugin com.github.bjornvester.xjc to generate java classes from xsd:
xjc {
xjcVersion.set("2.3.3")
outputJavaDir = file("${buildDir}/generated-sources/jaxb")
ext.downloaded = file("$buildDir/xjc/downloaded/schema2.wsdl")
doFirst {
mkdir downloaded.parentFile
downloaded.text = new URL("http://www.example.com/foo.xsd").text}
groups {
register("schema1") {
xsdFiles = files(xsdDir.file("${projectDir}/src/main/resources/wsdl/schema1.wsdl"))
defaultPackage.set("pl.com.project.schema1")
}
register("schema2") {
xsdFiles = files(downloaded)
defaultPackage.set("pl.com.project.schema2")
}
}
}
And I got an error in line "xjc {" :
In my previous attempt I incorrectly assumed that xjc was a task. After looking at the github page I can see that "xjc" is an extension object, not a task
So try this:
tasks.register('downloadXsd') {
ext.xsd = file("$buildDir/downloadXsd/foo.xsd")
outputs.file xsd // important!!! configures the task outputs
doLast {
mkdir xsd.parentFile
xsd.text = new URL("http://www.example.com/foo.xsd").text
}
}
xjc {
...
groups {
register("schema1") {
// assuming the plugin is written properly, this should configure a task dependency
xsdFiles = files(tasks.named('downloadXsd'))
...
}
...
}
}
You could improve this using the download task to download the xsd which shows progress of the download and also has caching options

GZip every file with Gradle 5.x and higher

We currently have a Gradle (v4.10.3) build script that compresses every static resource during build time. Below is a snippet of the code that we have:
tasks.register("gzipJsFiles") {
doLast {
fileTree(dir: "${buildDir}/classes/main/static/js", include: "**/*.min.js", exclude: "*.gz").eachWithIndex { file, index ->
def dynamicTask = "gzipJs-$file.name"
task "${dynamicTask}" (type: GzipJsTask) {
source = file
dest = Paths.get(file.absolutePath + ".gz").toFile()
}
tasks."$dynamicTask".execute()
}
}}
Now, with the latest versions of Gradle, the Task.execute() is being deprecated.
Is there a way to achieve the GZip task, to zip every file in file tree, individually with the newer versions of Gradle (5.x or higher)?
I don't know where the GzipJsTask comes from, but if it is the one from gradle-js-plugin, you can see from the source code that it is simply a wrapper around some Ant commands. So instead of creating Gradle tasks dynamically at execution time, which is no longer possible, just run the commands directly:
doLast {
fileTree(dir: "${buildDir}/classes/main/static/js", include: "**/*.min.js", exclude: "*.gz").each { file ->
ant.gzip(src: file.absolutePath, destfile: file.absolutePath + ".gz")
}
}

gradle - create jar iteratively under a certain directory

I am trying to create multiple jars. I have a certain directory which contains multiple directory. Each directory has its own files(xml and sql). So I am trying to create a jar with a subdirectory name and all the files in it. Those jars will be used for junit test, so I want to create it during configuration phase in advance.
The target directory "../dist" exists outside this project.
ext.createTemplateJar = { sourceDirectory, jarFileName ->
jar {
archiveName = jarFileName
from sourceDirectory
includeEmptyDirs = false
manifest
{
attributes 'Implementation-Title' : VENDOR_NAME
}
}
println "creating a jar for ${jarFileName}"
}
tasks.withType(Jar) {
destinationDir = file("../dist")
}
task generateTemplates {
new File("${projectDir}/templates").eachFile() { file ->
if (file.isFile()) {
return
}
println "template dir is ${file.path}"
createTemplateJar(file.path, "${file.name}.jar")
}
}
When I execute this gradle generateTemplates, it runs fine, but I don't see any jar files created in the destination directory.
It seems something wrong, but I can't tell.
You should create multiple Jar tasks, one for each subdirectory inside ${projectDir}/templates, and have your generateTemplates task do nothing but depend on all of those tasks. For example (I renamed generateTemplates to allJars):
task allJars {
}
file("${projectDir}/templates").eachFile { f ->
def taskName = "jar${f.name.capitalize()}"
tasks.create(name: taskName, type: Jar) {
archiveName = "${f.name}.jar"
destinationDir = file('../dist')
// Configure each JAR however you want
}
allJars.dependsOn taskName
}
Example build:
$ ls templates/
bar baz foo test
$ ./gradlew clean allJars
:clean
:jarBar
:jarBaz
:jarFoo
:jarTest
:allJars
BUILD SUCCESSFUL
Total time: 0.615 secs
$ ls ../dist/
bar.jar baz.jar foo.jar test.jar

Gradle: remove some files from an existing war | for each war-file do: unpack, remove/filter, assemble war

I'm relatively new to gradle, so this might be a typical newbee-question.
In our gradle build, we have a set of war files (dependencies) that all include a file that we need to remove from those war files, before building our ear file.
How can I achieve the following:
- for all war files in a folder,
- extract war content to a location (using a Copy task & zipTree)
- re-pack to a new war applying a filter (using War & excludes)
I assume I'll create a new task and add some 'dependsOn' declarations.
task excludeUnwantedFiles(){
file(directoryWithOriginalWars).eachFile { file ->
???? unpack war, filter, assemble new war file ????
}
}
ear.dependsOn(excludeUnwantedFiles)
excludeUnwantedFiles.dependsOn(downloadAllOriginalWarsIntoDirectory)
How do I create that task, that executes for each war-file? What is the best way to do this?
Is there a way I can to this in one task? E.g. with the Copy task and using zipTree(fooBarWithFile.war) as 'from' and 'war(fooBarWithoutFile.war)' and applying a filter in between?
Or is this the way to go, just with a loop? Delete/Remove file from war with Gradle
Any help is highly appreciated!
Cheers,
d.
---------UPDATE-------------------
Thanx Lance Java for your solution.
As I mentioned in my comment, I faced the problem that the war files were downloaded/extracted during execution time and hence not accessable to define the new tasks at configuration time.
My workaround for this is to use tarTree (with a filter) to access the list of war-files that are not yet extracted. See my code example below:
def warFileSourceTarGz = '...tar.gz'
def nfsLibDir="$buildDir/dependencies/"
def nfsLibDownloadDir="$buildDir/downloadedDependencies/"
// task that downloads & extracts the tar.gz
task fetchNfsDependencies(type: Copy) {
from tarTree(warFileSourceTarGz)
into nfsLibDownloadDir
}
// loop through all war files inside the tar.gz and
// create a task to remove unwanted libraries for each war
task excludeUnwantedJarsFromWars(dependsOn: fetchNfsDependencies){
// access the "remote" tar.gz file to get the list of war-files to loop over
def warFileSource = tarTree(warFileSourceTarGz).matching{
include '*.war'
}
// for every war-file, create an exclude-path
warFileSource.visit { nextWarFile ->
if(nextWarFile.name.endsWith('.war')) {
String taskName = "excludeUnwantedJarsFrom_${nextWarFile.name.replace('.war', '')}"
String nextWarFilePath = nfsLibDownloadDir+"/"+nextWarFile.name
Zip tweakWarTask = tasks.create(name: taskName, type: Zip, dependsOn: fetchNfsDependencies) {
from zipTree(nextWarFilePath)
destinationDir = file(nfsLibDir)
archiveName = nextWarFile.name
// exclude these jars, as they cause classloading problems in our ear deployment.
exclude 'WEB-INF/lib/jcan-optrace*'
}
// hook into build-process
ear.dependsOn(tweakWarTask)
}
}
}
ear.dependsOn(excludeUnwantedJarsFromWars)
I'd create a Zip task per war file and wire all the tasks into the DAG by having assemble depend on them all
FileTree warFiles = fileTree(dir: 'path/to/wars', includes: ['**/*.war'])
warFiles.files.each { File warFile ->
String taskName = "tweakWar${warFile.name.replace('.war', '')}"
Zip tweakWarTask = tasks.create(name: taskName, type: Zip) {
from zipTree(warFile) {
exclude 'path/to/some/file.xml'
}
destinationDir = "$buildDir/tweakedWars"
archiveName = warFile.name
}
// wire the task into the dag
assemble.dependsOn tweakWarTask
}

Resources