How to use FatJar (out of Eclipse) in continuous integration server? - java

From what I understood, FatJar is an Eclipse plugin which is based on the OSGi framework. I believe this makes it hard to use outside of an OSGi platform. Also, looking at decompiled FatJar, it seems to be requiring lots of OSGi and Eclipse classes, like org.eclipse.jdt.core.IJavaProject and org.osgi.framework.BundleContext, for example.
So, in front of all this, I'm wondering if there is any way to use our precious *.fatjar files with Hudson (using a script or whatever).
Any good advice is welcome!
Thanks!

After more work and research, it seems that, even though FatJar is primarily an Eclipse plugin, it is possible to integrate it quite easily in continuous integration servers.
In my case, using Ant, I have found that it was possible to run the FatJar plugin outside of Eclipse using the following code (originally from this site).
<project name="FatJar MySuperDuperClass.jar (experimental)" default="main" basedir=".">
<!-- this file was created by Fat-Jar Eclipse Plug-in -->
<!-- the ANT-Export is in a very early stage, so this -->
<!-- is only experimental, ANT 1.6 or above is -->
<!-- required, feedback is always welcome: -->
<!-- http://sourceforge.net/projects/fjep -->
<!-- uncomment the following lines if using ANT outside Eclipse -->
<!--
<property name="fjepPath" value="plugins/net.sf.fjep.fatjar_0.0.31/fatjar.jar"/>
<taskdef name="fatjar.build" classname="net.sf.fjep.anttask.FJBuildTask" classpath="${fjepPath}"/>
<typedef name="fatjar.manifest" classname="net.sf.fjep.anttask.FJManifestType" classpath="${fjepPath}"/>
<typedef name="fatjar.exclude" classname="net.sf.fjep.anttask.FJExcludeType" classpath="${fjepPath}"/>
<typedef name="fatjar.jarsource" classname="net.sf.fjep.anttask.FJJarSourceType" classpath="${fjepPath}"/>
<typedef name="fatjar.filesource" classname="net.sf.fjep.anttask.FJFileSourceType" classpath="${fjepPath}"/>
-->
<!-- uncomment the above lines to use ANT outside of Eclipse -->
<target name="main">
<fatjar.build output="MySuperDuperClass.jar">
<fatjar.manifest mainclass="de.schwobeseggl.test.MySuperDuperClass"/>
<fatjar.filesource path="bin" relpath=""/>
<fatjar.jarsource file="lib/commons-cli.jar" relpath=""/>
<fatjar.jarsource file="lib/jbossall-client.jar" relpath=""/>
<fatjar.jarsource file="lib/junit.jar" relpath=""/>
<fatjar.jarsource file="lib/log4j.jar" relpath=""/>
<fatjar.jarsource file="lib/jdom.jar" relpath=""/>
</fatjar.build>
</target>
</project>
I uncommented the block of 6 lines at the beginning and it's working good. Reading the comment on top, it seems this was exported using FatJar itself, but don't know how to do this. I just adjusted this sample to my use case.

FatJar is an Eclipse plugin providing one-jar functionality. Outside of Eclipse you just use one-jar directly.
http://one-jar.sourceforge.net/
Note, that the Eclipse complication process is not easy to script. I've done it in Ant using ant4eclipse and I would recommend against it. EDIT: As of 2015 you should look into Maven projects instead of plain Eclipse.

My advice would be to look for an alternative to FatJar that works with your build tool.
If you are using Maven, take a look at the shade plugin.
For Ant, you can do the job with the appropriate sequence of unjaring, copying and jaring tasks.

Yes, it's possible to use it out of eclipse. Try a configuration similar to the following one:
<property name="java.source" value="1.7" />
<property name="java.target" value="1.7" />
<property name="src.dir" location="src" />
<property name="libraries.dir" location="lib" />
<property name="dist.dir" location="out" />
<property name="build.classes.dir" location="${dist.dir}\classes" />
<property name="dist.jar" value="MyJAR.jar" />
<property name="fjepPath" value="${libraries.dir}\fatjar.jar" />
...
<typedef name="fatjar.manifest" classname="net.sf.fjep.anttask.FJManifestType"
classpath="${fjepPath}" loaderref="${fjepPath}" />
<typedef name="fatjar.exclude" classname="net.sf.fjep.anttask.FJExcludeType"
classpath="${fjepPath}" loaderref="${fjepPath}" />
<typedef name="fatjar.jarsource" classname="net.sf.fjep.anttask.FJJarSourceType"
classpath="${fjepPath}" loaderref="${fjepPath}" />
<typedef name="fatjar.filesource" classname="net.sf.fjep.anttask.FJFileSourceType"
classpath="${fjepPath}" loaderref="${fjepPath}" />
<taskdef name="fatjar.build" classname="net.sf.fjep.anttask.FJBuildTask"
classpath="${fjepPath}" loaderref="${fjepPath}" />
...
<target name="buildJar">
<echo>Building JAR</echo>
<fatjar.build output="${dist.dir}\${dist.jar}">
<fatjar.manifest mergemanifests="false" mainclass="com.company.app.Main" />
<fatjar.filesource path="${build.classes.dir}" />
<fatjar.jarsource file="${libraries.dir}\log4j-1.2.17.jar" />
<fatjar.jarsource file="${libraries.dir}\commons-httpclient-2.0.jar" />
...
</fatjar.build>
</target>

Related

sonar's code coverage using ANt (build.xml)

I am trying to use my junit test for sonar's code coverage. I am using Ant. I am trying to update build.xml like this:
<!-- ========= Define SonarQube Scanner for Ant Target ========= -->
<target name="sonar" depends="compile">
<taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml">
<!-- Update the following line, or put the "sonar-ant-task-*.jar" file in your "$HOME/.ant/lib" folder -->
<classpath path="/lib/sonar-ant-task-2.0.jar" />
</taskdef>
<!-- Execute SonarQube Scanner for Ant Analysis -->
<sonar:sonar />
</target>
But it is showing "resource="org/sonar/ant/antlib.xml" not found. I have sonar-ant-task-2.0.jar in my lib folder. and I am using intellij.
This . are the properties i added in build.xml
<property name="sonar.projectKey" value="org.codehaus.sonar:example-java-ant" />
<property name="sonar.projectName" value="SIML project" />
<property name="sonar.projectVersion" value="1.0" />
<property name="sonar.test" value="test" />
Please help :) :)
And let me know if you need any other information to make question clear. :)

How can I run an ant task as a prerequisite to <taskdef>?

I created my own ant task using the instructions here. In my ant script, I create the <taskdef> like this:
<!-- myUploader.xml -->
<taskdef name="fileUpload" classname="com.awt.client.UploaderTask" classpath="lib/fileUploader.jar" />
<target name="setup" description="some required setup before taskdef!">
<!-- checking for required jars, etc... -->
</target>
And then I can import the script that invokes this as an ant task:
<!-- build.xml -->
<import file="myUploader.xml" />
<fileUpload server="${server}" username="${username}" password="${password}" appname="TestApp" appversion="13" />
This all works fine. Now, there is a bit of setup I would like to happen in myUploader.xml before the taskdef occurs. <taskdef> does not like if, unless, or depends. How can I ensure that my setup task is called before <taskdef> is done?
One way is to move the taskdef inside the setup target:
<target name="setup" description="some required setup before taskdef!">
<!-- checking for required jars, etc... -->
<taskdef name="fileUpload" classname="com.awt.client.UploaderTask" classpath="lib/fileUploader.jar" />
</target>
Then in the main buildfile, after importing myUploader.xml, invoke the setup target which is now responsible for defining your custom task.
Or you can move the part of the setup target to outside (becoming a top-level section):
<project>
<!-- do required setup here -->
<taskdef name="fileUpload" classname="com.awt.client.UploaderTask" classpath="lib/fileUploader.jar" />
...

J2ME Polish - Unable to execute J2ME Polish task: java.lang.IllegalArgumentException: The property [dir.dist] is not defined in input [${dir.dist}]

I am trying to get a J2ME Polish sample project up and running, but am struggling.
I am using Netbeans 8.0.2 with the J2ME Polish plugin.
When I try to create a J2ME Polish project (File > New Project > Java ME > J2ME Polish Project), the New Project wizard works fine until I get to the last step, at which point clicking the Finish button does not do anything. I then have to close the wizard and open the project manually (which appears to have been created - although maybe not fully?).
Next, I fix the resource complaint by referencing enough-j2mepolish-client.jar after I have relocated it to root of my project.
I then try to clean and build the project, but I get this error in my Output window:
ant -f M:\\Netbeans\\J2ME-Polish-Project rebuild
clean:
Deleting directory M:\Netbeans\J2ME-Polish-Project\build
pre-init:
pre-load-properties:
exists.config.active:
exists.netbeans.user:
exists.user.properties.file:
load-properties:
exists.platform.active:
exists.platform.configuration:
exists.platform.profile:
basic-init:
cldc-pre-init:
cldc-init:
cdc-init:
semc-pre-init:
semc-init:
savaje-pre-init:
savaje-init:
sjmc-pre-init:
sjmc-init:
ojec-pre-init:
ojec-init:
cdc-hi-pre-init:
cdc-hi-init:
nokiaS80-pre-init:
nokiaS80-init:
post-init:
init:
j2mepolish-init:
j2mepolish:
J2ME Polish 2.4 (2013-08-27) (GPL License)
Loading device database...
Processing [7] devices...
building application for [Generic/jtwi] (1/7):
using locale [de_DE]...
java.lang.IllegalArgumentException: The property [dir.dist] is not defined in input [${dir.dist}]
at de.enough.polish.Environment.getProperty(Environment.java:537)
at de.enough.polish.Environment.writeProperties(Environment.java:452)
at de.enough.polish.ant.build.BuildSetting.getDestDir(BuildSetting.java:621)
at de.enough.polish.ant.PolishTask.initialize(PolishTask.java:1613)
at de.enough.polish.ant.PolishTask.execute(PolishTask.java:600)
at de.enough.polish.ant.PolishTask.execute(PolishTask.java:436)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
at sun.reflect.GeneratedMethodAccessor150.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:435)
at org.apache.tools.ant.Target.performTasks(Target.java:456)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:286)
at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:555)
at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
M:\Netbeans\J2ME-Polish-Project\build.xml:82: Unable to execute J2ME Polish task:
java.lang.IllegalArgumentException: The property [dir.dist] is not defined in input [${dir.dist}]
at de.enough.polish.Environment.getProperty(Environment.java:537)
at de.enough.polish.Environment.writeProperties(Environment.java:452)
at de.enough.polish.ant.build.BuildSetting.getDestDir(BuildSetting.java:621)
at de.enough.polish.ant.PolishTask.initialize(PolishTask.java:1613)
at de.enough.polish.ant.PolishTask.execute(PolishTask.java:600)
at de.enough.polish.ant.PolishTask.execute(PolishTask.java:436)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
at sun.reflect.GeneratedMethodAccessor150.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:435)
at org.apache.tools.ant.Target.performTasks(Target.java:456)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:286)
at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:555)
at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
BUILD FAILED (total time: 1 second)
As well as J2ME Polish, I'm also brand new to Ant, so maybe this could be a simple one to solve (although I haven't managed after 1 hour...).
For completeness, here is my build.xml file:
<!-- When you are using NetBeans 5, just rename this file -->
<!-- to build.xml. You can then use the normal menu items -->
<!-- run, debug, build and so forth from within NetBeans. -->
<!-- This file controls the build process. -->
<!-- The most important target is the "j2mepolish", -->
<!-- which controls for what devices the application should -->
<!-- be created and so on. -->
<!-- -->
<!-- Call the "emulator" target to skip the obfuscation -->
<!-- and to build the example for only one handsets. -->
<!-- The default target builds and obfuscates the example. -->
<!-- -->
<!-- The full documentation can be found at -->
<!-- http://www.j2mepolish.org -->
<!-- -->
<!-- Have fun! -->
<project
name="J2ME-Polish-Project"
default="j2mepolish">
<!-- extend the default NetBeans build script: -->
<import file="nbproject/build-impl.xml"/>
<!-- The polish.home property needs to point to the directory -->
<!-- containing the J2ME Polish installation. -->
<property name="polish.home" location="P:\Program Files\J2ME-Polish" />
<!-- import global properties -->
<property file="${polish.home}/global.properties" />
<!-- Definition of the J2ME Polish task: -->
<taskdef name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="${polish.home}/lib/enough-j2mepolish-build.jar"
/>
<!-- build targets, each target can be called via "ant [name]",
e.g. "ant clean", "ant test j2mepolish" or just "ant" for calling the default-target -->
<target name="setdeploy"
description="Call this target first to set the OTA download-URL, e.g. ant setdeploy j2mepolish"
>
<property name="deploy-url" value="http://www.company.com/download/" />
</target>
<target name="enableDebug"
description="Call this target first to skip the obfuscation step, call the emulator and start the debugger, e.g. ant enableDebug j2mepolish"
>
<property name="debug" value="true" />
</target>
<target name="test"
description="Call this target first to skip the obfuscation step and call the emulator, e.g. ant test j2mepolish"
>
<property name="test" value="true" />
<property name="dir.work" value="build/test" />
</target>
<target name="j2mepolish-init"
depends="init"
>
<property name="test" value="false" />
<property name="dir.work" value="build/real" />
<property name="deploy-url" value="" />
</target>
<!-- In this target the J2ME Polish task is used. -->
<!-- It has 3 sections: -->
<!-- 1. The info-section defines some general information -->
<!-- 2. The deviceRequirements-section chooses the devices -->
<!-- for which the application is optimized. -->
<!-- 3. The build-section controls the actual build -->
<!-- process. -->
<target name="j2mepolish"
depends="j2mepolish-init"
description="This is the controller for the J2ME build process."
>
<j2mepolish>
<!-- general settings, these settings basically form the JAD-attributes. -->
<!-- Have a look at the <jad>-section for setting specialised attributes.
You can also define localized attributes in the resources/messages.txt files -->
<info
name="J2ME Polish"
version="1.3.4"
description="A simple project that uses localization."
vendorName="Enough Software"
infoUrl="http://www.j2mepolish.org"
icon="dot.png"
jarName="${polish.vendor}-${polish.name}-${polish.locale}-menu.jar"
jarUrl="${deploy-url}${polish.jarName}"
copyright="Copyright 2005 - 2011 Enough Software. All rights reserved."
deleteConfirm="Do you really want to kill me?"
/>
<!-- selection of supported devices -->
<deviceRequirements if="config.active:defined and (test or enableCompilerMode)" >
<requirement name="Identifier" value="${config.active}" />
</deviceRequirements>
<deviceRequirements if="device:defined and (test or enableCompilerMode)" unless="config.active:defined">
<requirement name="Identifier" value="${device}" />
</deviceRequirements>
<deviceRequirements unless="test or enableCompilerMode">
<requirement name="Identifier" value="${devices}" />
</deviceRequirements>
<!-- build settings -->
<!--
-->
<build
usePolishGui="true"
workDir="${dir.work}"
destDir="${dir.dist}"
compilerMode="${enableCompilerMode}"
compilerDestDir="build/classes"
compilerModePreverify="true"
>
<!-- midlets definition, NetBeans defines all MIDlets in the Ant property manifest.midlets: -->
<midlets definition="${manifest.midlets}" if="manifest.midlets:defined" />
<midlets unless="manifest.midlets:defined">
<midlet class="de.enough.polish.example.MenuMidlet" name="Example" />
</midlets>
<!-- project-wide variables - used for preprocessing. -->
<!-- You can set localized variables in the resources/messages.txt files as well. -->
<variables includeAntProperties="true" >
<!-- use the advanced menubar mode that offers near-native command handling and positioning, on BB and Android use native commands: -->
<variable
name="polish.FullScreen"
value="menu"
unless="polish.blackberry || polish.android"
/>
<variable name="polish.MenuBar.useExtendedMenuBar" value="true" />
<!-- example variables:
In your Java-code you can use the following snipet to use this variable:
//#= private static final String UPDATE_URL = "${ update-url }";
You can change the title of the sample application with the "title"-var.
-->
<variable name="update-url" value="http://www.enough.de/update" />
<variable name="title" value="J2ME Polish" />
</variables>
<!-- Here you can set the dir attribute to "resources2" for an alternative design. -->
<resources
dir="resources/base"
defaultexcludes="yes"
excludes="readme.txt"
>
<root dir="resources/customizations/${customization}" if="${customization}.enabled" />
<!-- add the localization element for created localized
versions of your application: -->
<localization locales="de_DE, en_US" unless="test" />
<localization locales="en_US" if="test" />
</resources>
<!-- obfuscator settings: do not obfuscate when the test-property is true -->
<obfuscator name="ProGuard" unless="test or polish.blackberry" >
<!--
You can set additional parameters here, e.g.:
<parameter name="optimize" value="false" />
-->
</obfuscator>
<!-- debug settings: only include debug setting when the test-property is true -->
<debug if="test or log" verbose="true" level="error">
<filter pattern="de.enough.polish.example.*" level="debug" />
<filter pattern="de.enough.polish.ui.*" level="warn" />
<!-- activate display handler to see log entries in real time:
<handler name="display" />
-->
</debug>
<!-- user defined JAD attributes can also be used: -->
<jad>
<attribute name="Nokia-MIDlet-Category" value="Game" if="polish.group.Series40" />
</jad>
<!--
This is an example for signing MIDlets with J2ME Polish.
You can set the password on the commandline by calling "ant -Dpassword=secret",
or by setting the Ant property above.
Signing is done only for MIDP/2.0 devices.
-->
<!--
<sign
key="SignMIDlet"
keystore="midlets.ks"
password="${password}"
unless="test"
/>
-->
</build>
<!-- execution of emulator(s) -->
<emulator
wait="true"
trace="class"
securityDomain="trusted"
enableProfiler="true"
enableMemoryMonitor="true"
enableNetworkMonitor="true"
if="test and not debug"
>
<!--
<parameter name="-Xjam" value="transient=http://localhost:8080/${polish.jadName}" />
-->
</emulator>
<emulator
wait="true"
trace="class"
securityDomain="trusted"
enableProfiler="false"
enableMemoryMonitor="false"
enableNetworkMonitor="false"
if="debug"
>
<!-- Attach the emulator to the NetBeans debugger: -->
<debugger name="antcall" target="connect-debugger" port="6001" />
</emulator>
</j2mepolish>
</target>
<target
name="emulator"
depends="test,j2mepolish"
description="invokes the emulator"
>
</target>
<target name="clean"
description="allows a clean build. You should call [ant clean] whenever you made changes to devices.xml, vendors.xml or groups.xml">
<delete dir="build" />
<delete dir="dist" includes="**/*" />
</target>
<target
name="cleanbuild"
description="allows a clean build. You should call [ant cleanbuild] whenever you made changes to devices.xml, vendors.xml or groups.xml"
depends="clean, j2mepolish"
/>
<target name="debug" description="debugs the project" depends="enableDebug, test, j2mepolish" />
<target name="deploy"
description="Deploys the applications. Currently empty."
depends="j2mepolish"
/>
<target name="enableBarbie">
<property name="customization" value="Barbie" />
<property name="Barbie.enabled" value="true" />
</target>
<target name="barbie"
description="customizes this project with the settings found in resources/customizations/Barbie"
depends="enableBarbie, j2mepolish"
/>
<target name="enableFrogger">
<property name="customization" value="Frogger" />
<property name="Frogger.enabled" value="true" />
</target>
<target name="frogger"
description="customizes this project with the settings found in resources/customizations/Barbie"
depends="enableFrogger, j2mepolish"
/>
<target name="enableAnimations">
<property name="customization" value="Animations" />
<property name="Animations.enabled" value="true" />
<property name="polish.MenuBar.useExtendedMenubar" value="true" />
</target>
<target name="animations"
description="customizes this project with the settings found in resources/customizations/Animations"
depends="enableAnimations, j2mepolish"
/>
<target
name="build-all"
description="Builds your application in all customizations."
>
<subant target="j2mepolish" buildpath="." genericantfile="build.xml" inheritall="false" ></subant>
<subant target="frogger" buildpath="." genericantfile="build.xml" inheritall="false" ></subant>
<subant target="barbie" buildpath="." genericantfile="build.xml" inheritall="false" ></subant>
<subant target="animations" buildpath="." genericantfile="build.xml" inheritall="false" ></subant>
</target>
<!-- NetBeans specific build targets: -->
<target name="run"
depends="test, j2mepolish"
>
</target>
<target name="rebuild"
depends="clean, j2mepolish"
>
</target>
<target name="rebuild-all"
depends="clean, j2mepolish"
>
</target>
<target name="jar"
depends="j2mepolish"
>
</target>
<target name="jar-all"
depends="j2mepolish"
>
</target>
<target name="clean-all"
depends="clean"
>
</target>
<target name="deploy-all"
depends="deploy"
>
</target>
<target name="enable-compiler-mode">
<property name="enableCompilerMode" value="true" />
</target>
<target name="compile-single"
depends="enable-compiler-mode, j2mepolish"
>
</target>
<target name="connect-debugger">
<property name="jpda.port" value="${polish.debug.port}" />
<antcall target="nbdebug"/>
</target>
</project>
Any help much appreciated.
Update: (17-Feb-2015)
I have added <property name="dir.dist" value="dist" /> (right after the existing <property name="dir.work" value="build/real" /> line), but now I get this error when trying to clean/build the project:
ant -f M:\\Netbeans\\J2ME-Polish-Project rebuild
clean:
Deleting directory M:\Netbeans\J2ME-Polish-Project\build
pre-init:
pre-load-properties:
exists.config.active:
exists.netbeans.user:
exists.user.properties.file:
load-properties:
exists.platform.active:
exists.platform.configuration:
exists.platform.profile:
basic-init:
cldc-pre-init:
cldc-init:
cdc-init:
semc-pre-init:
semc-init:
savaje-pre-init:
savaje-init:
sjmc-pre-init:
sjmc-init:
ojec-pre-init:
ojec-init:
cdc-hi-pre-init:
cdc-hi-init:
nokiaS80-pre-init:
nokiaS80-init:
post-init:
init:
j2mepolish-init:
j2mepolish:
J2ME Polish 2.4 (2013-08-27) (GPL License)
Loading device database...
Processing [7] devices...
building application for [Generic/jtwi] (1/7):
using locale [de_DE]...
M:\Netbeans\J2ME-Polish-Project\build.xml:83: build.xml line 0: found no operator before symbol [.enabled] in term [${customization}.enabled] (both symbol and term might be simplified).
BUILD FAILED (total time: 1 second)
I never got to the bottom of this specific error message, but I did manage to get another J2ME Polish demo project up and running in the end - from which point I could adapt the project as per my requirements.
Basically, I had no joy with Netbeans 8.0, so I used Netbeans 7.2.1. And the demo project that worked for me (which you select in the last step of the J2ME Polish New Project wizard) was the datefield project.
I also found it's important to select a specific device to get the project to compile - I just selected the Generic/midp2 device (found under the Virtual section in the wizard) and make sure it is selected as the current configuration when you build the project.
I expect there will be many other variations that also work, but after a lot of farting around, this is the combination that eventually worked for me - so hopefully this will be a good starting point for someone else.

How do I create a Jar file from my program

I am using eclipse, and I am having difficulty in creating jar files.
So I have codes like getClass().getResource("/imagesfolder/dog.jpg").
How would I create Jar files such that the folder containing my images will also be included. Because error occurs if my Jar file is not in my bin folder with the class files and the imagesfolder.
I tried File>Export>Java>Executable Jar>Save in desktop but when I double click it, it does not start. I tried cmd and it worked but with errors that it can't find imagesfolder.
How will I do a jar file in a separate directory that executes with a double click
I have a class TreeIcon; it uses two images, and I store them in a folder 'images' which is within the package of TreeIcon. For whatever reason, I made the package of TreeIcon spacecheck.images (it could just as easily have been com.mycompany.images). Therefore I used following code to access my images:
expandedIcon = new ImageIcon(TreeIcon.class.getResource("images/Expanded.GIF"));
where the 'images' here is the name of the folder containing just the images, not the one that is part of the package. I.E., in my tree structure for the program source, the images are in a folder named spacecheck.images.images.
Note that there's no slash at the start of my string; this means it references a path relative to that of the class. Putting the slash in front of the spec causes getResource to regard the path as absolute within your jar, so I could also have used the string "/spacecheck/images/images/Expanded.GIF".
ANT is The Way
In eclipse you can use Ant to build your .jar file.
From ant.apache.org
Apache Ant is a Java library and command-line tool whose mission is to
drive processes described in build files as targets and extension
points dependent upon each other. The main known usage of Ant is the
build of Java applications. Ant supplies a number of built-in tasks
allowing to compile, assemble, test and run Java applications. Ant can
also be used effectively to build non Java applications, for instance
C or C++ applications. More generally, Ant can be used to pilot any
type of process which can be described in terms of targets and tasks.
Ant is written in Java. Users of Ant can develop their own "antlibs"
containing Ant tasks and types, and are offered a large number of
ready-made commercial or open-source "antlibs".
Ant is extremely flexible and does not impose coding conventions or
directory layouts to the Java projects which adopt it as a build tool.
Software development projects looking for a solution combining build
tool and dependency management can use Ant in combination with Apache
Ivy.
The Apache Ant project is part of the Apache Software Foundation.
Search with google and you will find many documentation, I will show the basic way to do it.
The Build.xml file
First of all create a new file xml, for example "Build.xml" this will be the file that Ant will read.
The you start writing inside it this:
<?xml version="1.0" encoding="UTF-8"?>
This is the basic line you have always to include.
<project name="NameOfYourProject" default="try_jar" basedir=".">
This (with its closing tag </project> at the end of the file, is the main tag, declaring the name of the project and the first task (default) that will be executed, each task is something Ant will do, and is called "Target", you can create a single target that do everything or various target that do few things each, in this case you can create different "flow-chart" that ant will follow. For example I usually create 3 route for Ant: try_jar that is used just to try if all is working in the jar without doing many things, new_version_jar that is the same of try_jar but will update version number, will sign the jar and some other stuff, and javadoc that creates the javadoc for the project. Il will show you the basic try_jar.
<description>
This buildfile is used to build the jar of the game.
</description>
No need to explanation.
<!-- ================= File and Directory Names ==================== -->
<property name="src" location="${basedir}/src" />
<property name="conf" location="${basedir}/conf" />
<property name="build" location="${basedir}/build" />
<property name="dist" location="${basedir}/dist" />
<property name="app.name" value="MyAppName" />
<property name="dist.jarHome" value="${user.home}/MyApplicationMainFolder" />
<property name="app.version" value="0.2" />
<tstamp />
<property name="jar.name" value="${app.name}_${app.version}.${DSTAMP}.jar" />
<property name="jar.completePath" value="${dist.jarHome}/${jar.name}" />
Here we declare the base properties of the jar, we tell it where the source code is, where the build folder should be and so on. We also choose to put all the app in a folder in the base user home (in mac this is /user/UserName/) and create the name for the file that will include the name (obviously) the version and the time when this jar is created. This avoid duplicated or overriding of files that we may want to keep.
<property name="shared.lib" value="${basedir}/lib" />
Here we must specify the directory in which jar files needed by this plugin to run are stored
<!-- =============== Custom Ant Task Definitions =================== -->
<property name="compile.debug" value="true" />
<property name="compile.deprecation" value="false" />
<property name="compile.optimize" value="true" />
This are configuration params for ant
<!-- ================== External Dependencies ======================= -->
<property name="LWJGL" value="lwjgl.jar" />
<property name="Timer" value="timer.jar" />
<property name="Database" value="hsqldb.jar" />
<property name="Splice" value="jarsplice-0.25.jar" />
Here you must specify your external dependencies (something like easymock or powermock if you want to create a test target.
<!-- ================== Compilation Classpath ======================= -->
<path id="compile.classpath">
<fileset dir="${src}">
<include name="**/*.java" />
<exclude name="**/server/*.java"/>
</fileset>
<fileset dir="${shared.lib}">
<include name="**/*.jar" />
</fileset>
</path>
This is what And (with javac command) will build, you have to specify all the folders you want to build and to add (with <fileset>) any jar that is in the buildpath
<!-- =================== All Target ================================ -->
<!-- ================== Try_jar Target ============================ -->
<target name="try_jar" depends="compile, dist, clean_class_files, run" description="Clean build and dist directories, then compile, create jar and finally run" />
This is our target, as specified in "default" the first line, and will run this. Depends tells Ant what it should do before this target. A you can read it will compile, create the jar (dist), remove the class files, and run it.
<!-- ================== Clean Target ============================== -->
<target name="clean" description="Delete old build and dist directories">
<delete dir="${build}" />
<delete dir="${dist}" />
</target>
This is very clear, before to compile a new version we want to remove any old class file to avoid problems. You may think that this is never called, but pay attention to the dependencies of each target.
<!-- ================== Prepare Target ============================= -->
<target name="prepare" depends="clean">
<mkdir dir="${build}" />
<mkdir dir="${build}/classes" />
<mkdir dir="${build}/lib" />
<copy todir="${build}/lib">
<fileset dir="${shared.lib}" includes="${Timer}, ${LWJGL}, ${Database}" />
</copy>
</target>
This prepare the path, creating new needed folders (like build and build/classes) and adding the external dependencies jars.
<!-- ================== Compile Target =========================== -->
<target name="compile" depends="prepare" description="Compile Java sources">
<mkdir dir="${build}/classes" />
<javac srcdir="${src}" destdir="${build}/classes" encoding="8859_1" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}" source="1.6" target="1.6">
<classpath refid="compile.classpath" />
</javac>
</target>
This is the main compiling target, as you can see it depends on prepare (that depends on clean) so until now we are using all <target> tags.
Ant compile .java files using <javac> tag, that needs to know where the source files are, where to put .class files, the encoding, and the three params we specified earlier.
<!-- =================== Dist Target ================================ -->
<target name="dist" description="Creates Jar archive">
<!-- Create the time stamp -->
<tstamp>
<format property="compile.timestamp" pattern="yyyyMMddHHmm" />
</tstamp>
<!-- update version in manifest -->
<replaceregexp file="${basedir}/manifestClient" match="Implementation-Version: .*" replace="Implementation-Version: ${app.version}.${compile.timestamp}" />
<!-- Create Jar file -->
<jar destfile="${jar.completePath}" manifest="${basedir}/manifest">
<fileset dir="${build}/classes" excludes="**/*.bak" />
<fileset dir="${src}/" excludes="mh/" />
<fileset dir="${shared.lib}/native/macosx" />
<zipfileset src="${shared.lib}/${Timer}" />
<zipfileset src="${shared.lib}/${LWJGL}" />
<zipfileset src="${shared.lib}/${Database}" />
</jar>
</target>
this creates the real jar. <tstamp> and <replaceregexp> are used to update the version in the manifest, you can remove them.
Jar tag will create the .jar file, we specified what files to add in the jar that will be avaible to my classes inside. We have also to specify a manifest that will discuss later.
<!-- =================== Delete .class Target===================== -->
<target name="clean_class_files" description="Delete .class files stored inside build directory and dist folder">
<delete dir="${build}" />
<delete dir="${dist}" />
</target>
This target deletes the two folder used to store .class files (and obviously all the files inside).
<!-- ================== Run Target =============================== -->
<target name="run" description="Run MagicHogwarts">
<java jar="${jar.completePath}" fork="true">
</java>
</target>
The end of our build.xml file, that is the run target that runs the jar.
This is almost what you need to compile and and the correct resources to a jar, if something is not like you are expecting, simply try few times and all will go right.
This is the manifest:
Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)
Main-Class: package.to.class.with.main
Built-by: Gianmarco
Implementation-Vendor: Gianmarco
Implementation-Title: Title
I hope this will be useful to you.
I am editing few things to make the post better, but no contents will be different.

Shall I add my unit test folder to the java build path in Eclipse?

We are developing an Eclipse product made of several plugins, some of them developed by us. Each of our plugins has be defined as an Eclipse plugin project in workspace and has two folders, source and test. Recently I noticed that we are delivering the test classes to the user like the our source classes. Now I want to remove the test classes from the result of our product. Shall I remove the test folder from the Java build path (see the attachment)? And what else I should do to don't deploy our tests to the end-user?
To build the project we are using the eclipse standard ant script to create our zip file. I don't find where can I exclude test files. Here is the the Ant script:
<property name="allElementsFile" value="${eclipse.pdebuild.scripts}/productBuild/allElements.xml"/>
<import file="${eclipse.pdebuild.scripts}/build.xml"/>
<property name="pluginPath" value=""/>
<property name="pluginList" value=""/>
<property name="featureList" value=""/>
<property name="includeLaunchers" value="true"/>
<property name="generatedBuildProperties" value=""/>
<condition property="nestedInclusions" value="true">
<istrue value="${p2.gathering}" />
</condition>
<!-- ===================================================================== -->
<!-- main entry point to setup, fetch, generate, build etc. Use -->
<!-- the customTargets.xml to modify the build behaviour. -->
<!-- ===================================================================== -->
<target name="main" description="the main build target">
<antcall target="preBuild" />
<antcall target="processRepos"/>
<antcall target="generateFeature"> <!-- Generate the feature to drive the fetch -->
<param name="verify" value="false"/>
</antcall>
<antcall target="fetch" />
<antcall target="generateFeature"> <!-- We are calling generate feature a second time so that we can get the pack / unpack clause fixed -->
<param name="verify" value="true"/>
</antcall>
<antcall target="generate" />
<antcall target="process" />
<antcall target="assemble" />
<antcall target="package" />
<antcall target="postBuild" />
</target>
<!-- ===================================================================== -->
<!-- Generate a container feature based on the product file -->
<!-- The plugin or feature containing the .product file will need to exist -->
<!-- already, use preSetup or postSetup to fetch it if necessary -->
<!-- ===================================================================== -->
<target name="generateFeature">
<eclipse.generateFeature
featureId="org.eclipse.pde.build.container.feature"
buildDirectory="${buildDirectory}"
baseLocation="${baseLocation}"
productFile="${product}"
verify="${verify}"
pluginPath="${transformedRepoLocation}${path.separator}${pluginPath}"
configInfo="${configs}"
pluginList="${pluginList}"
featureList="${featureList}"
includeLaunchers="${includeLaunchers}"
buildPropertiesFile="${generatedBuildProperties}"
nestedInclusions="${nestedInclusions}"
filterP2Base="${filterP2Base}"
/>
</target>
</project>
This is an issue with your deployment procedure/script. Are you using Eclipse to build the jar ?
It should not have to do with the build path, you should keep your test source in the build path if you use Eclipse to code them.
Usually a deployment procedure using Ant or Maven will exclude the test classes from the result (jar, war, ...). It is also advisable to automatically run the tests before the jar is created.
To remove test files (if you defined for every plugin project a source folder and a test folder) from the code while building a pde project using pde ant scripts you should remove the test folder from the build.properties of that project. The build.properties is a part of plugin.xml

Categories

Resources