Build project into a JAR automatically in Eclipse - java

I have an Eclipse project where I want to keep my Java project built into a JAR automatically. I know I have an option to export the project into a JAR; if I do a right click; but what I am really looking for is, that like Eclipse automatically builds a project's .class files and put them in target folder; it should also build a JAR automatically and copy the latest JAR at some or a specific location.
Is there a option to configure Eclipse in such a way, to build JARs automatically?
Just to make it clear for guys, patient enough to answer my question; I am not looking at ANT as solution; as I already use it, but what I would like it something that gets initiated automatically either with a time based trigger or immediate build with change.

You want a .jardesc file. They do not kick off automatically, but it's within 2 clicks.
Right click on your project
Choose Export > Java > JAR file
Choose included files and name output JAR, then click Next
Check "Save the description of this JAR in the workspace" and choose a name for the new .jardesc file
Now, all you have to do is right click on your .jardesc file and choose Create JAR and it will export it in the same spot.

Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.
Step 1
Create a build.xml file and add to package explorer:
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="." includes="*.class" />
</target>
</project>
Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml.
Step 2
Right-click on the root node in the project.
- Select Properties
- Select Builders
- Select New
- Select Ant Build
- In the Main tab, complete the path to the build.xml file in the bin folder.
Check the Output
The Eclipse output window (named Console) should show the following after a build:
Buildfile: /home/<user>/src/Test/build.xml
CreateJar:
[jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds
EDIT: Some helpful comments by #yeoman and #betlista
#yeoman I think the correct include would be /.class, not *.class, as most
people use packages and thus recursive search for class files makes
more sense than flat inclusion
#betlista I would recomment to not to have build.xml in src folder

Check out Apache Ant
It's possible to use Ant for automatic builds with eclipse, here's how

This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.

Regarding to Peter's answer and Micheal's addition to it you may find How Do I Automatically Generate A .jar File In An Eclipse Java Project useful. Because even you have "*.jardesc" file on your project you have to run it manually. It may cools down your "eclipse click hassle" a bit.

Using Thomas Bratt's answer above, just make sure your build.xml is configured properly :
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="bin/" includes="**/*.class" />
</target>
</project>
(Notice the double asterisk - it will tell build to look for .class files in all sub-directories.)

Creating a builder launcher is an issue since 2 projects cannot have the same external tool build name. Each name has to be unique. I am currently facing this issue to automate my build and copy the JAR to an external location.
I am using IBM's Zip Builder, but that is just a help but not doing the real.
People can try using IBM ZIP Creation plugin.
http://www.ibm.com/developerworks/websphere/library/techarticles/0112_deboer/deboer2.html#download

Related

Eclipse automation with ant

In Eclipse (Neon) a runnable .jar can be created via File > Export > Runnable jar > Next and interacting with the dialog that appears. I wanted to eliminate those steps. I automated the export of my .jar file by creating the following ant file which is called makeJar.xml and resides in the project directory.
<project name="makeJar" default="makeJarTarget" basedir=".">
<property name="jar" value="../export/ohana1/ohana1.jar"/>
<target name="makeJarTarget">
<jar destfile="${jar}" basedir="bin"/>
</target>
<target name="cleanTarget">
<delete file="${jar}"/>
</target>
</project>
This ant file is visible in the Project > Properties > Builders dialog. At the top of the list of builders is the default builder called Java Builder and next in the list is this additional builder which is the aforementioned ant file and it appears as makeJar.
Assume that at this point an edit to the Java source code happens. The first step of saving any code changes will cause .class files to be updated. The next step of clicking Build All will update the .jar file.
It would be more ideal if saving any code changes (without having to click Build All) had that same effect. Unfortunately it does not. Saving code changes results in only .class files being updated; the .jar will be unchanged (out-of-date).
It is possible to reason why this is the case. In the Eclipse Project menu, Build All is a choice that is distinct from Build Automatically. So if code changes are saved and Build Automatically was previously set (this menu item can "remember" a check mark setting) the .class files are updated but nothing more than that. There is no menu item to perform something like Build All Automatically. Is there any way to further automate so that saving code changes is sufficient to generate not only .class files but also the .jar?
EDIT: Caution: "Build All" has the effect of building all projects that are open. Before clicking "Build All" you might want to close any projects that you are merely browsing.
In the Navigator view double-click the file .project to open it and remove the line:
<triggers>full,incremental,</triggers>
After the Builder configuration is edited, this has to be done again.

Failed Ant build - The libs.CopyLibs.classpath property is not set up

I am trying to create a .war file from a svn source code that appears to be built using NetBeans.
I am aware of the question The libs.CopyLibs.classpath property is not set up
However, I would like to provide further details about my setup and the answers in the other question don't resolve my issue.
I am using Eclipse Luna & Ant version apache-ant-1.9.4. Could someone please enlightenment me whether I actually need the file and if so why? I downloaded the missing jar and the title of the jar is "org-netbeans-modules-java-j2seproject-copylibstask.jar" which suggests to me that this jar is IDE-specific. Just making an assumption here.
Here's my error message that I receive in a command prompt on running "ant" command.
BUILD FAILED
C:\eclipse_workspace\MyProject\xyz\project\build-impl.xml:476:
The libs.CopyLibs.classpath property is not This property must point to org-netbeans-modules-java-j2seproject-copylibstask.jar file which is part
of NetBeans IDE installation and is usually located at /java/ant/extra folder.
Either open the project in the IDE and make sure CopyLibs library
exists or setup the property manually. For example like this:
ant -Dlibs.CopyLibs.classpath=a/path/to/org-netbeans-modules-java-j2seproject-copylibstask.jar
I can see that message is coming from my "build-impl.xml" file. But I don't really understand the purpose of the file and how to resolve this issue since I don't even have Netbeans installed on my machine.
<target name="-init-taskdefs">
<fail unless="libs.CopyLibs.classpath">
The libs.CopyLibs.classpath property is not set up.
This property must point to org-netbeans-modules-java-j2seproject-copylibstask.jar
file which is part of NetBeans IDE installation and is usually located at
<netbeans_installation>/java<version>/ant/extra folder.
Either open the project in the IDE and make sure CopyLibs library exists or setup the
property manually. For example like this:
ant -Dlibs.CopyLibs.classpath=a/path/to/org-netbeans-modules-java-j2seproject-copylibstask.jar
</fail>
<taskdef classpath="${libs.CopyLibs.classpath}"
resource="org/netbeans/modules/java/j2seproject/copylibstask/antlib.xml"/>
</target>
I have managed to find a working solution for my situation.
1) Downloaded and added the org-netbeans-modules-java-j2seproject-copylibstask.jar to my Ant/lib directory: C:/apache-ant-1.9.4/lib/
2) (in command line) Navigated to the folder containing my "build.xml" file, so it would be "abcfolder"
C:\eclipse_workspace\myproject\abcfolder\build.xml
3) Ran the following commmand
ant -Dlibs.CopyLibs.classpath=C:/apache-ant-1.9.4/lib/org-netbeans-modules-java-j2seproject-copylibstask.jar
I got a successful build.
simply only a call of the netbeans frequently updates (Help --> Check for Updates) solved this problem on my PC (using NetBeans 8.0.2)
checked for updates in netbeans(Help --> Check for Updates) and the problem got solved. This solved my problem......
Earlier i was thinking to re-install netbeans, but being a lenghty process I decided to search for the solution and luckily found the solution.
Guys every prob has a solution, try to get the solution in your way.....
Using NetBeans, You can resolve this problem using these steps:
In NetBeans, select Tools > Options > Miscellaneous > Ant.
In the Properties section, add the following property:
libs.CopyLibs.classpath=/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar
/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar
must be your org-netbeans-modules-java-j2seproject-copylibstask.jar file path
I updated the build.xml file and it worked
<target name="-init-taskdefs">
<property name="libs.CopyLibs.classpath" value="(path of netbeans
folder)/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar"/>
<fail unless="libs.CopyLibs.classpath">
thank you, for referring this
If you get "
Could not load definitions from resource
org/netbeans/modules/java/j2seproject/copylibstask/antlib.xml. It
could not be found.
" this error after setting Tools > Options > Miscellaneous > Ant in the Properties , adding property-
libs.CopyLibs.classpath=/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar
Then add jar in the upper field "Classpath" add this "org-netbeans-modules-java-j2seproject-copylibstask.jar" jar located in your netbeans installation location inside "NetBeans 8.0.2\extide\ant\extra".
For the main answer the setting in Netbeans. You may find is in Tools > Options > Java > Ant
And it may be easier to click Add Directory next to the Classpath window and navigate to the ...\java\ant\extra to add that whole folder.

Launch4J - how to attach dependent jars to generated exe

I have a simple java project, which requires external jars.
I build this with netbeans and after Clean and Build command, I can find in dist directory the following structure:
-myApp.jar
-lib/
library1.jar
library2.jar
typical, I would say.
Now, I'd like to distribute myApp.jar with dependent libraries as one exe.
Is this possible? I am trying to use Launch4J. In the GUI I create the config file, there are some options in cp section
<cp>lib/swing-layout-1.0.4.jar</cp>
but it seems to be classpath, and it is the only place I can refer to my extra jars.
After exe file is created, I can't find dependend libs in the exe (exe can be opened with winrar) and thus my application crashes.
How can I make the exe file properly then?
Thanks for your help.
As it often happens being unable to solve the problem I published it on StackOverflow ... and pretty soon after publishing the question I got an idea.
So the answer to my question is:
Put all the dependent jars into one main jar.
It took me some time to find info how can I do that.
To help people I decided to publish detailed instruction here - they are based on Netbeans 7.4.
Following article from http://mavistechchannel.wordpress.com/2010/08/17/how-to-build-a-single-jar-file-with-external-libs/ I created the ant script that build one-jar-app for me.
I could then manually create exe via Launch4J
I then decided that I want more automated task, and I did that, Ant builds exe for me (via Launch4J)
Then I realized that I must do "clean and build" before my automated task (in point 2)/ I decided that I want clean and build to be done automatically before the exe build
Putting all together I am attaching my ant build script consisting of points 1,2,3:
It is required to edit build.xml and put the content found below before "project" end tag
<target name="package-for-launch4j" depends="clean,compile,jar">
<property name="launch4jexe.dir" location="C:\Program Files (x86)\Launch4j" />
<taskdef name="launch4j"
classname="net.sf.launch4j.ant.Launch4jTask"
classpath="${launch4jexe.dir}/launch4j.jar
:${launch4jexe.dir}/lib/xstream.jar" />
<property name="launch4j.jar.name" value="MyAppJarName"/>
<property name="launch4j.dir" value="exe"/>
<property name="launch4j.jar" value="${launch4j.dir}/${launch4j.jar.name}.jar"/>
<echo message="Packaging ${application.title} into a single JAR at ${launch4j.jar}"/>
<delete dir="${launch4j.dir}"/>
<mkdir dir="${launch4j.dir}"/>
<jar destfile="${launch4j.dir}/temp_final.jar" filesetmanifest="skip">
<zipgroupfileset dir="dist" includes="*.jar"/>
<zipgroupfileset dir="dist/lib" includes="*.jar"/>
<manifest>
<attribute name="Main-Class" value="${main.class}"/>
</manifest>
</jar>
<zip destfile="${launch4j.jar}">
<zipfileset src="${launch4j.dir}/temp_final.jar"
excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA"/>
</zip>
<delete file="${launch4j.dir}/temp_final.jar"/>
<launch4j configFile="misc/l4j-myapp.xml" />
</target>
then in Netbeans rightclick on the build.xml and choose:
Run Target / Other Targets / package-for-launch4j
exe file is ready in exe folder :-)
When you are converting your .jar file
Go to classpath tab
Check custom classpath
On main class select your .jar from your dist folder after building the project
On the classpath textarea add your libraries, you add them right below that
textarea writting the full path to the lib (of course including the
lib, ie "C:\folder\lib\file.jar")
I have spent hours on this issue. So here is my contribution.
The problem here: how to sucessfully put your external jars that your .JAR program needs INSIDE the .exe that you generate.
We assume that you already, and correctly, configured the external jars on eclipse/netbeans and ALL WORK FINE with the command: java -jar yourprogram.jar.
So the real problem is how to ensure that this .EXE file will contain the external jars, otherwise it will not work properly.
1) First of all, you need to forget Launch4J and anyother program.
2) Install JSmooth, I recommend that you use the windows version.
3) On the left menu there is a button "Application". Click on it.
4) You will see a tab "Classpath" panel. Click on the plus (+) and add your external .jar's files. And that is it!!
Don't forget to put your .jar application marking checkbox "use am embedded jar" and choose the main class properly. It will work.
I also faced the same issue while migrating my .jar to exe. I also had many dependent libraries as well. So These were the steps I performed :
Download and Install launch4j.
Open your project in netbeans. Clean and build the project.
Make sure you have a folder named 'dist' in the project directory. It will have your jar files with lib folder(containing the dependent libraries).
Open launch 4j.
Create output file in the dist folder. For example : OutputFile : D:******\My_App\dist\my_application.exe
Browse your jar file in the next row. For example : Jar : D:******\My_App\dist\my_application.jar
Go to classpath tab. Tick CustomClasspath. Press browse icon, and browse to your jar file which is located in the dist folder.
Specify Min Jre version in the JRE tab.
Save the configration.
Build the wrapper(by clicking the settings icon)
Your exe file will be generated in the dist folder.
Thats it :)
Putting different links of places which had helped me
How to include all dependent Jars within a single non-executable jar?
How can I create an executable JAR with dependencies using Maven?
http://www.mkyong.com/java/how-to-make-an-executable-jar-file/
and most importantly
http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
quick tut
http://www.mkyong.com/java/how-to-add-your-manifest-into-a-jar-file/
To include external libraries with Launch4j you have to have the ".jar" files of the external libraries near your .exe (mine are just in the same folder) then in "Classpath" you put in the path to the .jar files into "Edit Item: "
In launch4j go to the classpath tab. Tick the custom classpath field. In the edit field, enter the full path of each jar you want included and press accept. When finished type just the name of the main class into the separate field (ie MyProg). All the jars will now be included in the exe.
PS I have all the jars in the same directory. I'm using version 3.12

Create automatically JAR with ANT and Eclipse

I want to make the file build automatically using Eclipse. I need this file creates the JAR of the application. And if it were possible, I would like to insert the command to pass some test of JUnit. How can I do all of this automatically?
Generally to create jar files in Eclipse I do this things:
create an ant file with the necessary code to create the jar file I need
configure the ant file to be processed when something change in my project files: and to do this I open the project properties, I choose Builders, "New..." and I add a Ant builder that use my ant file
In the ant files I put for example something similar:
<project name="My Project" default="createjar">
<property name="projectHome" location="." />
<target name="createjar">
<jar destfile="${projectHome}/file.jar" basedir="${projectHome}/bin" />
</target>
</project>
You can add other instructions to the ant file and process whatever you need after the jar creation. But my suggestion is to not launch JUnit test on very file change, can be very ugly.

How best to store Subversion version information in EAR's?

When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question.
I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look in/at the JAR and switch to the same branch, version or tag that was the source of the released JAR.
How can I best adjust the ant build process so that the version information in the svn checkout remains in the created build?
I was thinking along the lines of:
adding a VERSION file, but with what content?
storing information in the META-INF file, but under what property with which content?
copying sources into the result archive
added svn:properties to all sources with keywords in places the compiler leaves them be
I ended up using the svnversion approach (the accepted anwser), because it scans the entire subtree as opposed to svn info which just looks at the current file / directory. For this I defined the SVN task in the ant file to make it more portable.
<taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask">
<classpath>
<pathelement location="${dir.lib}/ant/svnant.jar"/>
<pathelement location="${dir.lib}/ant/svnClientAdapter.jar"/>
<pathelement location="${dir.lib}/ant/svnkit.jar"/>
<pathelement location="${dir.lib}/ant/svnjavahl.jar"/>
</classpath>
</taskdef>
Not all builds result in webservices. The ear file before deployment must remain the same name because of updating in the application server. Making the file executable is still an option, but until then I just include a version information file.
<target name="version">
<svn><wcVersion path="${dir.source}"/></svn>
<echo file="${dir.build}/VERSION">${revision.range}</echo>
</target>
Refs:
svnrevision: http://svnbook.red-bean.com/en/1.1/re57.html
svn info http://svnbook.red-bean.com/en/1.1/re13.html
subclipse svn task: http://subclipse.tigris.org/svnant/svn.html
svn client: http://svnkit.com/
Use the svnversion command in your Ant script to get the revision number:
<exec executable="svnversion" outputproperty="svnversion" failonerror="true">
<env key="path" value="/usr/bin"/>
<arg value="--no-newline" />
</exec>
Then use the ${svnversion} property somewhere in your EAR. We put it in the EAR file name, but you could also put it in a readme or version file inside the EAR, or specify the version in the EAR's META-INF/manifest.mf:
<!-- myapp-r1234.ear -->
<property name="ear" value="myapp-r${svnrevision}.ear" />
You'd want to provide the Subversion branch and repository number. As discussed in How to access the current Subversion build number?, the svn info command will give you this information, which you can then use to build a VERSION file or place in any of the other files that you're building into your *AR files. If you've nothing else in mind, you could consider using the XmlProperty Ant task to extract the relevant information from the output of your
svn info --xml command
Check out the jreleaseinfo project. Contains a ANT task that can generate a java class that can be called at runtime to display the release info for your project.
I like its simplicity.
See also this question: Build and Version Numbering for Java Projects (ant, cvs, hudson)
It includes several helpful code snippets.
From the top of my mind. A tag for each jar build?
We have the first part of our build create a version.txt file in the root of the package and dump the tag used to check the code out from (in our case) CVS... Additionally, the final part of our build process checks the fully built EAR back into CVS for future reference.
That way, if we have an issue with a webapp - it's just a case of asking the reporter to hit /app/version.txt - from there we can drill down the particular build history in CVS to locate the relevant components (handles different versions of libraries in apps) to locate the error.
Not sure how much help this is to our support folk - but it's definitely something they complain about not being there!
Do automatic builds, and place a tag (with a date stamp) on the codebase when the build is succesful (with unittest ofcourse).
In your delivery process, only deliver tagged builds to the customer. This way you are in control, and can place the tag name in a readme.txt somewhere, or have the filename of the ear file reflect the tagname.
I personally switched back to CVS, and this is one of the reasons. In CVS, I can have a class report it's tag. All my jar files contain a "main" which makes them runnable. With support questions, I ask the customer to do a "java -jar somejar.jar" and send the output to me alongside the question.
This way I'm sure of the build they-re using, and I can even have information like java version, OS type and version. Without the customer having to answer strange questions.
It's simple but very effective.
Why not put the build number into a properties file... this can then be easily read by the java and output to a Help | About dialog (applet/application), web-page footer or whatever other GUI you might have.
(See the footer on every SOF page.... has the SVN version number there.)
Seems a load easier than looking in the WAR/EAR/JAR etc easy time?
I store the absolute repository revision as a part of my full version number. This gives people a quick glance to see if a given change is in a given version or not.
We also store the version number / build date / etc in the manifest file of the ear as custom properties, these are mostly informational only. We also store it in a properties file that is built into our jar, so the application can read it.

Categories