Adding jcenter() in rootlevel repositories breaks my build - docker

I have a project with a Gradle buildscript and I added the bmuschko/gradle-docker-plugin to create and push image on new builds.
However I cant use the plugin if I don't specify jcenter() in root level repositories, but that breaks my build, so im kinda lost.
If I add the root level jcenter() it fails the build with:
Could not resolve all dependencies for configuration ':compileClasspath'.
Could not find com.sleepycat:je:7.0.6. Searched in the following locations:
https://jcenter.bintray.com/com/sleepycat/je/7.0.6/je-7.0.6.pom
https://jcenter.bintray.com/com/sleepycat/je/7.0.6/je-7.0.6.jar
https://repo1.maven.org/maven2/com/sleepycat/je/7.0.6/je-7.0.6.pom
https://repo1.maven.org/maven2/com/sleepycat/je/7.0.6/je-7.0.6.jar
https://nexus.company.com/content/groups/public/com/sleepycat/je/7.0.6/je-7.0.6.pom
https://nexus.company.com/content/groups/public/com/sleepycat/je/7.0.6/je-7.0.6.jar
Required by: project : > org.jpos:jpos:2.1.1
However if I don't add it i get this:
Could not resolve all dependencies for configuration ':dockerJava'.
Could not find com.aries:docker-java-shaded:3.1.0-rc-3. Searched in the following locations:
https://nexus.company.com/content/groups/public/com/aries/docker-java-shaded/3.1.0-rc-3/docker-java-shaded-3.1.0-rc-3.pom
https://nexus.company.com/content/groups/public/com/aries/docker-java-shaded/3.1.0-rc-3/docker-java-shaded-3.1.0-rc-3-cglib.jar
Required by: project :
Should I perhaps build Java shaded and include in our local Maven repo?
Here is the script:
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url = 'https://nexus.company.com/content/repositories/snapshots/'
credentials {
username 'na'
password 'na'
}
}
}
dependencies {
classpath group: 'com.company.gradle', name: 'cpmgradle', version: '0.1-SNAPSHOT'
classpath 'com.bmuschko:gradle-docker-plugin:3.4.4'
}
}
// ADDING THIS BREAKS MY BUILD BUT IS NECESSARY FOR DOCKER PLUGIN TO WORK
repositories {
jcenter()
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'com.company.gradle.java'
apply plugin: 'com.bmuschko.docker-remote-api'
projectinfo {
group = 'com.company.mesb'
artifact = 'MESB'
version = '1.29.DEV-SNAPSHOT'
description = 'MESB'
packaging = 'jar'
}
dependencies {
compile 'org.jpos:jpos:2.1.1'
compile 'org.jdom:jdom2:2.0.6'
compile 'org.json:json:20140107'
compile 'com.company.javasdk:JavaSDK:1.1.JDOM2-SNAPSHOT'
compile 'com.company.javasdk:Base64:1.0'
compile 'org.apache.wss4j:wss4j-ws-security-dom:2.0.3'
compile 'org.apache.santuario:xmlsec:2.0.3'
compile 'org.slf4j:slf4j-log4j12:1.7.10'
compile 'com.google.code.gson:gson:2.3.1'
compile 'org.bouncycastle:bcprov-jdk15on:1.54'
compile 'org.bouncycastle:bcpkix-jdk15on:1.54'
compile 'junit:junit:4.12'
compile 'org.jsoup:jsoup:1.9.2'
compile 'org.apache.commons:commons-lang3:3.4'
compile 'com.ibm:mq:5.3.07'
compile 'com.ibm:mq.pcf:5.3.07'
compile 'com.ibm:mq.jmqi:5.3.07'
compile 'com.ibm:mq.headers:5.3.07'
compile 'com.ibm:mq.commonservices:5.3.07'
compile 'com.ibm:connector:1.0.0'
runtime 'jaxen:jaxen:1.1.6'
runtime 'xalan:xalan:2.7.2'
runtime 'org.postgresql:postgresql:8.0-311.jdbc3'
runtime 'commons-logging:commons-logging:1.2'
}
compileJava {
sourceCompatibility = 1.6
targetCompatibility = 1.6
options.fork = true
options.compilerArgs << '-XDignore.symbol.file'
options.forkOptions.executable = 'javac'
}
task libs(type: Copy) {
description = "Copies dependencies to the 'lib' directory of the deployment."
def libsDir = new File("$buildDir", 'libs')
libsDir.mkdirs()
def dockerDir = new File("$buildDir", 'docker')
dockerDir.mkdirs()
from project.configurations.runtime
into libsDir
}
task bundleZip(type: Zip) {
from projectDir
include 'xsl/**'
include 'conf/**'
include 'js/**'
include 'test/**'
include 'mesb.sh'
from(tasks.libs.outputs) {
include 'MESB*'
}
into project.projectinfo.version
}
tasks.bundleZip.dependsOn jar
tasks.bundleZip.dependsOn libs
def dockerUsername = project.properties['dockerUsername'] ?: ""
def dockerPassword = project.properties['dockerPassword'] ?: ""
docker {
registryCredentials {
username = dockerUsername
password = dockerPassword
}
}
task buildImage(type: com.bmuschko.gradle.docker.tasks.image.DockerBuildImage) {
doFirst {
copy {
from "${buildDir}/libs/MESB-${projectinfo.version}.jar"
into "${buildDir}/docker"
rename { String fileName ->
fileName.replace("-${projectinfo.version}", "")
}
}
copy {
from "docker/jdk/Dockerfile"
into "${buildDir}/docker"
}
copy {
from "xsl"
into "${buildDir}/docker/xsl"
}
copy {
from "conf"
into "${buildDir}/docker/conf"
}
copy {
from "test"
into "${buildDir}/docker/test"
}
copy {
from "${buildDir}/libs"
into "${buildDir}/docker/libs"
}
}
inputDir = project.file("${buildDir}/docker")
tag = "company/mesb:${projectinfo.version}"
}
tasks.buildImage.dependsOn build
task pushImage(type: com.bmuschko.gradle.docker.tasks.image.DockerPushImage) {
imageName = "company/mesb"
tag = "${projectinfo.version}"
}
tasks.pushImage.dependsOn buildImage
artifacts {
archives bundleZip
}
/* Remove the default JAR file from the uploaded artifacts */
configurations.archives.artifacts.with { archives ->
def jarArtifact
archives.each {
if (it.file =~ 'jar') {
jarArtifact = it
}
}
remove(jarArtifact)
}
jar {
dependsOn configurations.runtime
manifest {
attributes 'Main-Class': 'main.MESB'
}
}
tasks.build.dependsOn libs
sourceSets {
main {
java {
srcDir 'src'
}
}
}

Apparently moving root repository definitions benieth the apply plugins section solved this.
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'com.company.gradle.java'
apply plugin: 'com.bmuschko.docker-remote-api'
repositories {
jcenter()
mavenCentral()
}

Don't know whether you have solved your issue but either way...
I encountered a similar issue regarding:
Could not resolve all dependencies for configuration ':dockerJava'.
Could not find com.aries:docker-java-shaded:3.1.0-rc-3.
We solved it by adding the following
repositories {
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}

Related

How to install the snapshot jar by Gradle?

For this project, I want to install the jar files into my local repository. So far, I modified the build.gradle to this:
buildscript {
dependencies {
classpath 'io.spring.gradle:spring-build-conventions:0.0.33.RELEASE'
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
classpath 'io.spring.nohttp:nohttp-gradle:0.0.5.RELEASE'
}
repositories {
mavenLocal() // 使用本地仓库
maven { url 'https://repo.spring.io/plugins-snapshot' }
maven { url 'https://plugins.gradle.org/m2/' }
}
}
plugins{
id 'maven-publish'
}
apply plugin: 'io.spring.nohttp'
apply plugin: 'locks'
apply plugin: 'io.spring.convention.root'
apply plugin: 'maven'
group = 'org.springframework.security.experimental'
description = 'Spring Authorization Server'
ext.snapshotBuild = version.contains("SNAPSHOT")
repositories {
mavenLocal() // 使用本地仓库
mavenCentral()
}
// 指定上传的路径
def localMavenRepo = 'file://' + new File(System.getProperty('user.home'), '.m2/repository').absolutePath
// 上传Task,Gradle会生成并上传pom.xml文件。
uploadArchives {
repositories {
mavenDeployer {
repository(url: localMavenRepo)
//构造项目的Pom文件
pom.project {
name = project.name
packaging = 'jar'
description = 'description'
}
}
}
}
publishing {
// 配置发布的地址
repositories{
// 一. 这种方式是最简便的方式
mavenLocal()
}
}
dependencyManagementExport.projects = subprojects.findAll { !it.name.contains('-boot') }
subprojects {
plugins.withType(JavaPlugin) {
project.sourceCompatibility = "1.8"
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
}
nohttp {
allowlistFile = project.file("etc/nohttp/allowlist.lines")
}
When running gradle uploadArchives, this is the error I received:
Execution failed for task ':spring-security-oauth2-authorization-server:uploadArchives'.
Could not publish configuration 'archives'
Must specify a repository for deployment
Also, when running artifactory publishing, this is the error I received:
Execution failed for task ':artifactoryDeploy'.
java.io.IOException: Failed to deploy file. Status code: 401 Response message: Artifactory returned the following errors:
Artifactory configured to accept only encrypted passwords but received a clear text password, getting the encrypted password can be done via the WebUI. Status code: 401
Any idea?
The install task will deploy artifacts to Maven repositories, including local. See the Maven Plugin for details.
If you want to reference the snapshot jar for Spring Authorization Server then ensure you have the following in your gradle build file:
dependencies {
compile 'org.springframework.security.experimental:spring-security-oauth2-authorization-server:0.1.0-SNAPSHOT'
}
repositories {
maven { url 'https://repo.spring.io/snapshot' }
}
For additional details, see the Spring Security reference for Gradle setup.

gradle docker plugin bmuschko Splitting a build.gradle into two files gives error

I am new to using gradle scripts. I have a build.gradle file that I want to split into two files. I get the following two files once I split the larger build.gradle file.
build.gradle
buildscript {
ext {
springBootVersion = '1.5.12.RELEASE'
gradleDockerVersion = '3.2.7'
}
repositories {
jcenter()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("com.bmuschko:gradle-docker-plugin:${gradleDockerVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
jar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
compileJava.options.encoding = 'UTF-8'
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
project.ext.imageName = 'myImage'
project.ext.tagName ='myTag'
project.ext.jarName = (jar.baseName + '-' + jar.version).toLowerCase()
apply from: 'dockerapp.gradle'
dockerapp.gradle
def gradleDockerVersion = '3.7.2'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath("com.bmuschko:gradle-docker-plugin:${gradleDockerVersion}")
}
}
apply plugin: 'com.bmuschko.docker-remote-api'
import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage
import com.bmuschko.gradle.docker.tasks.image.DockerRemoveImage
import com.bmuschko.gradle.docker.tasks.image.Dockerfile
def imageName = project.ext.imageName
def tagName = project.ext.tagName
def jarName = project.ext.jarName
task createAppDockerfile(type: Dockerfile) {
// Don't create dockerfile if file already exists
onlyIf { !project.file('Dockerfile').exists() }
group 'Docker'
description 'Generate docker file for the application'
dependsOn bootRepackage
destFile = project.file('Dockerfile')
String dockerProjFolder = project.projectDir.name
from 'openjdk:8-jre-slim'
runCommand("mkdir -p /app/springboot/${dockerProjFolder} && mkdir -p /app/springboot/${dockerProjFolder}/conf")
addFile("./build/libs/${jarName}.jar", "/app/springboot/${dockerProjFolder}/")
environmentVariable('CATALINA_BASE', "/app/springboot/${dockerProjFolder}")
environmentVariable('CATALINA_HOME', "/app/springboot/${dockerProjFolder}")
workingDir("/app/springboot/${dockerProjFolder}")
if (System.properties.containsKey('debug')) {
entryPoint('java', '-Xdebug', '-Xrunjdwp:server=y,transport=dt_socket,address=5005,suspend=n', '-jar', "/app/springboot/${dockerProjFolder}/${jarName}.jar")
} else {
entryPoint('java', '-jar', "/app/springboot/${dockerProjFolder}/${jarName}.jar")
}
}
task removeAppImage(type: DockerRemoveImage) {
group 'Docker'
description 'Remove the docker image using force'
force = true
targetImageId { imageName }
onError { exception ->
if (exception.message.contains('No such image')) {
println 'Docker image not found for the current project.'
}
}
}
task createAppImage(type: DockerBuildImage) {
group 'Docker'
description 'Executes bootRepackage, generates a docker file and builds image from it'
dependsOn(createAppDockerfile, removeAppImage)
dockerFile = createAppDockerfile.destFile
inputDir = dockerFile.parentFile
if (tagName)
tag = "${tagName}"
else if (imageName)
tag = "${imageName}"
else
tag = "${jarName}"
}
If I try to run the command ./gradlew createAppImage I get an error as follows:
The other two tasks within dockerapp.gradle file seem to work without issues. If I place all my code within the build.gradle file, it works properly without giving any errors. What is the best way to split the files and execute createAppImage without running into errors?
I was able to resolve this with help from CDancy (maintainer of the plugin) as follows:
build.gradle
buildscript {
ext {
springBootVersion = '1.5.12.RELEASE'
gradleDockerVersion = '3.2.7'
}
repositories {
jcenter()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("com.bmuschko:gradle-docker-plugin:${gradleDockerVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
jar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
compileJava.options.encoding = 'UTF-8'
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
project.ext.imageName = 'myimage'
project.ext.tagName ='mytag'
project.ext.jarName = (jar.baseName + '-' + jar.version).toLowerCase()
apply from: 'docker.gradle'
docker.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.bmuschko:gradle-docker-plugin:3.2.7'
}
}
repositories {
jcenter()
}
// use fully qualified class name
apply plugin: com.bmuschko.gradle.docker.DockerRemoteApiPlugin
// import task classes
import com.bmuschko.gradle.docker.tasks.image.*
def imageName = project.ext.imageName
def tagName = project.ext.tagName
def jarName = project.ext.jarName
task createAppDockerfile(type: Dockerfile) {
// Don't create dockerfile if file already exists
onlyIf { !project.file('Dockerfile').exists() }
group 'Docker'
description 'Generate docker file for the application'
dependsOn bootRepackage
destFile = project.file('Dockerfile')
String dockerProjFolder = project.projectDir.name
from 'openjdk:8-jre-slim'
runCommand("mkdir -p /app/springboot/${dockerProjFolder} && mkdir -p /app/springboot/${dockerProjFolder}/conf")
addFile("./build/libs/${jarName}.jar", "/app/springboot/${dockerProjFolder}/")
environmentVariable('CATALINA_BASE', "/app/springboot/${dockerProjFolder}")
environmentVariable('CATALINA_HOME', "/app/springboot/${dockerProjFolder}")
workingDir("/app/springboot/${dockerProjFolder}")
if (System.properties.containsKey('debug')) {
entryPoint('java', '-Xdebug', '-Xrunjdwp:server=y,transport=dt_socket,address=5005,suspend=n', '-jar', "/app/springboot/${dockerProjFolder}/${jarName}.jar")
} else {
entryPoint('java', '-jar', "/app/springboot/${dockerProjFolder}/${jarName}.jar")
}
}
task removeAppImage(type: DockerRemoveImage) {
group 'Docker'
description 'Remove the docker image using force'
force = true
targetImageId { imageName }
onError { exception ->
if (exception.message.contains('No such image')) {
println 'Docker image not found for the current project.'
} else {
print exception
}
}
}
task createAppImage(type: DockerBuildImage) {
group 'Docker'
description 'Executes bootRepackage, generates a docker file and builds image from it'
dependsOn(createAppDockerfile, removeAppImage)
dockerFile = createAppDockerfile.destFile
inputDir = dockerFile.parentFile
if (tagName)
tag = "${tagName}"
else if (imageName)
tag = "${imageName}"
else
tag = "${jarName}"
}
The change was basically in my docker.gradle file , I had to add the repositories section that pointed to jcenter() and to use fully qualified plugin class name.
I wonder why would you ever want to use Docker Plugins in your Gradle? After playing some time with the most maintained Mushko's Gradle Docker Plugin I don't undersand why should one build plugin boilerplate over docker boilerplate both in varying syntax?
Containerizing in Gradle is comfortable for programmers and DevOps would say they don't work Docker like this and you should go their way if you need support. I found a solution below that is short, pure Docker-style and functionally full.
Find normal Dockerfile and docker.sh shell script in the project structure:
In your build.gradle file:
buildscript {
repositories {
gradlePluginPortal()
}
}
plugins {
id 'java'
id 'application'
}
// Entrypoint:
jar {
manifest {
attributes 'Main-Class': 'com.example.Test'
}
}
mainClassName = 'com.example.Test'
// Run in DOCKER-container:
task runInDockerContainer {
doLast {
exec {
workingDir '.' // Relative to project's root folder.
commandLine 'sh', './build/resources/main/docker.sh'
}
// exec {
// workingDir "."
// commandLine 'sh', './build/resources/main/other.sh'
// }
}
}
Do anything you want in a clean shell script following normal Docker docs:
# Everything is run relative to project's root folder:
# Put everything together into build/docker folder for DOCKER-build:
if [ -d "build/docker" ]; then rm -rf build/docker; fi;
mkdir build/docker;
cp build/libs/test.jar build/docker/test.jar;
cp build/resources/main/Dockerfile build/docker/Dockerfile;
# Build image from files in build/docker:
cd build/docker || exit;
docker build . -t test;
# Run container based on image:
echo $PWD
docker run test;

Building uberjar with gradle fails in jenkins

Hi I'm using gradle to create a fat jar.
It works properly on my local machine but fails when running from Jenkins.
My local gradle version is: GradleVersion.current().getVersion()=2.2.1
The one in Jenkins: GradleVersion.current().getVersion()=2.4
build.gradle looks like
Is there anything about gradle version?
I just run tasks: clean uberjar
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'maven'
sourceCompatibility = 1.5
version = '1.0'
repositories {
mavenLocal()
mavenCentral()
}
def classifier = 'producao'
println "GradleVersion.current().getVersion()="+ GradleVersion.current().getVersion()
println "Project env = '${project.hasProperty('env')}'"
// para passar parametros -Penv=homologacao
if (project.hasProperty('env') && project.getProperty('env') == 'homologacao') {
classifier = 'homologacao'
}
println "Classifier = ${classifier}"
println "Using 'com.mundi:OneStop:1.0:${classifier}'"
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.10'
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
compile 'net.sf.opencsv:opencsv:2.3'
compile "com.mundi:OneStop:1.0:${classifier}"
compile 'org.apache.commons:commons-lang3:3.4'
testCompile group: 'junit', name: 'junit', version: '4.+'
testCompile "org.spockframework:spock-core:1.0-groovy-2.3"
}
task listJars << {
configurations.compile.each { File file -> println file.name }
}
test { systemProperties 'property': 'value' }
uploadArchives {
repositories { flatDir { dirs 'repos'
} }
}
task copyToLib(type: Copy) {
into "build/classes/main"
sourceSets {
main { resources { srcDir 'src/main/resources' } }
}
from sourceSets.main.resources
}
task uberjar(type: Jar, group:'Extra Jars', description: 'Assembles a single uber jar archive containing the main classes along with all its dependencies.',
dependsOn:[':copyToLib',
':compileJava',
':compileGroovy',
':processResources'
]) {
classifier = 'uber'
destinationDir new File("$buildDir")
from files(sourceSets.main.output.classesDir)
from(configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) }) {
//exclude all META-INF that may appear in any dependant jar
exclude "META-INF/**"
}
version = '1.0'
baseName = "OneStopMonitor"
manifest {
attributes 'Main-Class': "com.onestop.monitor.AirMonitor",
'Implementation-Title': 'OneStop Monitor',
'Implementation-Version': version
}
}
group = 'com.onestop'
uploadArchives {
repositories {
mavenDeployer {
repository(url: "file:///Users/eduardorodrigues/.m2/repository")
}
}
}

How to compile multiple xsd files in Gradle JAXB/XJC?

I'm fairly new to Gradle and I am facing some issues trying to compile multiple schema files using Gradle Ant XJC.
Using the below code, I'm able to compile 1 schema successfully. However, I'm not sure how to do the same for multiple schema files.
Any advice please?
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task : XJC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final def packageName = "org.test.webservice.domain"
final def schemaFile = "misc/resources/schemas/employee-v3/wadl/employee.xsd"
configurations { provided }
project.ext.generatedSrcDir = file("$buildDir/generated-src")
dependencies {
provided 'com.sun.xml.bind:jaxb-impl:2.2.6'
provided 'com.sun.xml.bind:jaxb-xjc:2.2.6'
}
task jaxb {
println 'Starting JAXB XJC...'
ext {
packagePath = packageName.replaceAll("\\.", "/")
srcFile = file(schemaFile)
destDir = new File(project.ext.generatedSrcDir, packagePath)
}
inputs.file srcFile
outputs.dir destDir
project.ext.generatedSrcDir.mkdirs()
ant.taskdef(name: 'xjc',
classname: 'com.sun.tools.xjc.XJCTask',
classpath: configurations.provided.asPath)
doLast {
project.ext.generatedSrcDir.mkdirs()
ant.xjc(schema: srcFile, package: packageName,
destdir: project.ext.generatedSrcDir)
}
task generateSources() {}
sourceSets.main.java.srcDirs += project.ext.generatedSrcDir
generateSources.dependsOn jaxb
compileJava.dependsOn generateSources
eclipseClasspath.dependsOn generateSources
// ideaClasspath.dependsOn generateSources
}
I solved it myself. Here is the working solution.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task : XJC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final def packageName = "org.test.webservice.domain"
final def schemaDir = "misc/resources/schemas/employee-sda-v3/wadl"
configurations { provided }
project.ext.generatedSrcDir = file("$buildDir/generated-src")
dependencies {
provided 'com.sun.xml.bind:jaxb-impl:2.2.6'
provided 'com.sun.xml.bind:jaxb-xjc:2.2.6'
}
task jaxb {
println 'Starting JAXB XJC...'
ext {
packagePath = packageName.replaceAll("\\.", "/")
destDir = new File(project.ext.generatedSrcDir, packagePath)
}
outputs.dir destDir
project.ext.generatedSrcDir.mkdirs()
ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.provided.asPath)
doLast {
project.ext.generatedSrcDir.mkdirs()
ant.xjc(package: packageName, destdir: project.ext.generatedSrcDir){
schema(dir: ${schemaDir}, includes: "**/*.xsd")
}
}
task generateSources() {}
sourceSets.main.java.srcDirs += project.ext.generatedSrcDir
generateSources.dependsOn jaxb
compileJava.dependsOn generateSources
eclipseClasspath.dependsOn generateSources
// ideaClasspath.dependsOn generateSources
}
jacobono's gradle-jaxb-plugin compiles all schemas in the input directory.
I find this plugin more stable than Ant XJC. In my project, on some machines Ant XJC does not generate classes for no reason, although the results is successful. Maybe this is matter of configuration but IMHO even setup is easier with the plugin.
Here is one more working example. I put complete version of my build.gradle file.
You can setup directory and include filter on schema inside of xjc.
if you have 'nested "$" element is not supported' error like above, then below my example will help
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
sourceCompatibility = 1.8
targetCompatibility = 1.8
task genJaxb {
ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
ext.classesDir = "${buildDir}/classes/jaxb"
ext.schemaDir = "${projectDir}/src/main/resources"
outputs.dir classesDir
doLast() {
project.ant {
taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask",
classpath: configurations.jaxb.asPath
mkdir(dir: sourcesDir)
mkdir(dir: classesDir)
xjc(destdir: sourcesDir) {
schema(dir: schemaDir, includes: "**/*.xsd")
arg(value: "-wsdl")
produces(dir: sourcesDir, includes: "**/*.java")
}
javac(destdir: classesDir, source: 1.8, target: 1.8, debug: true,
debugLevel: "lines,vars,source",
classpath: configurations.jaxb.asPath,
includeantruntime: "false") {
src(path: sourcesDir)
include(name: "**/*.java")
include(name: "*.java")
}
copy(todir: classesDir) {
fileset(dir: sourcesDir, erroronmissingdir: false) {
exclude(name: "**/*.java")
}
}
}
}
}
jar {
baseName = 'myProject'
version = '0.0.1'
from genJaxb.classesDir
}
repositories {
mavenLocal()
mavenCentral()
}
configurations {
jaxb
}
dependencies {
compile("com.google.code.gson:gson:2.3",
"commons-lang:commons-lang:2.6",
"commons-collections:commons-collections:3.2.1",
"commons-codec:commons-codec:1.10",
"commons-io:commons-io:2.4",
"org.springframework.ws:spring-ws-core:2.2.1.RELEASE"
)
compile("wsdl4j:wsdl4j:1.6.1")
jaxb("com.sun.xml.bind:jaxb-xjc:2.2.4-1")
compile(files(genJaxb.classesDir).builtBy(genJaxb))
testCompile("junit:junit",
"org.powermock:powermock-api-mockito:1.6.2",
"org.powermock:powermock-module-junit4:1.6.2",
)
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
This could be the easiest solution without any external plugin.
Does it have any other impact?
task prepareXSD2Java{
def xsdSourceDir = xsdPackageName.replace(".","/")
FileTree xsdFilesTree = fileTree(dir: "$projectResourceDir/$xsdSourceDir")
xsdFilesTree.include '*.xsd'
doLast{
xsdFilesTree.getFiles().each {
File xsdFile ->
def xsdPackageExt = xsdFile.name.replace("-","_")
xsdPackageExt = xsdPackageExt.take(xsdPackageExt.lastIndexOf("."))
String xsdFileName = xsdFile.getAbsolutePath();
exec {
executable = "xjc"
args = [ "-d", "$projectSourceDir", "-p",
"$xsdPackageName.$xsdPackageExt", "$xsdFileName" ]
}
}
}
}

Gradle Geb saucelabs plugin

I'm following the example from http://www.gebish.org/manual/0.9.2/sauce-labs.html#gradle_geb_saucelabs_plugin but am unable to get it working. My build.gradle script is as follows:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "org.grails:grails-gradle-plugin:2.0.0"
classpath 'org.gebish:geb-gradle:0.9.2'
}
}
version "0.1"
group "example"
apply plugin: "grails"
apply plugin: "geb-saucelabs"
repositories {
grails.central() //creates a maven repo for the Grails Central repository (Core libraries and plugins)
maven { url "http://repository-saucelabs.forge.cloudbees.com/release" }
}
grails {
grailsVersion = '2.3.5'
groovyVersion = '2.1.9'
springLoadedVersion '1.1.3'
}
dependencies {
bootstrap "org.grails.plugins:tomcat:7.0.50" // No container is deployed by default, so add this
compile 'org.grails.plugins:resources:1.2' // Just an example of adding a Grails plugin
sauceConnect "com.saucelabs:sauce-connect:3.0.28"
}
sauceLabs {
browsers { //5
firefox_linux_19 //Could not find property 'reporting' on root project 'gradleGrailsError'.
chrome_mac
internetExplorer_vista_9
}
task { //6
testClassesDir = test.testClassesDir
testSrcDirs = test.testSrcDirs
classpath = test.classpath
}
account { //7
username = System.getenv("SAUCE_ONDEMAND_USERNAME")
accessKey = System.getenv("SAUCE_ONDEMAND_ACCESS_KEY")
}
}
When I run $gradle test, I get the following error: Could not find property 'reporting' on root project... This error occurs on the line which specifies firefox_linux_19 as the browser. Can someone please advise how I can get the geb-saucelabs plugin working correctly? Thanks.
After a lot of trial and error, I got the following to work:
sauceLabs {
tasks.withType(Test) {
reports.junitXml.destination = reporting.file("test-results/$name")
reports.html.destination = reporting.file("test-reports/$name")
}
browsers { //5
firefox_linux_19
chrome_mac
internetExplorer_vista_9
}
account { //7
username = System.getenv("SAUCE_ONDEMAND_USERNAME")
accessKey = System.getenv("SAUCE_ONDEMAND_ACCESS_KEY")
}
}
The addition of the tasks.withType(Test) was the key, and I also removed the task closure which was listed in the sample code.

Resources