Groovy classpath not set up properly by <groovy> Ant task - ant

My Groovy script depends on some libraries. This is what I have at the top of my script.
#Grapes([
#Grab(group = 'net.sf.json-lib', module = 'json-lib', version = '2.3',
classifier = 'jdk15'),
#Grab(group = 'org.codehaus.groovy.modules.http-builder',
module = 'http-builder', version = '0.7.1'),
#Grab(group = 'commons-cli', module = 'commons-cli', version = '1.2')])
When I run the script from command line using groovy executable, everything works properly. The artefacts get downloaded and the script runs.
However, if I try to execute the same script from Apache Ant using <groovy src="myscript.groovy" fork="true" /> (simplified), the artefacts also get resolved and downloaded but then I get [groovy] Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException.
The Apache Ant installation uses groovy-all-2.3.6.jar that I have copied from the Groovy installation that I have installed, so they should be pretty much identical.
What am I missing? How can I make the <groovy> task work and use the downloaded jars?
UPDATE I
The issue I believe is that Grape and Ant use different classloaders so the artifacts aren't visible to Ant. Can you try adding this: #GrabConfig(systemClassLoader = true) to your groovy script after the #Grape annotations?
If I do that I get General error during conversion: No suitable ClassLoader found for grab.
UPDATE II
I have also tried this now:
import groovy.grape.Grape;
Grape.grab(group:"commons-cli", module:"commons-cli", version:"1.2", classLoader:this.class.classLoader.rootLoader)
//...
It does not help. I get compile time error then:
[groovy] Exception in thread "main" Script Failed: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
[groovy] C:\Users\xxx\AppData\Local\Temp\embedded_script_in_2825216891785993632groovy_Ant_task: 18: unable to resolve class groovyx.net.http.HTTPBuilder
[groovy] # line 18, column 1.
[groovy] import groovyx.net.http.HTTPBuilder
[groovy] ^

Get rid of the #Grab and use the static .grab() method Grape offers. It allows you to specify a the rootLoader classloader which Ant can see:
import groovy.grape.Grape;
Grape.grab(group:"commons-cli", module:"commons-cli", version:"1.2", classLoader:this.class.classLoader.rootLoader)
<repeat for rest of #Grab>

Related

how to successfully build ant source code?

I reinstalled between jdk-8 and jdk-12, the building process shows different errors but both failed. And both are showing in the log that the bcel package is missing as the first error.
I've set JAVA_HOME in both jdk with the corresponding value;
sh build.sh -Ddist.dir=~/tmp/ant dist
this is the code I get from the org document for building.
Loading source files for package org.apache.tools.tar...
Loading source files for package org.apache.tools.zip...
Constructing Javadoc information...
/home/uppdev/tmp/ant/src/main/org/apache/tools/ant/filters/util/JavaClassHelper.java:23: error: package org.apache.bcel.classfile does not exist
import org.apache.bcel.classfile.ClassParser;
^
/home/uppdev/tmp/ant/src/main/org/apache/tools/ant/filters/util/JavaClassHelper.java:24: error: package org.apache.bcel.classfile does not exist
import org.apache.bcel.classfile.ConstantValue;
:
:
:
Building index for all the packages and classes...
Building index for all classes...
Generating /home/uppdev/tmp/ant/build/javadocs/help-doc.html...
Note: Custom tags that could override future standard tags: #todo. To avoid potential overrides, use at least one period character (.) in custom tag names.
26 errors
100 warnings
BUILD FAILED
/home/uppdev/tmp/ant/build.xml:1012: The following error occurred while executing this line:
/home/uppdev/tmp/ant/build.xml:1520: Javadoc returned 1
Total time: 20 seconds
If this is for ant 1.10.2 then I can provide info:
JDK8 returns an error for missing references in javadocs (see https://bugs.openjdk.java.net/browse/JDK-8224266) which can be maded non-fatal by passing -Xdoclint:none to javadoc.
ant 1.10.2 removed this flag together with the configure param withDoclint which made builds fail if the optional dependencies were not found.
A workaround is to add additionalparam="-Xdoclint:none" to the <javadoc ...> tag in the <target name="javadocs" in build.xml before building.
Fixed part of 1.10.2:
<target name="javadocs" depends="check-javadoc"
description="--> creates the API documentation" unless="javadoc.notrequired">
<mkdir dir="${build.javadocs}"/>
<javadoc additionalparam="-Xdoclint:none"
useexternalfile="yes"
destdir="${build.javadocs}"
failonerror="true"
author="true"
version="true"
locale="en"
windowtitle="${Name} API"
doctitle="${Name}"
maxmemory="1000M"
verbose="${javadoc.verbose}">

Why am I getting groovy.lang.MissingPropertyException for TRACE?

In groovy file I've imported jars groovy.util.logging.Log4j and
org.apache.log4j.Level for using #Log4jand I'm setting log level as: log.setLevel(Level.TRACE) in the constructor.
Now while executing the script I'm getting groovy.lang.MissingPropertyException: No such property: TRACE for class: org.apache.log4j.Level but when I replace TRACE with INFO it executes successfully.
So what will be the reason for this?
Do you use multiple version of log4j in your application?
[log4j-1.2.16.jar & lower to log4j-1.2.12.jar which doesn't support TRACE]
In this case,lower version might have been taken into consideration by your groovy script.If you are executing script in LINUX,append $GROOVY_HOME/lib/log4j-1.2.16.jar to $CLASSPATH at the end. This works!!!

Missing ant property while configuring worklight database via ant task

I am integrating worklight 6.1 official deployment ant task into gradle build script.
We will utilize below script to run flexible continuous integration process.
def antTaskLibClasspath = "ant-task-lib/worklight-ant-deployer.jar"
def verifyDatabaseArguments(String database){
switch(project.ext[database + 'Type']){
case 'derby':
def dbNameProp = database + 'Name'
def dbDirPathProp = database + 'Dir'
def dbProperties = ['databaseName':project.ext[dbNameProp], 'databaseDir':project.ext[dbDirPathProp] ]
.each { key, value ->
if(!value?.trim()){
def errMsg = "Missing mandatory parameter : ${key}"
println errMsg
throw new StopExecutionException(errMsg)
}
}
project.ext[dbDirPathProp] = Eval.me(""" "${project.ext[dbDirPathProp]}" """).replace("\\", "/")
def dbFile = file(project.ext[dbDirPathProp] + "/${project.ext[dbNameProp]}")
if(!dbFile.exists()){
if(dbFile.mkdirs()){
println "Create folders ${project.ext[dbDirPathProp]} for ${database} derby database"
}else {
def errMsg = "Can not create folders for ${database} derby database"
println errMsg
throw new StopExecutionException(errMsg)
}
}
break
case 'oracle':
break
default:
errMsg = "Unsupported database type"
println errMsg
throw new StopExecutionException(errMsg)
break
}
}
verifyDatabaseArguments("worklightDatabase")
verifyDatabaseArguments("worklightReportsDatabase")
task configure {
description "Configure database for worklight server"
doLast {
ant.typedef(name:'configureDatabase',
classname:'com.ibm.worklight.config.ant.database.ConfigureDatabaseTask',
classpath:antTaskLibClasspath
)
ant.configureDatabase(kind: "Worklight"){
switch(worklightDatabaseType){
case 'derby':
derby(database:worklightDatabaseName, datadir:worklightDatabaseDir)
break
}
}
ant.configureDatabase(kind: "WorklightReports"){
switch(worklightReportsDatabaseType){
case 'derby':
derby(database:worklightReportsDatabaseName, datadir:worklightReportsDatabaseDir)
break
}
}
}
}
And these are properties which were referenced in the script overhead. I've set them in gradle.properties where the build.gradle is located.
worklightDatabaseType=derby
# derby database name
worklightDatabaseName=WRKLGHT
# derby database file directory
worklightDatabaseDir=${System.properties['user.home']}/.derby/ibm
worklightReportsDatabaseType=derby
# derby database name
worklightReportsDatabaseName=WLREPORT
# derby database file directory
worklightReportsDatabaseDir=${System.properties['user.home']}/.derby/ibm
The command line shows ant error message which I can't figure out what's going wrong after I try to configure database with command $ > gradle configure.
Line 75 is the place where I start the first invocation of ant.configureDatabase( ...
Did I miss any mandatory configuration which may not documented in the worklight 6.1?
My jdk version is jdk7_60, gradle version 2.4 without wrapper.
Any suggestion/comment is appreciated, thank you~
By the way, if any consultant from IBM mobilefirst team is watching,
please consider to ask your product team to rename ant task which has dash symbol in it's name.
It seems that Groovy AntBuilder can not load ant element name includes dash symbol,
so we have to unzip worklight ant task jar archives and search for the task class we need in defaults.properties,
then redefine ant task using class name manually in gradle script. That's not convenient.
The build progress of worklight project is complex. We don't like to use ant to setup build automation.
Appended after Peter post his suggestion:
Thank you, Peter.
I have step over the ant library issue after adopting your way.
But it stucks again, and I couldn't interpret the error message.
At first I assume this issue is because worklight 6.1 ant deploy task may not be compatible with gradle,
so I wrote ant build script below to test if my assumption is correct,
which implements the same build logic and variable as previous gradle script does.
build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="install">
<loadproperties srcfile="build.properties" />
<taskdef resource="com/worklight/ant/defaults.properties">
<classpath>
<pathelement location="worklight-ant-task-libs/worklight-ant-deployer.jar"/>
</classpath>
</taskdef>
<target name="configure">
<configuredatabase kind="Worklight">
<derby database="${worklightDatabaseName}" datadir="${worklightDatabaseDir}"/>
</configuredatabase>
<configuredatabase kind="WorklightReports">
<derby database="${worklightReportsDatabaseName}" datadir="${worklightReportsDatabaseDir}"/>
</configuredatabase>
</target>
</project>
build.properties
# derby database name
worklightDatabaseName=WRKLGHT
# derby database file directory
worklightDatabaseDir=${user.home}/.derby/ibm
# derby database name
worklightReportsDatabaseName=WLREPORT
# derby database file directory
worklightReportsDatabaseDir=${user.home}/.derby/ibm
And my build progress fails again.
I have upload the ant error message log file to google drive.
Can anyone give me some suggestion to help me figure it out?
Thank you~
I'm going to use a lot of guesswork here, but according to this section of the Ant Manual, ant.library.dir is only set by Ant's Launcher class, which Gradle's Ant integration probably doesn't use.
I suspect that the Worklight Ant task you're using assumes that property is set and throws an exception. You can check this by running
gradle --stacktrace configure
assuming that configure is the task you want to run. This will show you where the exception is being thrown from (and any causes too).
You might be best off adding an unpacked Ant distribution to your source tree (or perhaps just its lib directory) and adding the following entry to a gradle.properties file in the root of your project:
systemProp.ant.library.dir=<path to Ant>/lib
Of course you should replace <path to Ant> with the actual path to an Ant installation.

Running Ant build from Gradle, how to pass -lib argument?

I want to slowly migrate to a better build and dependency resolution process, we are currently using Ant with local file dependencies.
We chose to migrate to gradle ,so as a first step I would like to simply run my current ant build from a gradle sript. But i dont know how to pass the -lib classpath to ant. Im getting errors of missing dependencies.
This is my gradle.build:
apply plugin: 'java'
task someProperties {
ext.LIBS_CATW = "backend/java-src/lib"
ext.LIB_SERVLET = "/usr/local/apache-tomcat-7.0.32/lib/servlet-api.jar"
}
dependencies {
compile files('/usr/local/apache-tomcat-7.0.32/lib/servlet-api.jar')
compile fileTree(dir: 'backend/java-src/lib', include: '*.jar')
}
I use this shell script to run ant from command line.
#!/bin/bash
export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home"
ROOT_DIR="/Users/poolebu/catwizardMultitenant/catwizard/catwBackend/branches/branchSpringSecurity/"
DIR_MT="$ROOT_DIR"
LIBS_CATW="$ROOT_DIR/backend/java-src/lib"
LIB_SERVLET="/usr/local/apache-tomcat-7.0.32/lib/servlet-api.jar"
ANT_TARGET="allButFlex"
cd $DIR_MT
ant -lib $LIBS_CATW -lib $LIB_SERVLET $ANT_TARGET
This is one of the many dependency errors I´m getting
[ant:javac] /Users/poolebu/catwizardMultitenant/catwizard/catwBackend/branches/branchSpringSecurity/backend/java-src/catw-common/src/com/bamboo/common/factory/SpringFactory.java:5: error: package flex.messaging does not exist
[ant:javac] import flex.messaging.FlexFactory;
[ant:javac] ^

Could not create task or type: getProjectData from Ant

I am trying to run an Ant task from within IBM RSA IDE using Ant build ...
I get the following error message:
BUILD FAILED
build.xml:21: Could
not create task or type of type: getProjectData.
Ant could not find the task or a class this task relies upon.
This is common and has a number of causes; the usual
solutions are to read the manual pages then download and
install needed JAR files, or fix the build file:
- You have misspelt 'getProjectData'.
Fix: check your spelling.
- The task needs an external JAR file to execute
and this is not found at the right place in the classpath.
Fix: check the documentation for dependencies.
Fix: declare the task.
- The task is an Ant optional task and the JAR file and/or libraries
implementing the functionality were not found at the time you
yourself built your installation of Ant from the Ant sources.
Fix: Look in the ANT_HOME/lib for the 'ant-' JAR corresponding to the
task and make sure it contains more than merely a META-INF/MANIFEST.MF.
If all it contains is the manifest, then rebuild Ant with the needed
libraries present in ${ant.home}/lib/optional/ , or alternatively,
download a pre-built release version from apache.org
- The build file was written for a later version of Ant
Fix: upgrade to at least the latest release version of Ant
- The task is not an Ant core or optional task
and needs to be declared using <taskdef>.
- You are attempting to use a task defined using
<presetdef> or <macrodef> but have spelt wrong or not
defined it at the point of use
Remember that for JAR files to be visible to Ant tasks implemented
in ANT_HOME/lib, the files must be in the same directory or on the
classpath
Please neither file bug reports on this problem, nor email the
Ant mailing lists, until all of these causes have been explored,
as this is not an Ant bug.
Here's the Ant buildfile:
<!-- Get property locationName. -->
<target name="config">
<echo message="${ear.project.name}" />
<getProjectData projectName="${ear.project.name}" />
</target>
I am not quite sure what the problem is here because the error message seems not helpful. Any suggestions?
I believe getProjectData is an IBM extension to ant. Like you, I had a similar error, but I was able to get it working after ensuring the Run in the same JRE as the workspace option was enabled (which you can find by right-clicking the build file, run-as, Ant Build..., and selecting the option on the JRE tab).
I discovered the solution on the IBM info center:
The Run in the same JRE as the workspace option enables the classpath
of the workbench to access the additional Ant tasks that perform
operations that are specific to the workbench, such as projectImport,
projectBuild, workspaceBuild, ejbDeploy, or earExport. If your Ant
build script uses any Ant tasks that perform workbench operations,
verify that you selected the Run in the same JRE as the workspace
option; otherwise you might get the following error message in the
Console view:
Problem: failed to create task or type <Ant task> Cause:
The name is undefined.
The build file I used looked like this:
<?xml version="1.0"?>
<project name="Test" default="config" basedir=".">
<target name="config">
<getProjectData Basedir="${basedir}" />
<echo message="getProjectData: projectName=${projectName}
nature=${natureName}
workspace=${workspaceName}
basedir=${basedir}" />
</target>
</project>
And output:
Buildfile: C:\DATA\java\workspace\test-java\build.xml
config:
[getProjectData] Setting projectName=test-java
[getProjectData] Retrieved following Project Data :
[getProjectData] workspaceName=C:\DATA\java\workspace
[getProjectData] natureName=Java
[echo] getProjectData: projectName=test-java
nature=Java
workspace=C:\DATA\java\workspace
basedir=C:\DATA\java\workspace\test-java
BUILD SUCCESSFUL
Total time: 78 milliseconds

Resources