I have Spring RESTfull application and I want to generate an API for it. I use a gradle configuration from there https://github.com/Casturan/swagger-gradle-example/blob/master/build.gradle to generate code. But there is problem it uses models defined in definitions: while I want it to use my models from shared module. I found that I need to use importMapping but when I try to apply this command in my build.gradle I am getting an error:
importMappings = [
'board_container': 'board_container=com.workingbit.share.domain.impl.BoardContainer'
]
> Could not set unknown property 'importMappings' for task ':myproject:generateApi' of type org.gradle.api.DefaultTask.
So question how to use importMapping and how to connect it with my model in yaml?
I haven't tried it but looking at the code of CodegenConfigurator modifying the generateApi task like this in the build.gradle might work:
task generateApi {
inputs.file("$projectDir/$swaggerSourceFile")
outputs.dir("$projectDir/$swaggerTargetFolder")
doLast{
def config = new CodegenConfigurator()
config.setInputSpec("file:///$projectDir/$swaggerSourceFile")
config.setOutputDir("$projectDir")
config.setLang('spring')
config.setAdditionalProperties([
'interfaceOnly' : 'true',
'apiPackage' : 'com.dturan.api',
'modelPackage' : 'com.dturan.model',
'sourceFolder' : swaggerTargetFolder
])
//Add this line
config.addImportMapping("board_container", "com.workingbit.share.domain.impl.BoardContainer")
new DefaultGenerator().opts(config.toClientOptInput()).generate()
}
}
The CodegenConfigurator is being called at the second line in the build.gradle you linked to in your question and it has a few methods to configure importMappings. You can have a look here (if this doesn't work try with the setImportMappings).
Related
In a Maven project, it is easy to add extra deps and include extra source codes via defining a new Maven profile.
How to do the following things in a Gradle project.
Includes extra deps
Includes another source codes directory
And for example, use an extra property existence(eg. add to command line) to decide to activate it or not. I am not sure the best way in Gradle world.
I am not recommending your approach.
But it can be done via - project properties from gradle command line and groovy if (condition) { } for dependencies and multiple sourceset defs
on command line
gradle build -PbProfile=extra1
ext.buildFlag = 'default'
if (project.hasProperty('bProfile')) {
ext.buildFlag = property('bProfile')
}
println "running profile - ${buildFlag}"
dependencies {
//common-deps
if ("extra1".equals(buildFlag)) {
//extra deps
}
}
if ("extra1".equals(buildFlag)) {
//custom sourceset def
} // more else if needed
I use conditionally applied sub-configurations. This is done thru the apply from directive:
if (project.hasProperty('browsers')) {
ext.browsers.split(',').each {
def browser = it.trim()
if (browser) {
apply from: "${browser}Deps.gradle"
}
}
}
This block checks for specification of the browsers property (either from gradle.properties or the -P command line argument). If this property is defined, I split the property's value on commas and apply sub-configurations whose names conform to the pattern <browser>Deps.gradle.
The project in which I use this pattern is here
Suppose following configuration:
build.dependencies.gradle:
ext {
libraries = [:]
}
libraries += [
library : [group: 'com.example', name: 'library', version: '1.1.1']
]
build.gradle.kts:
apply(from = "build.dependencies.gradle")
dependencies {
implementation(libraries["library"]) // does not work
}
Is there a way to get values provided by Groovy script in build.gradle.kts?
It doesn’t work because Kotlin is statically/strongly typed language unlike Groovy. libraries is not defined on any object from Gradle’s API.
You can access it like so:
dependencies {
implementation((project.extra["libraries"] as LinkedHashMap<*, *>)["library"]!!)
}
println(project.extra["libraries"])
project.extra[“libraries”] returns an Object so we need to cast it correctly in order to get the next value. It is also marked as #Nullable so hence the !! operator.
—
A better way to manage dependency versions is to leverage Java Platform plugin.
I have multi-project Gradle build that contains also non-Java projects.
I want to declare the artifacts create by one such project in a way that I can use project/configuration dependencies to get them, e.g.
consumer:
dependencies {
myConf project(path: ':producer', configuration: 'myConf')
}
What I currently have is this:
producer:
configurations {
myConf
}
task produceFile {
//... somehow create the file...
outputs.file file('path/to/file')
}
artifacts.add('myConf', produceFile.outputs.files.singleFile, { builtBy produceFile })
Is there a better way to declare the artifact than my clumsy version?
I couldn't figure out a way to pass the task dependency from the artifact to the producing task in one go.
According to the documentation article on Legacy publishing and the javadoc on the ArtifactHandler, for your simple example it should be sufficient to just pass the task, as long as the task type extends AbstractArchiveTask (e.g. Zip or Jar):
artifacts.add('myConf', produceFile)
... or in the more Gradle-ish way:
artifacts {
myConf produceFile
}
The article mentioned above has another example, where a File is passed directly to the add method, which requires you to specify the task to build the file in the way you did in your example.
However, let me propose other ideas for syntax that may be experienced more 'lightweight':
artifacts {
myConf files(produceFile).singleFile { buildBy produceFile }
// or
myConf file: files(produceFile).singleFile, buildBy: [produceFile]
}
These two examples use the Project.files(...) method to resolve the output(s) of the task instead of accessing them manually. The second example makes use of the map syntax often provided by Gradle.
If you want to somehow standardize your way to publish your custom artifacts, I would propose to create a custom task type that offers any of the different arguments the ArtifactHandler can process as a method or property:
class MyTaskType extends DefaultTask {
// ... other stuff ... of course this should be part of a plugin
def getArtifact() {
return ... // either a (Configurable)PublishArtifact (if constructor is available) or a map representation
}
}
task produceFile(type: MyTaskType) {
// configure somehow
}
artifacts {
myConf produceFile.artifact
}
So, I am using a plugin in my gradle build (the plugin is org.flywaydb.flyway but that is not really relevant). I want to validate the caller has passed in a runtime parameter when tasks from this plugin are executing but not when other tasks are executing.
I pass options to the flyway plugin based on a supplied parameter. I want an error to be returned when a flywayTask is being executed and no parameter is supplied. When a non-flyway task is being run, I do not want to validate if the parameter is supplied.
gradle -PmyParam=myValue flywayMigration
=> should run code and there should be no error
gradle flywayMigration
=> should run code and should produce error (as no parameter supplied)
gradle jar
=> should not run code and no error should be produced
I have been reading about gradle configuration and execution which is fine but I still can't find a way to only run the code when the flyway plugin is bveing executed OR specific flyway tasks are being executed.
This is my current code:
if(gradle.taskGraph.hasTask("flywayMigrate")) {
flyway {
def dbCode, dbUser, dbPassword, dbUrl
if (!project.hasProperty("db_env")) {
throw new GradleException("Expected db_env property to be supplied for migration task. Can be passed" +
" at command line e.g. [gradle -Pdb_env=ex1 flywayMigrate]")
} else {
// do stuff
}
user = balh
password = blah
url = blah
driver = 'oracle.jdbc.OracleDriver'
cleanDisabled = true
baselineOnMigrate = true
baselineVersion = '1.0.0'
}
}
To be clear, I only want this code:
if (!project.hasProperty("db_env")
to run for flyway tasks.
The code above throws this error:
Task information is not available, as this task execution graph has not been populated.
I've tried a few things here, any advice would be appreciated.
It's not really clear to me, what exactly do you want to do in case if this property is provided, but I think, you can do it without accesing task graph, just try to use doFirst Closure of the flywayMigrate task. Just something like this:
flywayMigrate.doFirst {
if(!project.hasProperty("db_env")) {
throw ...
} else {
//Do something
}
}
And leave your plugin configuration free of any additional logic.
As for exception, have you tried to wait until graph is ready? It's usualy done as follows:
gradle.taskGraph.whenReady {taskGraph ->
if(gradle.taskGraph.hasTask("flywayMigrate")) {
...
}
}
Update: to answer the question from the comments
if I can attach doFirst to multiple tasks?
Yes, you can use somthing like:
//declare task names
def names = ["taskA", "taskB", "taskC"]
tasks.findAll {it ->
//filter tasks with names
if (it.name in names)
return it
}.each { it ->
//add some extra logic to it's doFirst closure
it.doFirst {
println 'hello'
}
}
Just check, that all the tasks are exists before this configuration.
I'm writing a custom Gradle plugin that will create a new Test task and run it. I need to set some configuration on this test task.
The plugin is written in Java and the code to execute the Test task looks like this:
private void runSmokeTests() {
Test test = new Test();
test.useTestNG(new Closure(/* What goes in here? */) {
// and here? How do I get hold of TestNGOptions?
});
test.executeTests();
}
I can't figure out how to use the Closure class from Java.
Simplest option is just to call getOptions() and cast to the appropriate type.
test.useTestNG();
TestNGOptions options = (TestNGOptions) test.getOptions();
// configure options ie...
options.setPreserveOrder(true);