gradle wsimport - gradle

I'm running wsimport from my commandline to generate java classes from WSDL as below.
wsimport -J-Djavax.xml.accessExternalDTD=all
-J-D-Djavax.xml.accessExternalSchema=all
-b http://www.w3.org/2001/XMLSchema.xsd
-b customization.xjb
-s genSrc https://example.com/XYZ.asmx?wsdl
I want to create the equivalent gradle task.
I shouldn't be using any random custom gradle plugins due to company restrictions.
What's the best way to go about it?

As #lunicon mention, you should use an ant task, here are some improvements since gradle has change a couple of properties.
configurations {
jaxws
}
dependencies {
jaxws 'com.sun.xml.ws:jaxws-tools:2.1.4'
}
task wsimport {
ext.destDir = file("${projectDir}/src/main/generated")
doLast {
ant {
sourceSets.main.output.classesDirs.inits()
destDir.mkdirs()
taskdef(name: 'wsimport',
classname: 'com.sun.tools.ws.ant.WsImport',
classpath: configurations.jaxws.asPath
)
wsimport(keep: true,
sourcedestdir: 'src/main/java',
package: "com.example.client.api",
wsdl: 'src/main/resources/api.wsdl') {
xjcarg(value: "-XautoNameResolution")
}
}
}
}
compileJava {
dependsOn wsimport
source wsimport.destDir
}

Found on web use ant task
more detail on metro project site
configurations {
jaxws
}
dependencies {
jaxws 'com.sun.xml.ws:jaxws-tools:2.1.4'
}
task wsimport {
ext.destDir = file("${projectDir}/src/main/generated")
doLast {
ant {
sourceSets.main.output.classesDir.mkdirs()
destDir.mkdirs()
taskdef(name: 'wsimport',
classname: 'com.sun.tools.ws.ant.WsImport',
classpath: configurations.jaxws.asPath
)
wsimport(keep: true,
destdir: sourceSets.main.output.classesDir,
sourcedestdir: destDir,
extension: "true",
verbose: "false",
quiet: "false",
package: "com.example.client.api",
xnocompile: "true",
wsdl: 'src/main/resources/api.wsdl') {
xjcarg(value: "-XautoNameResolution")
}
}
}
}
compileJava {
dependsOn wsimport
source wsimport.destDir
}

configurations {
jaxws
}
dependencies {
jaxws 'com.sun.xml.ws:jaxws-tools:2.1.4'
}
task wsimport {
ext.destDir = file("${projectDir}/src/main/generated")
doLast {
ant {
destDir.mkdirs()
taskdef(name: 'wsimport',
classname: 'com.sun.tools.ws.ant.WsImport',
classpath: configurations.jaxws.asPath
)
wsimport(keep: true,
destdir: sourceSets.main.output.classesDir,
sourcedestdir: destDir,
extension: "true",
verbose: "false",
quiet: "false",
package: "com.example.client.api",
xnocompile: "true",
wsdl: 'c:/projects/gluecode/src/main/resources/api.wsdl') {
xjcarg(value: "-XautoNameResolution")
}
}
}
}
This example copied from another answer of this question but removed one line as "sourceSets.main.output.classesDir.mkdirs()" and added the absolute path of .wsdl
To run the task form gradle follow the below process.
Goto run configuration and create new configuration.
From the configuration select either Gradle Project or Gradle Task from the list side
task name should same as task <<Task_Name>> {} provided in the .gradle file.
From the run configuration run the task then check the console log. In the console log some of the dependencies downloaded from the gradle repository.

This is the equivalent in Kotlin DSL
dependencies {
jaxws("com.sun.xml.ws:jaxws-tools:2.3.5")
jaxws("jakarta.xml.ws:jakarta.xml.ws-api:2.3.3")
jaxws("jakarta.activation:jakarta.activation-api:2.1.0")
jaxws("jakarta.xml.bind:jakarta.xml.bind-api:2.3.3")
}
tasks.register("wsimport") {
val destDir by extra("${buildDir}/generated/main/java")
doLast {
ant.withGroovyBuilder {
mkdir(destDir)
"taskdef"(
"name" to "wsimport",
"classname" to "com.sun.tools.ws.ant.WsImport",
"classpath" to configurations["jaxws"].asPath
)
"wsimport"(
"keep" to true,
"sourcedestdir" to destDir,
"wsdl" to "${projectDir}/some-api.wsdl",
"verbose" to true
) {
"xjcarg"("value" to "-XautoNameResolution")
}
}
}
}
tasks.compileJava {
dependsOn(tasks["wsimport"])
val destDir: String by tasks["wsimport"].extra
source(destDir)
}

Related

Running specific tests using gradle over multiple browsers

I'm using Geb/Spock for automated testing. I'm using Gradle as my build tool.
I'd like to call different gradle tasks to build and run a specific spec(test) or a suite of specs.
I dont know enough about the gradle build lifecycle to completely understand what is going on here: https://github.com/geb/geb-example-gradle/blob/master/build.gradle
plugins {
id "idea"
id "groovy"
id "com.energizedwork.webdriver-binaries" version "1.4"
id "com.energizedwork.idea-base" version "1.4"
}
ext {
// The drivers we want to use
drivers = ["firefox", "chrome", "chromeHeadless"]
ext {
groovyVersion = '2.4.12'
gebVersion = '2.2'
seleniumVersion = '3.6.0'
chromeDriverVersion = '2.32'
geckoDriverVersion = '0.18.0'
}
}
repositories {
mavenCentral()
}
dependencies {
// If using Spock, need to depend on geb-spock
testCompile "org.gebish:geb-spock:$gebVersion"
testCompile("org.spockframework:spock-core:1.1-groovy-2.4") {
exclude group: "org.codehaus.groovy"
}
testCompile "org.codehaus.groovy:groovy-all:$groovyVersion"
// If using JUnit, need to depend on geb-junit (3 or 4)
testCompile "org.gebish:geb-junit4:$gebVersion"
// Drivers
testCompile "org.seleniumhq.selenium:selenium-chrome-driver:$seleniumVersion"
testCompile "org.seleniumhq.selenium:selenium-firefox-driver:$seleniumVersion"
}
webdriverBinaries {
chromedriver chromeDriverVersion
geckodriver geckoDriverVersion
}
drivers.each { driver ->
task "${driver}Test"(type: Test) {
group JavaBasePlugin.VERIFICATION_GROUP
outputs.upToDateWhen { false } // Always run tests
systemProperty "geb.build.reportsDir", reporting.file("geb/$name")
systemProperty "geb.env", driver
}
}
test {
dependsOn drivers.collect { tasks["${it}Test"] }
enabled = false
}
tasks.withType(Test) {
maxHeapSize = "1g"
jvmArgs '-XX:MaxMetaspaceSize=128m'
testLogging {
exceptionFormat = 'full'
}
}
tasks.withType(GroovyCompile) {
groovyOptions.forkOptions.memoryMaximumSize = '256m'
}
I've tried inserting the following into build.gradle:
task dataGen {
include '**com.company.project.spec.util/DataGenerationUtilSpec.groovy'
}
task sanity {
include '**com.company.project.spec.sanity.*'
}
But calling these tasks (gradle sanity) results in a build failure:
Could not find method include() for arguments [**com.company.project.spec.util/DataGenerationUtilSpec.groovy] on task ':dataGen' of type org.gradle.api.DefaultTask
Obviously there's existing build instructions since I can call gradle build and all the specs run on Chrome, I'm just not sure how to add more tasks
I think these 2 tasks are test tasks so it should look like that :
task dataGen (type: Test) {
include '**com.company.project.spec.util/DataGenerationUtilSpec.groovy'
}
task sanity (type: Test) {
include '**com.company.project.spec.sanity.*'
}
You can use Spock annotation to control the test or the Spec, see example here.
You will have to define annotation classes and define the Spock config file to use that annotation. You then annotate the specific Specification (or test).
Now you will have to define the Spock config file in the task or from a parameter.

Using Gradle to build a jar with dependencies with Kotlin-DSL

There is already an answer to the question: how to include all the dependencies in a jar file though it's for Groovy
I'm using gradle with kotlin-dsl and the code is not compatible. I tried to make it work using a few ways including:
tasks.withType<Jar> {
configurations["compileClasspath"].forEach { file: File ->
copy {
from(zipTree(file.absoluteFile))
}
}
}
Though this doesn't work. So how to include the dependencies using kotlin-dsl in gradle?
This will work:
tasks.withType<Jar>() {
configurations["compileClasspath"].forEach { file: File ->
from(zipTree(file.absoluteFile))
}
}
There's no need in copy { ... }, you should call from on the JAR task itself.
Note: Gradle does not allow changing the dependencies after they have been resolved. It means that the block above should be executed only after the dependencies { ... } are configured.
my case
withType<Jar> {
enabled = true
isZip64 = true
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
archiveFileName.set("$project.jar")
from(sourceSets.main.get().output)
dependsOn(configurations.compileClasspath)
from({
configurations.compileClasspath.get().filter {
it.name.endsWith("jar")
}.map { zipTree(it) }
}) {
exclude("META-INF/*.RSA", "META-INF/*.SF", "META-INF/*.DSA")
}
}

classes not visible to gradle task swagger when using kongchen swagger-maven-plugin

When performing gradle clean and then gradle swagger a ClassNotFoundException is thrown. If gradle swagger is then run again (basically after the api build is done in previous run), it works fine.
build.gradle looks as below:
buildscript {
repositories {
maven { url hydraMavenRepo }
maven { url hydraPluginsRepo }
}
dependencies {
classpath "com.github.kongchen:swagger-maven-plugin:3.1.4"
}
}
apply plugin: 'java'
configurations {
addclasspath
}
dependencies {
addclasspath files(project(':api:desktop-api').configurations['runtime'].files)
addclasspath files(project(':api:desktop-api').sourceSets['main'].output)
addclasspath files(project(':api:desktop-api').sourceSets.main.output.classesDir)
runtime project(':api:desktop-api')
}
sourceSets {
main {
runtimeClasspath += files(project(':api:desktop-api').sourceSets['main'].output)
runtimeClasspath += files(project(':api:desktop-api').sourceSets['main'].output.classesDir)
runtimeClasspath += files(project(':api:desktop-api').configurations['runtime'].files)
}
}
import com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo
import com.github.kongchen.swagger.docgen.mavenplugin.ApiSource
import io.swagger.models.Info
task swagger(dependsOn: [':api:desktop-api:build']) {
doLast {
logger.info 'Swagger GenDoc...'
project.file(reportsDir).mkdirs()
// a trick to have all needed classes in the classpath
def customClassLoader = new GroovyClassLoader()
buildscript.configurations.classpath.each {
//println it.toURI().toURL()
customClassLoader.addURL(it.toURI().toURL())
}
configurations.addclasspath.each {
customClassLoader.addURL(it.toURI().toURL())
}
// the same settings as in the swagger-maven-example/pom.xml
final ApiDocumentMojo mavenTask = Class.forName('com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo', true, customClassLoader).newInstance(
apiSources: [
new ApiSource(
springmvc: false,
locations: ['com/vmware/vdi/hydra'],
schemes: ['http', 'https'],
host: 'vmware.com',
basePath: '/api',
info: new Info(
title: "Hydra DS-REST API's",
version: 'v100',
description: "Hydra DS-REST API's",
),
swaggerDirectory: reportsDir
)
]
)
mavenTask.execute()
logger.info 'Swagger GenDoc task is completed'
}
}
You have several flaws in your build script.
You should not depend on built things in build script dependencies. This is a hen and egg problem. You need to execute the build to get the classes that are necessary to execute the build. This cannot work reliably, if at all.
Instead you should declare them as dependencies outside the buildscript block. The buildscript block is only for dependencies that are needed by your build script to run itself, like Gradle Tasks and Gradle Plugins or classes you use during the build, like the swagger-maven-plugin stuff which is correct in the buildscript block.
Besides that, you execute part of your swagger stuff (the instanciation, execution and printing) during the configuration phase instead of during the execution phase. Everything you do in a task closure, but outside any doFirst or doLast blocks is run during the configuration phase, when the build is configured and thus always, no matter what tasks you actually want to execute and no matter whether the task may already be up-to-date or not. For the up-to-date check to work and save your time you need to declare all inputs like files and properties that might change between executions and all outputs that you generate, then Gradle can do its magic to only execute the task when actually necessary.
Also you should not use println in build scripts. That is like using System.out.println in Java programs. Instead you should use the provided logging facility directly, e. g. doing logger.info 'Swagger GenDoc task is completed'.
buildscript.classloader is what I was looking for.
Below is the code that works:
buildscript {
repositories {
maven { url mavenRepo }
}
dependencies {
classpath "com.github.kongchen:swagger-maven-plugin:3.1.4"
}
}
import com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo
import com.github.kongchen.swagger.docgen.mavenplugin.ApiSource
import io.swagger.models.Info
task swagger(dependsOn: ':api:build') {
doLast {
logger.info 'Swagger GenDoc...'
project.file(<dir>).mkdirs()
FileCollection apiRuntimeFiles = files(project(':api').configurations['runtime'].files)
apiRuntimeFiles.each {
buildscript.classLoader.addURL(it.toURI().toURL())
}
FileCollection apiClassFiles =files(project(':api').sourceSets['main'].output)
apiClassFiles.each {
buildscript.classLoader.addURL(it.toURI().toURL())
}
final ApiDocumentMojo mavenTask = Class.forName('com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo', true, buildscript.classLoader).newInstance(
apiSources: [
new ApiSource(
springmvc: false,
locations: ['<loc>'],
schemes: ['http', 'https'],
host: '<host>',
basePath: '/api',
info: new Info(
title: "REST API's",
version: 'v1',
description: "REST API's",
),
swaggerDirectory: <dir>
)
]
)
mavenTask.execute()
logger.info 'Swagger GenDoc task is completed'
}
}

Creating a maven wrapper pom.xml from gradle: can't create the <build> element

How do I set the sourceDirectory, testSourceDirectory and build plugins in a pom.xml that I'm creating using the gradle maven-plugin's pom DSL?
When I add build without a Closure to my DSL section, it's ok.. but when I add build { /* anything else, like actual compile plugins */} it gives me this error:
Execution failed for task ':mavenWrapper'.
> No such property: _SCRIPT_CLASS_NAME_ for class: org.apache.maven.model.Model
I'm guessing that gradle is treating build as the task rather than the DSL verb generated by org.sonatype.maven.polyglot.groovy.builder.ModelBuilder.
Is there a way to force build to be treated as part of the DSL? Can it be cast or something?
Right now I'm working around this by using .withXml but it's massively verbose and much less maintainable.
Here's an abbreviated version of what I've got working:
task mavenWrapper {
doLast {
delete 'pom.xml', 'mvnw', 'mvnw.cmd'
pom {
project {
packaging 'pom'
repositories {
repository {
id 'spring-milestones'
name 'Spring Milestones'
url 'https://repo.spring.io/libs-milestone'
snapshots {
enabled 'false'
}
}
}
properties {
'kotlin.compiler.incremental' 'true'
}
/* ******** Problem is here
build {
plugins {
plugin {
// ... etc. etc.
}
}
}
******* */
dependencyManagement {
dependencies {
dependency {
groupId 'org.jetbrains.kotlin'
artifactId 'kotlin-stdlib-jre8'
version "${kotlin_version}"
scope 'compile'
}
}
}
}
}.withXml {
// Workaround for the missing build { ... } section above.
asNode().appendNode('build').appendNode('plugins')
// etc. etc.
}.writeTo("${projectDir}/pom.xml")
exec {
commandLine 'mvn', '-N', 'io.takari:maven:wrapper', '-Dmaven=3.5.0'
}
}
}

QueryDSL for Mongo with Spring and gradle

How do I generate the predicate classes (Q* classes) with gradle? I want to use Q* classes for Mongo using Spring data. Spring documentation shows maven and ant versions but no gradle.
Is there any plugin out there that I could use?
You can use the same approach is presented here Generating JPA2 Metamodel from a Gradle build script
Just replace the Querydsl JPA APT processor with the Spring Mongodb processor.
There is an example in my project: spring-data-demo
You will need to define the relevant source to scan.
In this case it is: 'org/springframework/data/demo/data/**'
queryDslVersion is defined in gradle.properties
configurations {
queryDslTool
}
dependencies {
queryDslTool group: 'com.mysema.querydsl', name: 'querydsl-apt', version: queryDslVersion
}
task generateSources {
def queryDslDir = new File(buildDir, 'generated-sources/java')
sourceSets.main.java.srcDirs += queryDslDir
inputs.files(sourceSets.main.java.srcDirs)
outputs.dir(queryDslDir)
doLast {
if (!queryDslDir.exists()) {
queryDslDir.mkdirs()
}
def classPathStr = (configurations.queryDslTool + sourceSets.main.runtimeClasspath).asPath
ant {
javac(classpath: classPathStr, includes: 'org/springframework/data/demo/data/**', includeantruntime: false) {
sourceSets.main.java.srcDirs.each {
if (it != queryDslDir) {
src(path: it.path)
}
}
compilerarg value: '-proc:only'
compilerarg value: '-processor'
compilerarg value: 'com.mysema.query.apt.QuerydslAnnotationProcessor'
compilerarg value: '-s'
compilerarg value: queryDslDir.path
}
echo(message: 'Generated QueryDSL Helpers')
}
}
}
compileJava.dependsOn generateSources

Resources