Setting environment variables from Gradle - ant

I need to execute from Gradle an Ant script which relies on environment variables.
Ant uses <property environment="env"/> for it.
I tried to do env.foo="bar" in Gradle, but it throws a Groovy exception.
What is the proper way to pass environment variables from Gradle to Ant?

From the gradle 2.0 docs, i see something like this is possible
test {
environment "LD_LIBRARY_PATH", "lib"
}
Or in this case could use this
systemProperty "java.library.path", "lib"

It is impossible to set environment variables from Gradle or JVM in general, but it is possible to trick Ant like this:
ant.project.properties['env.foo'] = 'bar'

Accepted solution from #Sergey:
ant.project.properties['env.foo'] = 'bar'
Does not work for me on gradle 2.9 and ant 1.9.7.
That did not thrown any error, but do nothing. Indeed if you are look at code it implemented as:
public Hashtable<String, Object> getProperties() {
return PropertyHelper.getPropertyHelper(this).getProperties();
}
where org.apache.tools.ant.PropertyHelper#getProperties is:
public Hashtable<String, Object> getProperties() {
//avoid concurrent modification:
synchronized (properties) {
return new Hashtable<String, Object>(properties);
}
}
So it make explicit copy and it can't work.
The way do it correctly in gradle file:
ant.project.setProperty('env.foo', 'bar')
Documentation mention few other ways (note, without project):
ant.buildDir = buildDir
ant.properties.buildDir = buildDir
ant.properties['buildDir'] = buildDir
ant.property(name: 'buildDir', location: buildDir)

Related

Copy subfolder with groovy in Jenkins

I am trying to script a groovy script which copies a complete folder with all subfolder and jobs to the actual folder, where the script is executed.
Here you can see how my folderstructure looks like.
--> Templ
|-->Folder
|-->Folder
|-->Subfolder
|-->Subsubfolder
|-->Subfolder
|-->Folder
-->Execution 2020
|-->Copyscript
I tried with different Plug-Ins like Jobcopy Builder.
Finally I tried with groovy scrips but nothing seems to work.
the simplest way to use AntBuilder
def ant = new AntBuilder()
ant.copy(todir: myDir) {
fileset(dir: "src/test") {
include(name: "**/*.java")
}
}
example taken from here
http://docs.groovy-lang.org/latest/html/documentation/ant-builder.html
to see all parameters of ant copy command see documentation:
https://ant.apache.org/manual/Tasks/copy.html

Gradle - "override" behaviour/properties from build.gradle

I'm not a Gradle expert by any means so please be gentle...
I have a Gradle build which I'm trying to run on Jenkins. The build.gradle contains the following:
repositories {
maven {
url "http://some_internal_corporate_repo"
}
}
The Jenkins server that I am running the job on cannot access "some_internal_corporate_repo".
As I can't modify the build.gradle I would like to know if there's a way I can somehow extend or override the build.gradle, on the Jenkins server, to point to mavenCentral (or similar), maybe via an init file or setting a property etc?
Thanks in advance
EDIT: in the end, because I was using Jenkins, I used it's Groovy support (execute Groovy build step) to address my issue:
def file = new File('build.gradle')
def newConfig = file.text.replace('url "http://some_internal_corporate_repo"', 'url "http://repo.maven.apache.org/maven2/"')
file.text = newConfig
You can define multiple repositories.
The order of declaration determines how Gradle will check for dependencies at runtime
repositories {
maven {
url "http://some_internal_corporate_repo"
}
mavenCentral()
}
You can use a properties to define the maven repo url:
repositories {
maven {
url "${repositories_maven_url}"
}
}
In the gradle.properties file
repositories_maven_url=maven_url
According to the gradle documentation, gradle.properties files are applied in the following order:
gradle.properties in project root directory.
gradle.properties in GRADLE_USER_HOME directory.
system properties, e.g. when -Dgradle.user.home is set on the command line.
Or you can use something like this:
repositories {
maven {
url getMavenUrl()
}
}
/**
* Returns the url of the maven repo.
* Set this value in your ~/.gradle/gradle.properties with repositories_maven_url key
* If the property is not defined returns a default value
* #return
*/
def getMavenUrl() {
return hasProperty('repositories_maven_url') ? repositories_maven_url : "YOUR_DEFAULT_VALUE"
}

How to set environment variables when testing DSL scripts against dummy jenkins?

I am trying to automate testing Jenkins groovy dsl scripts, like here:
https://github.com/sheehan/job-dsl-gradle-example
The idea I think is very straight forward, what I'm having issues with is setting environment variables for the dummy Jenkins. I followed the instructions here:
https://wiki.jenkins-ci.org/display/JENKINS/Unit+Test
Specifically "How to set env variables" section and added the following to my test executor:
import hudson.slaves.EnvironmentVariablesNodeProperty
import hudson.EnvVars
/**
* Tests that all dsl scripts in the jobs directory will compile.
*/
class JobScriptsSpec extends Specification {
#Shared
#ClassRule
JenkinsRule jenkinsRule = new JenkinsRule()
EnvironmentVariablesNodeProperty prop = new EnvironmentVariablesNodeProperty();
EnvVars envVars = prop.getEnvVars();
#Unroll
void 'test script #file.name'(File file) {
given:
envVars.put("ENVS", "dev19");
jenkinsRule.jenkins.getGlobalNodeProperties().add(prop);
JobManagement jm = new JenkinsJobManagement(System.out, [:], new File('.'))
when:
new DslScriptLoader(jm).runScript(file.text)
then:
noExceptionThrown()
where:
file << jobFiles
}
However when I run the actual tests for one of the scripts, I still see the following:
Failed tests
test script Build.groovy
Expected no exception to be thrown, but got 'javaposse.jobdsl.dsl.DslScriptException'
at spock.lang.Specification.noExceptionThrown(Specification.java:118)
at com.dslexample.JobScriptsSpec.test script #file.name(JobScriptsSpec.groovy:40)
Caused by: javaposse.jobdsl.dsl.DslScriptException: (script, line 3) No such property: ENVS for class: script
The script Build.groovy uses the variable "${ENVS}" (as if it were provided by parameter in seed job of Jenkins), which works as expected when actually running in Jenkins... So any way to set these "parameters" or env variables in the test jenkins context?
Example of how I use the ENVS variable in the Build.groovy:
def envs = '-'
"${ENVS}".eachLine{
def env = it
envs+=env+'-'
}
envs.substring(0,envs.length()-1)
job('Build'+envs) {
...
}
The second argument of the JenkinsJobManagement constructor is a map of environment variables which will be available in the DSL scripts.
Map<String, String> envVars = [
FOO: 'BAR'
]
JobManagement jm = new JenkinsJobManagement(System.out, envVars, new File('.'))

How perform OpenJPA Enhancement when using Gradle?

I've tried this gradle plugin https://github.com/schmutterer/gradle-openjpa but it complains that it cannot find certain libraries and doesn't support providedCompile which makes this unusable for me anyway.
I've also tried calling ANT tasks, my latest attempt below is throwing:
Caused by: C:\Work_Java\workspace\PaxHoldRelease\jpa_enhance.xml:5: taskdef class org.apache.openjpa.ant.PCEnhancerTask cannot be found
build.gralde
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'ear'
// Java compilier compliance level
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
mavenLocal()
mavenCentral()
}
ant.importBuild 'jpa_enhance.xml'
war.dependsOn enhance
dependencies {
// Ensure ear plugin gets war file
deploy files(war)
providedCompile 'javax.servlet:javax.servlet-api:3.0.1'
compile 'javax.websocket:javax.websocket-api:1.1'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.16'
compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.5.1'
compile 'org.glassfish:javax.json:1.0.4'
providedCompile 'org.apache.openjpa:openjpa:2.2.2'
providedCompile 'com.sybase:jconn3:6.05'
providedCompile files('libs/sqljdbc4-3.0.jar')
}
jpa_enhance.xml
This is the latest version in a long list of attempts and probably complete rubbish as I just ripped everything out in a fit of desperation :-(
<project>
<target name="enhance">
<taskdef name="openjpac" classname="org.apache.openjpa.ant.PCEnhancerTask"/>
<!-- invoke enhancer on all .java files below the model directory -->
<openjpac>
</openjpac>
<echo message="Enhancing complete!"/>
</target>
</project>
Try this Andrew - I loosely based this gradle on the nice Enhancer script provided on S.O. by another member (for the DataNucleus enhancer).
Note that you will need to modify the entity-files (include/exclude) to point to your specific 'to be/to not be' enhanced Java source files. Further, this approach assumes that classpath derives from your parent build.gradle.
task openJPAEnhance {
description "Enhance JPA model classes using OpenJPA Enhancer"
dependsOn compileJava
doLast {
// define the entity classes
def entityFiles = fileTree(sourceSets.main.output.classesDir).matching {
include 'org/foo/mypkg/entity/*.class'
exclude 'org/foo/mypkg/entity/DoNotEnhance.class'
}
println "Enhancing with OpenJPA, the following files..."
entityFiles.getFiles().each {
println it
}
// define Ant task for Enhancer
ant.taskdef(
name : 'openjpac',
classpath : sourceSets.main.runtimeClasspath.asPath,
classname : 'org.apache.openjpa.ant.PCEnhancerTask'
)
// Run the OpenJPA Enhancer as an Ant task
// - see OpenJPA 'PCEnhancerTask' for supported arguments
// - this invocation of the enhancer adds support for a default-ctor
// - as well as ensuring JPA property use is valid.
ant.openjpac(
classpath: sourceSets.main.runtimeClasspath.asPath,
addDefaultConstructor: true,
enforcePropertyRestrictions: true) {
entityFiles.addToAntBuilder(ant, 'fileset', FileCollection.AntType.FileSet)
}
}
}
I hope this helps, and the individual who wrote that first gradle script did not mind that we re-purposed it (from DataNucleus) to OpenJPA.

Classpath for ant plugins when using ANTBuilder from Gradle

I have a build.gradle file which loads PMD (downloading it from upstream Maven), and then loads an Ant build.xml file which requires PMD:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'pmd:pmd:4.2.5'
}
}
ant.importBuild 'shared-build.xml'
However, the Ant import fails:
taskdef class net.sourceforge.pmd.ant.PMDTask cannot be found
using the classloader AntClassLoader[]
at org.apache.tools.ant.ProjectHelper.addLocationToBuildException(ProjectHelper.java:551)
[...]
at org.gradle.api.internal.project.DefaultAntBuilder.importBuild(DefaultAntBuilder.groovy:76)
How can Gradle's ant integration be instructed to make this available?
There's no straighforward way to do it, as Gradle does not offer any API support for this. So you need to hack it some way.
For example, you can do something like this, right before calling ant.importBuild
org.apache.tools.ant.Project.class.classLoader.addURL( file('libs/somelib.jar').toURI().toURL() )
Alternatively you can call the addURL() method with the paths you get through the Gradle's dependency resolution (again, this should be executed before the call to ant.importBuild).
configurations { someconf }
dependencies { someconf "org.eclipse.jdt:ecj:3.6.1" }
def antClassLoader = org.apache.tools.ant.Project.class.classLoader
configurations.someconf.each { File f ->
antClassLoader.addURL(f.toURI().toURL())
}
Of course, another solution would be to have the classpath defined inside your build.xml file so you won't have to do anything from Gradle.
See some input here http://gradle.1045684.n5.nabble.com/How-to-add-to-classpath-for-ant-importBuild-td3268631.html

Resources