How to avoid copy'n'paste in gradle? - spring-boot

I have a build.gradle file for my spring-boot application. I have a few environment details I wish to change for some of the gradle tasks. Specifically for the gradle tasks 'test', 'runSmokeTest' and 'bootRun'. In all the tasks I have to make the same calls, so I would prefer if I could extract a method out of that. Or a task. But whenever I do that, suddendly gradle no longer finds the functions that I require.
These are the calls I need to make:
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("TEAM_ENCRYPT_KEY"))
environment "ENCRYPT_KEY", "$TEAM_ENCRYPT_KEY"
The code works perfectly fine when included directly in the bootRun task, the test task and the runSmokeTest task via copy'n'paste. I would prefer not to duplicate the code. I tried the following approach to extract them from the bootRun task, but Gradle keeps complaining that he does not find the functions systemProperty and environment. Similarly if I use the Intellij integrated feature 'extract Method':
task specialConfiguration() {
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("TEAM_ENCRYPT_KEY"))
environment "ENCRYPT_KEY", "$TEAM_ENCRYPT_KEY"
}
bootRun {
dependsOn 'specialConfiguration'
}
How can I extract this short piece of code from the 3 tasks to avoid duplicate code?

Gradle keeps complaining that he does not find the functions systemProperty and environment
This is a prime example where the Kotlin DSL would shine. You would know exactly what methods/properties are available at any given time because it's a strongly type language unlike Groovy.
With that said, when you do the following:
task specialConfiguration() {
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("TEAM_ENCRYPT_KEY"))
environment "ENCRYPT_KEY", "$TEAM_ENCRYPT_KEY"
}
bootRun {
dependsOn 'specialConfiguration'
}
You are:
Declaring a task named specialConfiguration.
No type was specified so the type is DefaultTask.
Configure bootRun task to depend on specialConfiguration
I think you are assuming that dependsOn is like "configuring" a task when really it's just adding a dependency to the task. See Adding dependencies to a task.
I am assuming that runSmokeTest is of type Test. So tasks test, runSmokeTest, and bootRun all implement the JavaForkOptions interface which is where the systemProperties(..), systemProperty(.., ..) and environment(.., ..) methods come from.
With that said, since you know the three tasks you want to configure, and they all implement JavaForkOptions and in some fashion, you can do (Kotlin DSL):
import org.springframework.boot.gradle.tasks.run.BootRun
// Assuming this is a Test task type
tasks.register("runSmokeTest", Test::class)
// Define a new Action (configuration)
val taskConfig = Action<JavaForkOptions> {
systemProperties(System.getProperties() as Map<String, Any>)
systemProperty("spring.cloud.config.failFast", false)
if (project.hasProperty("TEAM_ENCRYPT_KEY")) {
environment("ENCRYPT_KEY", project.property("TEAM_ENCRYPT_KEY")!!)
}
}
// Configure all three tasks
tasks.named("test", Test::class, taskConfig)
tasks.named("runSmokeTest", Test::class, taskConfig)
tasks.named("bootRun", BootRun::class, taskConfig)

The Groovy version of Francisco Mateo's answer, in case anyone needs that.:
Closure<JavaForkOptions> configAction = {
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("MOBTECH_ENCRYPT_KEY"))
it.environment "ENCRYPT_KEY", "$MOBTECH_ENCRYPT_KEY"
}
# Configure the tasks with it
bootRun (configAction)

Related

Gradle: any difference between task configuration approaches

Is there any difference between two following pieces of code?
May be there is some difference about eager initialization of a task?
tasks.bootJar {
archiveFileName = "some-name"
}
and
bootJar {
archiveFileName = "some-code"
}
They are the effectively the same just different syntax. Both cause the task to be realized or eager initialized. You can confirm this by simply running with debug output: ./gradlew -d
You will see the following line logged:
[DEBUG] [org.gradle.internal.operations.DefaultBuildOperationRunner] Build operation 'Realize task :bootJar' started
For the Groovy DSL, the Gradle team takes advantage of the metaprogramming offered by the Groovy language to dynamically make tasks, extensions, properties, and more "magically" available.
So for this example:
tasks.bootJar {
archiveFileName = "some-name"
}
tasks is of type TaskContainer. If you were to examine all available methods and properties for TaskContainer, you will see that bootJar is not one of them. So Gradle hooks into the Groovy metaprogramming to search for something named bootJar. Since it's on the TaskContainer type, it can be assumed that bootJar is a task.
So if you were to desugar the DSL, the first example is effectively:
tasks.getByName("bootJar") {
}
Now for the second example:
bootJar {
archiveFileName = "some-code"
}
The default scope or this in a Gradle build file is Project. Again, just like before, if you were to examine all available methods and properties, you will not see bootJar as one of them.
Groovy's 'magic' is at play here, but this time around, Gradle will search (my understanding) practically everywhere because there is a lot more available on a Project.
project.extensions.named("bootJar") // exists?
project.hasProperty("bootJar") // exists?
project.tasks.getByName("bootJar") // found it!
To summarize, no there is no difference between the two since both cause the bootJar task to be realized. Use task configuration avoidance wherever possible to make your Gradle builds more efficient:
import org.springframework.boot.gradle.tasks.bundling.BootJar
tasks.named("bootJar", BootJar) {
}

Passing parameters to dependable task of custom task

There is task which can be executed with parameter like this:
./gradlew taskX -Pkey=value
And plugin with custom task which should execute taskX:
class CustomPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.tasks.register("custom", CustomTask::class.java)
.configure {
it.description = "Description"
it.group = "Group"
val taskX = project.getTasksByName("taskX", true).first()
it.dependsOn(taskX)
}
}
}
I would expect something like this for example:
it.dependsOn(taskX, "key=value")
How to pass parameters to dependsOn?
Simple answer: You can't. Task dependencies only express what needs to be done beforehand, not how it needs to be done.
Let me show you a simple example, why something like this is not possible in the Gradle task system:
First, we need to know that in Gradle, every task will be executed only once in a single invocation (often called build). Now imagine a task that needs to be run before two tasks that are unrelated to each other. A good real world example is the task compileJava from the Java plugin that both the test task and the jar task depend on. If dependsOn would support parameters, it could happen that two tasks depend on a single task with different parameters. What parameters should be used in this case?
As a solution, you may configure the other task directly in your plugin. If you want to pass the parameter only if your custom task is run, you may need to add another task that runs as a setup and applies the required configuration to the actual task:
task setup {
doFirst {
// apply configuration
}
}
taskX.mustRunAfter setup
task custom {
dependsOn setup
dependsOn taskX
}
This example uses Groovy, but it should be possible to translate it to Kotlin and use it in your plugin.
Edit regarding actual parameter
To be honest, I am not that familiar with the Android Gradle plugin, but if I get this documentation right, the project property android.testInstrumentationRunnerArguments.annotation is just an alternative to using the following code in the build script:
android {
defaultConfig {
testInstrumentationRunnerArgument 'annotation', '<some-value>'
}
}
You may try to define the following task and then run it using ./gradlew customTest
task customTest {
doFirst {
android.defaultConfig.testInstrumentationRunnerArgument 'annotation', '<some-value>'
}
finalizedBy 'connectedAndroidTest'
}

How to create a gradle task that will execute bootRun with a specific profile?

I essentially want to create a task in gradle that executes the command
gradle bootRun -Dspring.profiles.active=test
This command does exactly what I want it to do if executed from the command line but I have had no luck trying to use type:Exec on a task and also no luck passing in System properties
I don't really want to make this into an external command that the user needs to know about to run. I would like it to show up under tasks/other.
My closest attempt so far:
task bootRunTest() {
executable "gradle"
args "-Dspring.profiles.active=test bootRun"
}
The task I was trying to create wound up being this:
task bootRunTest(type: org.springframework.boot.gradle.run.BootRunTask, dependsOn: 'build') {
group = 'Application'
doFirst() {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
systemProperty 'spring.profiles.active', 'test'
}
}
Here is how you set the properties for the task you wish to run, in this case bootRun
add inside of Build.gradle
bootRun {
systemProperty "spring.profiles.active", "test,qa,ect"
}
Then from the command line
gradle bootRun
You can also do it by setting the OS variable, SPRING_PROFILES_ACTIVE, to the specific profile.
For eg:
SPRING_PROFILES_ACTIVE=dev gradle clean bootRun

Gradle: Fail on adding systemProperty

I'm trying to add a .dll file to the "java.library.path" system property via gradle on my Spring Boot project. I'm using Gradle 2.1 on STS.
This is the small piece of groove code within my build.gradle:
tasks.withType(JavaCompile) {
systemProperty "java.library.path", file("./src/main/resources/META-INF/opencv-2.4.9/windows_bin/x64")
}
And I'm getting the following error:
Could not find method systemProperty() for arguments [java.library.path, D:\GitHub\TFG_1\GuiaTV\src\main\resources\META-INF\opencv-2.4.9\windows_bin\x64] on root project 'GuiaTV'
That path does exists, so I don't know where the problem is.
Any help? Thank you!
UPDATE 1:
#Amnon Shochot
What I try to do is to add a native library (.dll) to the project. I took the idea from some sites (for example, http://zouxifeng.github.io/2014/07/17/add-system-property-to-spring-boot.html, https://github.com/cjstehno/coffeaelectronica/wiki/Going-Native-with-Gradle).
The first one is using what you suggested:
tasks.withType(JavaExec) {
systemProperty "java.library.path", file("./libs")
}
The second one is using:
run {
systemProperty 'java.library.path', file( 'build/natives/windows' )
}
None of them are working for me.
The first one (with JavaExec) is failing gradle test throwing:
java.lang.UnsatisfiedLinkError: no opencv_java249 in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1865)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
If you follow the trace, it's crashing at runtime in sentence: System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
And the second one is failing on gradle build with the following message:
Could not find method run() for arguments [build_24sfpo0st6dokeq7fn3ad7r34$_run_closure7#2652c3da] on root project 'GuiaTV'.
Luckily you know exactly what I try to achieve and you can solve my problem.
Thank you for your interest!
UPDATE 2:
Finally, I ended up adding these lines to my build.gradle script:
// The following makes "gradle build", "gradle test" work
test {
jvmArgs = ['-Djava.library.path=./src/main/resources/META-INF/opencv-2.4.9/windows_bin/x64']
}
// Thw following makes "gradle run" work
run {
jvmArgs = ['-Djava.library.path=./src/main/resources/META-INF/opencv-2.4.9/windows_bin/x64']
}
By the way, I'm also using "spring-boot" gradle plugin. That's where the run task comes from.
So, I can execute "gradle build", "gradle test" and "gradle run" sucessfully. This is, that native library is correctly added.
However, since I'm also using "eclipse" gradle plugin, I would like to add the native library simply by executing "gradle eclipse". Instead, I must create the library on Eclipse manually, and add it to my project.
Thank you #Amnon for your collaboration. I'll be posting a new solution in the case I found it.
The problem is that you do not set the context for the systemProperty method thus Gradle tries to locate it in the project object where it does not exist which is the reason for the error you got.
If you wanted to apply this configuration for all tasks of type JavaCompile your code should have been looked like:
tasks.withType(JavaCompile) { JavaCompile t ->
t.systemProperty "java.library.path", file("./src/main/resources/META-INF/opencv-2.4.9/windows_bin/x64")
}
However, the JavaCompile task type also does not contain a systemProperty so this code wouldn't work either.
You can define CompileOptions for a JavaCompile task using its options property, i.e.:
tasks.withType(JavaCompile) { JavaCompile t ->
t.options "java.library.path", file("./src/main/resources/META-INF/opencv-2.4.9/windows_bin/x64")
}
However, I'm not sure whether you can define this specific system property.
One last note - the systemProperty method does exist for tasks of type JavaExec in case that this is what you intended to do.

How to pass system property to Gradle task

I'm using Gradle spring-boot plugin and I need to select a spring active profile for the test run.
How do I pass spring.profiles.active system property to the bootRun plugin's task?
What has already failed:
task bootRunLocal {
systemProperty "spring.profiles.active", "local"
System.setProperty("spring.profiles.active", "local")
tasks.bootRun.execute() // I suspect that this task is executed in a separate JVM
}
and some command line magic also fails:
./gradle -Dspring.profiles.active=local bootRun
Could someone kindly help me solve my troubles?
Update from the answers and comments:
I'm able to set the systemProperty and pass it to the spring container by doing :
run {
systemProperty "spring.profiles.active", "local"
}
However, when I do this, the local profile is being set for both bootRun task and bootRunLocal task. I need a way to set this property for bootRunLocal task and call booRun task from bootRunLocal.
That might sound very simple, but I come with peace from the structured world of Maven.
I know I'm late here... but I recently faced this exact issue. I was trying to launch bootRun with spring.profiles.active and spring.config.location set as system properties on the command line.
So, to get your command line "magic" to work, simply add this to your build.gradle
bootRun {
systemProperties System.properties
}
Then running from the command line...
gradle -Dspring.profiles.active=local bootRun
Will set local as the active profile, without needing to define a separate task simply to add the env variable.
task local {
run { systemProperty "spring.profiles.active", "local" }
}
bootRun.mustRunAfter local
Then run gradle command as:
gradle bootRun local
There is no generic way to pass system properties to a task. In a nutshell, it's only supported for tasks that fork a separate JVM.
The bootRunLocal task (as defined above) will not execute in a separate JVM, and calling execute() on a task isn't supported (and would have to happen in the execution phase in any case). Tests, on the other hand, are always executed in a separate JVM (if executed by a Test task). To set system properties for test execution, you need to configure the corresponding Test task(s). For example:
test {
systemProperty "spring.profiles.active", "local"
}
For more information, see Test in the Gradle Build Language Reference.
SPRING_PROFILES_ACTIVE=local gradle clean bootRun
This is according to this and this and it works.
According to the spring-boot-gradle-plugin documentation you should be able to pass arguments like this
./gradlew bootRun --args='--spring.profiles.active=dev'
Seems like this is a new gradle feature since 4.9. I used it in my project and it worked out of the box.
For gradle 2.14 below example works.
I have added as below.
When System.properties['spring.profiles.active'] is null then default profile is set.
bootRun {
systemProperty 'spring.profiles.active', System.properties['spring.profiles.active']
}
command line example
gradle bootRun -Dspring.profiles.active=dev
Just for reference if anyone will have this issue:
Vlad answer didn't quite worked for me but this one works great with 2.4,
task local <<{
bootRun { systemProperty "spring.profiles.active", "local" }
}
local.finalizedBy bootRun
then gradle local
Responding to OP's exact request here ...
How do I pass spring.profiles.active system property to the bootRun plugin's task?
And assuming by "pass" the OP meant "pass from commandline" or "pass from IDE invocation" ... This is how I like to do it.
Add this to build.gradle:
/**
* Task from spring-boot-gradle-plugin, configured for easier development
*/
bootRun {
/* Lets you pick Spring Boot profile by system properties, e.g. gradle bootRun -Dspring.profiles.active=dev */
systemProperties = System.properties
}
Then when you invoke it, use the familiar Java flag for setting a system property
gradle bootRun -Dspring.profiles.active=local
There is one main advantage of sticking to system properties, over the environment variables option (SPRING_PROFILES_ACTIVE=local gradle bootRun) ... and that's easy portability between Linux/OS X (bash, etc.) and Windows (cmd.exe anyway).
I learned this way from this blog post.
(UPDATE: Ah somehow I had missed #Erich's response with same recommendation. Oops! I'm leaving my answer, because of the additional details about portability, etc.)
You can create a new task (in discussed case with name bootRunLocal), that would extend org.springframework.boot.gradle.run.BootRunTask and setup properties before task execution. You can create such a task with following code:
task bootRunLocal(type: org.springframework.boot.gradle.run.BootRunTask) {
doFirst() {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
systemProperty "spring.profiles.active", "local"
}
}
More details can be found here:
https://karolkalinski.github.io/gradle-task-that-runs-spring-boot-aplication-with-profile-activated/
Starting from SpringBoot 2.0.0-M5 setSystemProperties() is no longer a method of the task bootRun.
The build.gradle needs to be updated to
bootRun {
execSpec {
// System.properties["spring.profiles.active"]
systemProperties System.properties
}
}
This is as springBoot's run task uses org.gradle.process.JavaExecSpec
This works for me using Gradle 4.2
This works:
SPRING_PROFILES_ACTIVE=production ./gradlew app-service:bootRun
with run command you can add to build file run { systemProperties = System.properties } and start with gradle run -Dspring.profiles.active=local
Another way which doesn't require any support from the gradle task: Set the JAVA_TOOL_OPTIONS environment variable:
JAVA_TOOL_OPTIONS='-Dfoo=bar' gradle ...
Or if the variable might already contain anything useful:
JAVA_TOOL_OPTIONS="$JAVA_TOOL_OPTIONS -Dfoo=bar" gradle ...
// defualt value
def profiles = 'dev'
bootRun {
args = ["--spring.profiles.active=" + profiles]
}
Then you can simply pick a specific version when starting a gradle task, like
./gradlew bootRun -P dev
"dev" is gonna to take place "prod"

Resources