Ant taskdef - requires both classpath and -lib parameter? - java

Whilst working on an Ant script today I noticed that even though my classpath was defined with the classpath attribute, I still needed to use -lib when starting ant (ie ant -lib myjar.jar) to make it run properly.
<project name="My Project" default="run-task" basedir=".">
<target name="run-task" description="Use the Ant Task">
<taskdef name="TaskName" classname="mypackage.MyClass" classpath="myjar.jar"/>
<TaskName />
</target>
</project>
Is there a quirk in the classloading for ant that requires this?

The following should work the same.
<path id="ant.tasks">
<fileset dir="lib" includes="myspecialant.jar"/>
</path>
<taskdef name="TaskName" classname="mypackage.MyClass" classpathref="ant.tasks"/>
I prefer to manage my classpaths at the top of my build separate to the logic that uses them. Make troubleshooting simpler.

Related

Jar to Mac OSX App Bundle with app bundler

I'm trying to bundle my .jar to a MacOSX app bundle, using app bundler.
I'm following this tutorial.
It says to add a lib folder to the high-level project directory, but I don't know what that means. I've been looking everywhere for it, and I cannot find out what it is. That's my only problem I have, anyone know?
EDIT:
Here is my build.xml file:
<project name="Rage Mage" basedir=".">
<taskdef name="ragemage"
classname="com.oracle.appbundler.AppBundlerTask"
classpath="lib/appbundler-1.0.jar" />
<target name="bundle-RageMage">
<delete dir="appBundle" failonerror="false"/>
<mkdir dir="appBundle"/>
<bundleapp outputdirectory="bundle"
name="Rage Mage"
displayname="Rage Mage"
icon="res/icon.icns"
identifier="ragemage.src.Window"
mainclassname="ragemage.src.Window">
<classpath file="dist/ragemage_1.1.1.jar" />
</bundleapp>
</target>
Thanks!
Okay, so, after having a little play around, this is what I understand...
Download Java Application Bundler and place it in the lib directory of your project. You will need to create this directory...
Create a new Ant script into your project directory, call it what ever you like...Also, take the time to read through the AppBundler Task Docs
The ant script should be based on the following skeleton...
<project name="ButtonDemo" default="bundle-buttonDemo" basedir=".">
<taskdef name="bundleapp"
classname="com.oracle.appbundler.AppBundlerTask"
classpath="lib/appbundler-1.0.jar" />
<!-- See the lib reference here, this is why you need to use the lib directory! -->
<target name="bundle-buttonDemo">
<delete dir="appBundle" failonerror="false"/>
<mkdir dir="appBundle"/>
<bundleapp outputdirectory="appBundle"
name="ButtonDemo"
displayname="Button Demo"
identifier="components.ButtonDemo"
mainclassname="components.ButtonDemo">
<!-- The following is important and should point to your build -->
<classpath file="dist/ButtonDemo.jar" />
<!-- You can have multiple instance of classpath if you 3rd party or
dependent jars in different locations -->
</bundleapp>
</target>
</project>
Build your project
Run the ant script, using (something like) ant -f {You App Bundler script}
The app bundle, in this case ButtonDemo.app will be created in appBundle directory. If you can, browse the contents of the ButtonDemo.app/Contents/Java and make sure all your required Jar files are there...
Happy bundling!
Updated based on updated build.xml file
1- There is no default target specified by the project tag. Think of this like your "main class" or "main" method, without, ant has no idea what you want to run...
<project name="Rage Mage" basedir="." default="bundle-RageMage">
2- The name of the taskdef is significant and you use it in the any script to identify what ant should do when it hits your tag reference...
So based on your example, you either need to change the name of the taskdef from ragemage to bundleapp or change the bundleapp tag to ragemage...
Either change this...
<taskdef name="bundleapp"
classname="com.oracle.appbundler.AppBundlerTask"
classpath="lib/appbundler-1.0.jar" />
or this (in target bundle-RageMage)
<ragemage outputdirectory="bundle"
name="Rage Mage"
displayname="Rage Mage"
icon="res/icon.icns"
identifier="ragemage.src.Window"
mainclassname="ragemage.src.Window">
<classpath file="dist/ragemage_1.1.1.jar" />
</ragemage>
Personally, I'd leave it as bundleapp, but that's me...
3- The delete, mkdir and outputdirectory attribute of bundleapp are related...
<delete dir="appBundle" failonerror="false"/>
<mkdir dir="appBundle"/>
<bundleapp outputdirectory="bundle"...
Either, make them all appBundle or bundle, what every you want...
4- You main class is unlikely to be ragemage.src.Window and is probably going to be Window

How to set up a Java workspace without an IDE

I usually code with IDEs like Intellij Idea or Eclipse, but due to several reasons, I no longer have access to an IDE, and I'd like to be able to code in Java on a remote Linux machine through a ssh terminal.
Making simple progams with only a few classes is easy, but some of my projects have several libraries and several separate .java files. I also need to export to a .jar file.
For example, I have the following file organisation:
project/
src/
a.java
b.java
c.java
libs/
lib1.jar
lib2.jar
out/
export_here.jar
someconfig.conf
The java app consists of the a, b, and c .java files, uses libraries lib1 and lib2, and the file someconfig.conf needs to be inside the export jar.
I want to know how to easily compile and build a project such as this.
In other words, I just want to know how to export my project into a runnable jar the right way.
I expect this can be done with a few commands. If so, I plan to make a shell script to automate everything.
Thanks in advance!
As suggested by other users you need to use a build management tool to do this like Ant, Maven etc. I have used Ant quiet frequently to do these kind of automated tasks. In order to install and Use Ant you can refer How To Install Apache Ant
After that the main task is to write your automation script and that is called a build xml in ant world. Here is a sample build.xml file you can refer to start with:
<project>
<target name="clean">
<delete dir="build"/>
</target>
<target name="compile">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>
</target>
<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="oata.HelloWorld"/>
</manifest>
</jar>
</target>
<target name="run">
<java jar="build/jar/HelloWorld.jar" fork="true"/>
</target>
</project>
And for more information on the above sample You can visit this
In General you can read more at How to create build.xml
After creating your build.xml you can run ant by ant <path to build.xml> or ant in case your build.xml lies in current directory
Hope this helps you in right direction

Error with self-bootstrapping Ant build

I'm trying to write an Ant build that does not require me adding Ant-plugins to Ant's lib directory, or /home/myuser/.ant/lib, or in my Eclipse instance's ant home, etc; namely because I will eventually be building my project on a hosted Jenkins server where I do not have access to the system's Ant installation.
I'm calling this a "self-bootstrapping" build, because I use Ivy to pull down my Ant plugins at build time, and hopefully, with some proper configuration, make their tasks available to Ant dynamically.
The jist of my build (using ant-contrib plugin as an example:
<?xml version="1.0" encoding="utf-8" ?>
<project name="myapp" default="audit" basedir="."
xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:antcontrib="antlib:net.sf.antcontrib">
<!-- Build path. -->
<path id="build.path">
<fileset dir="${lib.buildtime.dir}" includes="**/*.jar"/>
</path>
<target name="bootstrap">
<taskdef resource="org/apache/ivy/ant/antlib.xml"
uri="antlib:org.apache.ivy.ant" classpathref="build.path"/>
</target>
<target name="resolve" depends="bootstrap">
<ivy:settings url="${ivy.settings.home}"/>
<ivy:cleancache/>
<ivy:resolve file="${ivy.xml}"/>
<ivy:retrieve pattern="${gen.lib.main.dir}/[artifact]-[revision].[ext]" conf="main"/>
<ivy:retrieve pattern="${gen.lib.test.dir}/[artifact]-[revision].[ext]" conf="test"/>
<ivy:retrieve pattern="${gen.lib.buildtime.dir}/[artifact]-[revision].[ext]" conf="buildtime"/>
<ivy:report todir="${gen.staging.dir}" />
<ivy:cachepath pathid="build.path" conf="buildtime"/>
</target>
<target name="taskdefs" depends="resolve">
<taskdef resource="/net/sf/antcontrib/antlib.xml"
uri="antlib:net.sf.antcontrib" classpathref="build.path"/>
<property name="fizz" value="buzz" />
<antcontrib:if>
<antcontrib:equals arg1="${fizz}" arg2="buzz" />
<antcontrib:then>
<echo message="Fizz is buzz!" />
</antcontrib:then>
<antcontrib:else>
<echo message="Fizz is not buzz!" />
</antcontrib:else>
</antcontrib:if>
</target>
</project>
When I run the taskdefs target, instead of seeing an echoed "Fizz is buzz!" message in my Ant output, I get the following error:
BUILD FAILED
/home/myuser/eclipse/workspace/myapp/build.xml:169: Problem: failed to create task or type antlib:net.sf.antcontrib:if
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any <presetdef>/<macrodef> declarations have taken place.
No types or tasks have been defined in this namespace yet
This appears to be an antlib declaration.
Action: Check that the implementing library exists in one of:
-/home/myuser/eclipse/plugins/org.apache.ant_1.8.3.v201301120609/lib
-/home/myuser/.ant/lib
-a directory added on the command line with the -lib argument
Is what I am trying to do (avoid having to do 1 of the 3 recommended things above) impossible? If so, why? If not, what is wrong with my setup here? Thanks in advance!
I normally create a single "boostrap" target and use this to install ivy into the "$HOME/.ant/lib" directory. See:
Ivy fails to resolve a dependency, unable to find cause
The following is a more complete example that does what you're trying to do:
How to include ant-contrib.jar dynamically in Ant
In conclusion, it's a shame ivy is not packaged by default with ANT. If you discover your hosted service prevents you from copying files into the home directory, then perhaps the simplest thing to do is ship a copy of the ivy jar alongside your source (and enable it using a taskdef)
Update
Use the following taskdef for ant-contrib:
<taskdef uri="antlib:net.sf.antcontrib" classpathref="build.path"/>
The homepage needs update. At some stage in the recent past the library was repackaged as an antlib.

what is the best practice to create a .jar file from a java project?

what is the best practice to create a .jar file from a java project??
Some points to consider:
Create proper MANIFEST.MF, which should contain:
Build date;
Author;
Implementation-version;
Use a script/program - like an Ant task - which takes care of properly creating a manifest file.
Here's a simple ant file which builds a java project, adapted from the Ant tutorial:
<project>
<target name="clean">
<delete dir="build"/>
</target>
<target name="compile">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>
</target>
<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
<manifest>
<attribute name="Implementation-Version" value="1.0"/>
</manifest>
</jar>
</target>
<target name="run">
<java jar="build/jar/HelloWorld.jar" fork="true"/>
</target>
</project>
Read up on the basics of Sun's JAR format at this tutorial. In my opinion you should learn the basics -- namely MANIFESTs, the SDK tools -- before jumping into third party tools such as the following.
The Jar command line tool distributed with the Sun JDK:
jar -cf myjar.jar base_src_folder
Where base_src_folder is the parent directory holding your source code.
Alternatively you could use a build tool such as Apache Ant. It has features such as the JAR task to do this for you.
Apache Maven, for projects which are dependent on other projects.
Admittedly, Maven may be overkill for learning projects, but it is invaluable for larger, distributed ones.
Eclipse IDE is the best way for new comers. Just select the project right click export File, select jar anf filename.
Apache Ant
Ant is not quite easy to begin with. Instead, I would suggest using an IDE, for instance NetBeans, which creates an Ant script under the hood. All you have to do is to hit "build", and you get a .jar file as result.

How to create war files

What are the best practices of creating war files (using eclipse) to run on tomcat? tutorials, links, examples are highly appreciated.
You can use Ant to set up, compile, WAR, and deploy your solution.
<target name="default" depends="setup,compile,buildwar,deploy"></target>
You can then execute one click in Eclipse to run that Ant target. Here are examples of each of the steps:
Preconditions
We'll assume that you have your code organized like:
${basedir}/src: Java files, properties, XML config files
${basedir}/web: Your JSP files
${basedir}/web/lib: Any JARs required at runtime
${basedir}/web/META-INF: Your manifest
${basedir}/web/WEB-INF: Your web.xml files
Set up
Define a setup task that creates the distribution directory and copies any artifacts that need to be WARred directly:
<target name="setup">
<mkdir dir="dist" />
<echo>Copying web into dist</echo>
<copydir dest="dist/web" src="web" />
<copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" />
</target>
Compile
Build your Java files into classes and copy over any non-Java artifacts that reside under src but need to be available at runtime (e.g. properties, XML files, etc.):
<target name="compile">
<delete dir="${dist.dir}/web/WEB-INF/classes" />
<mkdir dir="${dist.dir}/web/WEB-INF/classes" />
<javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src">
<classpath>
<fileset dir="${basedir}/../web/WEB-INF/lib">
<include name="*" />
</fileset>
</classpath>
</javac>
<copy todir="${dist.dir}/web/WEB-INF/classes">
<fileset dir="src">
<include name="**/*.properties" />
<include name="**/*.xml" />
</fileset>
</copy>
</target>
Build WAR
Create the WAR itself:
<target name="buildwar">
<war basedir="${basedir}/dist/web" destfile="My.war"
webxml="${basedir}/dist/web/WEB-INF/web.xml">
<exclude name="WEB-INF/**" />
<webinf dir="${basedir}/dist/web/WEB-INF/">
<include name="**/*.jar" />
</webinf>
</war>
</target>
Deploy
Finally, you can set up a task to deploy the WAR directly into your Tomcat deploy location:
<target name="deploy">
<copy file="My.war" todir="${tomcat.deploydir}" />
</target>
Click and go!
Once all this is set up, simply launching the default target from Eclipse will compile, WAR, and deploy your solution.
The advantage of this approach is that it will work outside Eclipse as well as within Eclipse and can be used to easily share your deployment strategy (e.g. via source control) with other developers who are also working on your project.
I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.
We use Maven (Ant's big brother) for all our java projects, and it has a very nifty WAR plugin. Tutorials and usage can be found there.
It's a lot easier than Ant, fully compatible with Eclipse (use maven eclipse:eclipse to create Eclipse projects) and easy to configure.
Maven's homepage
Maven WAR plugin
Sample Configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
<configuration>
<outputDirectory>${project.build.directory}/tmp/</outputDirectory>
<workDirectory>${project.build.directory}/tmp/war/work</workDirectory>
<webappDirectory>${project.build.webappDirectory}</webappDirectory>
<cacheFile>${project.build.directory}/tmp/war/work/webapp-cache.xml</cacheFile>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>pdf</nonFilteredFileExtension>
<nonFilteredFileExtension>png</nonFilteredFileExtension>
<nonFilteredFileExtension>gif</nonFilteredFileExtension>
<nonFilteredFileExtension>jsp</nonFilteredFileExtension>
</nonFilteredFileExtensions>
<webResources>
<resource>
<directory>src/main/webapp/</directory>
<targetPath>WEB-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</webResources>
<warName>Application</warName>
</configuration>
</plugin>
A war file is simply a jar file with a war extension, but what makes it work is how the contents is actually structured.
The J2EE/Java EE tutorial can be a start:
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/WebComponents3.html
And the Servlet specification contains the gory details:
http://java.sun.com/products/servlet/download.html
If you create a new web project in Eclipse (I am referring to the Java EE version), the structure is created for you and you can also tell it where your Appserver is installed and it will deploy and start the application for you.
Using the "Export->WAR file" option will let you save the war file.
If you are not sure what to do and are starting from scratch then Maven can help get you started.
By following the the below steps you can get a new war project setup perfectly in eclipse.
Download and install Maven
Go the command line run: mvn archetype:generate
Follow the prompted steps - choosing the simple java web project (18) and a suitable name.
When it is finished run: mvn eclipse:eclipse
Start Eclipse. Choose File -> Import -> Existing project. Select the directory where you ran the mvn goals.
That's it you should now have a very good start to a war project in eclipse
You can create the war itself by running mvn package or deploy it by setting up a server in eclipse and simply adding adding the project to the server.
As some others have said the downside of using maven is that you have to use the maven conventions. But I think if you are just starting out, learning the conventions is a good idea before you start making your own. There's nothing to stop you changing/refactoring to your own preferred method at a later point.
Hope this helps.
Use the following command outside the WEB-INF folder. This should create your war file and is the quickest method I know.
(You will need JDK 1.7+ installed and environment variables that point to the bin directory of your JDK.)
jar -cvf projectname.war *
Reference Link
Use the Ant war task
Use ant build code
I use this for my project SMS
<property name="WEB-INF" value="${basedir}/WebRoot/WEB-INF" />
<property name="OUT" value="${basedir}/out" />
<property name="WAR_FILE_NAME" value="mywebapplication.war" />
<property name="TEMP" value="${basedir}/temp" />
<target name="help">
<echo>
--------------------------------------------------
compile - Compile
archive - Generate WAR file
--------------------------------------------------
</echo>
</target>
<target name="init">
<delete dir="${WEB-INF}/classes" />
<mkdir dir="${WEB-INF}/classes" />
</target>
<target name="compile" depends="init">
<javac srcdir="${basedir}/src"
destdir="${WEB-INF}/classes"
classpathref="libs">
</javac>
</target>
<target name="archive" depends="compile">
<delete dir="${OUT}" />
<mkdir dir="${OUT}" />
<delete dir="${TEMP}" />
<mkdir dir="${TEMP}" />
<copy todir="${TEMP}" >
<fileset dir="${basedir}/WebRoot">
</fileset>
</copy>
<move file="${TEMP}/log4j.properties"
todir="${TEMP}/WEB-INF/classes" />
<war destfile="${OUT}/${WAR_FILE_NAME}"
basedir="${TEMP}"
compress="true"
webxml="${TEMP}/WEB-INF/web.xml" />
<delete dir="${TEMP}" />
</target>
<path id="libs">
<fileset includes="*.jar" dir="${WEB-INF}/lib" />
</path>
Another option would be to build it automatically using Eclipse. Of course if you have continuous integration environment Ant or Maven is recommended. The export alternative is not very convenient because you have to configure every time the export properties.
STEPS:
Enable "Project Archives" support; this might depend on your project (I used it on Java EE/Web project). Right-click project root directory; Configure -> Add Project Archives Support.
Go and create a new archive in the "Project Archives" top dir. You have only jar option, but name you archive *.war.
Configure Fileset-s, i.e what files to be included. Typical is to configure two filesets similar how the Web Deployment Assembly (project property) is configured.
copy /WebContent to /
copy /build/classes to WEB-INF/classes (create this fileset after you define the WEB-INF/classes directory in the archive)
You might need to tweek the fileset exclude property depending where you placed some of the config files or you might need more filesets, but the idea is that once you configured this you don't need to change it.
Build the archive manually or publish directly to server; but is also automatically built for you by Eclipse
Another common option is gradle.
http://www.gradle.org/docs/current/userguide/application_plugin.html
To build your war file in a web app:
In build.gradle, add:
apply plugin: 'war'
Then:
./gradlew war
Use the layout from accepted answer above.
Simpler solution which also refreshes the Eclipse workspace:
<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="default">
<target name="default">
<war destfile="target/MyApplication.war" webxml="web/WEB-INF/web.xml">
<fileset dir="src/main/java" />
<fileset dir="web/WEB-INF/views" />
<lib dir="web/WEB-INF/lib"/>
<classes dir="target/classes" />
</war>
<eclipse.refreshLocal resource="MyApplication/target" depth="infinite"/>
</target>
</project>
Simplistic Shell code for creating WAR files from a standard Eclipse dynamic Web Project. Uses RAM File system (/dev/shm) on a Linux platform.
#!/bin/sh
UTILITY=$(basename $0)
if [ -z "$1" ] ; then
echo "usage: $UTILITY [-s] <web-app-directory>..."
echo " -s ..... With source"
exit 1
fi
if [ "$1" == "-s" ] ; then
WITH_SOURCE=1
shift
fi
while [ ! -z "$1" ] ; do
WEB_APP_DIR=$1
shift
if [ ! -d $WEB_APP_DIR ] ; then
echo "\"$WEB_APP_DIR\" is not a directory"
continue
fi
if [ ! -d $WEB_APP_DIR/WebContent ] ; then
echo "\"$WEB_APP_DIR\" is not a Web Application directory"
continue
fi
TMP_DIR=/dev/shm/${WEB_APP_DIR}.$$.tmp
WAR_FILE=/dev/shm/${WEB_APP_DIR}.war
mkdir $TMP_DIR
pushd $WEB_APP_DIR > /dev/null
cp -r WebContent/* $TMP_DIR
cp -r build/* $TMP_DIR/WEB-INF
[ ! -z "$WITH_SOURCE" ] && cp -r src/* $TMP_DIR/WEB-INF/classes
cd $TMP_DIR > /dev/null
[ -e $WAR_FILE ] && rm -f $WAR_FILE
jar cf $WAR_FILE .
ls -lsF $WAR_FILE
popd > /dev/null
rm -rf $TMP_DIR
done
**Making War file in Eclips Gaynemed of grails web project **
1.Import project:
2.Change the datasource.groovy file
Like this: url="jdbc:postgresql://18.247.120.101:8432/PGMS"
2.chnge AppConfig.xml
3.kill the Java from Task Manager:
run clean comand in eclips
run 'prod war' fowllowed by project name.
Check the log file and find the same .war file in directory of workbench with same date.

Categories