I have JAVA library that I am working on and I am using Ant build system, I am trying to generate a .jar file from and using in another application, what I am trying to do is to enable some specific ENV variables only in Debug build and have them disabled in production/release, and I was wondering how can I achieve that?
In my build.xml I have a property called "debug", which is boolean.
In C/C++ You have the NDEBUG macros where you can define what you will exclude/include in debug mode,
is there something similar in JAVA?
I have tried to read Ant documentation, I see that they use properties but the documentation doesn't state exactly how you can pass those properties into the source code, In fact, I tried to do that but with no success.
As mentioned by #Joachim Sauer above, Java does not feature conditional compilation. You can argue either way for this being a good feature, but it's not available.
What can you do, then?
One method you can use is to write information into the jar's manifest.
For example, you could include the build version and your debug flag like so:
<jar destfile="my.jar" basedir="build/classes">
<manifest>
<attribute name="Package-Title" value="My Package Title" />
<attribute name="Package-Version" value="${build.current.version}" />
<attribute name="Debug" value="${debug}" />
</manifest>
</jar>
Then, in your code, you would attempt to read your own jar's manifest: Reading my own Jar's Manifest
Another simpler option might be to include a properties file in your jar, and just read that. You can use the ant task 'echo' to write out a properties file before the jar task:
<echo file="build/classes/my.properties" encoding="ISO-8859-1" append="false">
Package-Title: ${package-title}
Package-Version: ${build.current.version}
com.example.app.debug=${debug}
</echo>
Then, you can just open "my.properties" in the code as a resource, and use that.
Related
I have a multi-module native Netbeans Java EE project. In it I have a Java Class Library project that is used by multiple other projects which in turn are packaged into the root .ear project.
I'm adding the "build timestamp" and the "build user" attributes to a custom manifest using the library's build.xml:
<target name="-post-jar">
<jar destfile="${dist.jar}" update="true">
<manifest>
When I "clean and build" the root project, each project that refers the library calls:
<ant antfile="${call.script}" target="jar">
And my -post-jar target is called multiple times. This wouldn't be a problem, but sometimes the second invocation of the <jar> task fails with Unable to rename old file (probably due to Netbeans scanning the files in background, but I can't tell for sure).
There are repeating pairs of Building jar and Updating jar messages in Ant's output. However, if I remove my -post-jar target, the second invocation of the jar target does nothing, because it thinks that the jar is up to date and I see only one Building jar message.
How do I mark the updated jar up to date, so the second invocation of the jar target does nothing?
There's a github repo that demonstrates the problem.
I haven't found a way to not re-generate the manifest every time, but I found a way to make the generated file look the same as the zipped file (and we know that the <jar> task doesn't repack when the contents are the same).
Instead of updating the zipped manifest in -post-jar I now update the source file in -pre-jar. This way the final version of the manifest is zipped and since its contents don't change during build, subsequent <jar> invocations update nothing.
It worth mentioning that before adding the attributes Main-Class, Profile, etc. the build-impl.xml of Netbeans creates an empy manifest template, if the user doesn't provide a valid path in the manifest.file= property. The addition happens after -pre-jar, however the existence of the user-provided manifest is checked much earlier, during the init target and the result is saved to the manifest.available property.
My manifest template is not a static file. It contains the "build timestamp" and the "build user" attributes. Therefore the file doesn't exist during the init target, so I had to add the following line at the beginning of my build.xml:
<property name="manifest.available" value="true"/><!-- It will be available by the time we need it -->
Secondly, manifest.file still has to be set and I set it in project.properties (there's no UI for that setting yet and I wonder how it would behave in the presence of the variable in path)
manifest.file=${build.dir}/manifest.tmp
Next, I overwrite the manifest template in the -pre-jar target:
<tstamp>
<format property="current.time" pattern="HH:mm:ss" locale="de,DE"/>
</tstamp>
<target name="-pre-jar" >
<manifest file="${manifest.file}">
<attribute name="MyApp-built-time" value="${current.time}"/>
<attribute name="MyApp-built-by" value="${user.name}"/>
</manifest>
After that, the new problem became obvious: the timestamp was different for each invocation of
<ant antfile="mylib/build.xml" target="jar">
in the multi-module project and Ant had to repack the jar with the new timestamp in the manifest. I solved this by defining the timestamp property in every project's build.xml. Although the properties are not inherited due to inheritall="false", Netbeans allows for overcoming that:
<property name="transfer.current.time" value="${current.time}"/>
This mechanism is broken in Java EE projects, but the workaround is simple:
<presetdef name="ant">
<!-- workaround transfer.* not working in Java EE projects -->
<ant>
<propertyset>
<propertyref prefix="transfer."/>
<mapper from="transfer.*" to="*" type="glob"/>
</propertyset>
</ant>
</presetdef>
I am stuck in a very common problem.
I am plugging my jar (which has many dependencies on third party vendor) into an application server lib directory. If I just copy my jar along with its dependencies into server lib then server classpath becomes to long and hence server is not able to work. Therefore I want to package this Jar with all its dependencies in a single jar so that server's classpath doesn't become too long. I found on various forums that there is a utility to do this i.e. OneJar. But this utility works on executable jar. In my case, my final jar will not be executable.
Also I tried ZIPFileSetGroup utility provided by ANT but that is causing security issues with Manifest file.
Can you please help me in resolving this issue?
Thanks!
If you use Maven to build, you can use the maven dependency plugin and use the copy-dependency task. It will copy all dependencies into your jar file when it creates it.
If you manually add the jars to your jar file, then you need to make sure your jar file has a Manifest.mf file in it and specify the main class and classpath inside of that.
Manifest-Version: 1.0
Main-Class: com.mypackage.MainClass
Class-Path: my.jar log4j.jar
Another option may be to build an .ear file, that is usually how you see enterprise apps or a .war file for web apps when they package specific jar files with them. It sounds like you are using a server, so one of those formats may be a better fit for you.
Using zipgroupfileset in the jar task in ANT is the easiest approach.
<jar destfile="MyApplication.jar" filesetmanifest="mergewithoutmain">
<zipgroupfileset dir="lib" includes="*.jar" />
<!-- other options -->
<manifest>
<attribute name="Main-Class" value="Main.MainClass" />
</manifest>
</jar>
Note the filesetmanifest flag set to mergewithoutmain merges everything but the Main section of the manifests.
Signed jars are causing the SecurityException which need to be handled manually. If any classes associated with signed jars verify the signature on the jar as a whole then those will fail at runtime. Digest signatures against a particular file will be added to the manifest without a problem. Since problem is your classpath getting too large you may not be able to bundle all the jars into a single jar but merge most of them making the CLASSPATH manageable.
There is also : http://code.google.com/p/jarjar/
Create target directory with all dependent jars. Next move 10 jars into a temp directory and keep moving the jars in batches of 10 and each time try to create the single jar from that group. When you get the security exception you can isolate which one is causing the problem. Try divide-and-conquer approach. If you have 300 jars then only have to do this 30 times.
When you say
child process picks up classpath from server/lib directory
is this a process that is under your control? If the parent process were to specify the classpath just as
server/lib/*
(i.e. a literal *) then the target java process will enumerate the jar files in the lib directory itself - they do not all need to be named on the classpath.
But if the parent process is explicitly enumerating server/lib/*.jar to build the -cp value then you could take advantage of the fact that the Class-Path in a JAR manifest takes effect even if a JAR is not "executable". You could use a stanza like this to create a manifest-only JAR file
<!-- location of your 300 dependency JAR files, file1.jar ... file300.jar -->
<property name="lib.dir" location="lib" />
<fileset id="dependencies" dir="${lib.dir}" includes="*.jar" />
<pathconvert property="manifest.classpath" dirsep="/" pathsep=" "
refid="dependencies">
<map from="${lib.dir}" to="myapp" />
</pathconvert>
<jar destfile="myapp-manifest.jar">
<manifest>
<attribute name="Class-Path" value="${manifest.classpath}" />
</manifest>
</jar>
This will produce a JAR file named myapp-manifest.jar whose manifest contains
Class-Path: myapp/file1.jar myapp/file2.jar ... myapp/file300.jar
You put this file into server/lib and the 300 dependencies into a new directory server/lib/myapp. Now the generated -cp will include just one file (myapp-manifest.jar) but the resulting java process will have all the 300 myapp JAR files available to it.
Is there any way that i can give a version number to my application in netbeans.And then access that version number inside my code.
Something similar to the Assembly number that we use in .Net.Is there anything like that in java or in netbeans...?
Define an Implementation-Version in the manifest of the Jar at build time. It is common to use some form of the date as the version number. E.G. 14.07.28
The value can be retrieved in code using..
String version = this.getClass().getPackage().getImplementationVersion();
<tstamp>
<format property="now" pattern="yy.MM.dd"/>
</tstamp>
...
<jar
destfile="build/dist/lib/${jar.name}"
update='true'
index='true' >
<manifest>
<attribute name="Created-By" value="${vendor}"/>
<attribute name="Implementation-Title" value="${application.title}"/>
<attribute name="Implementation-Vendor" value="${vendor}"/>
<attribute name="Implementation-Vendor-Id" value="org.pscode"/>
<!-- This next property is retrieved in code above. -->
<attribute name="Implementation-Version" value="${now}"/>
</manifest>
<fileset dir="build/share">
<include name="${package.name}/*.class" />
<include name="${package.name}/*.png" />
</fileset>
</jar>
This comes from a build file for a project I have open at the moment. The relevant attribute is the last one in the manifest section.
In my JavaFX app created in Netbeans, I can set the build version (Implementation version) in the Project Properties window shown here:
This number is then used everywhere, for example it is automatically inserted into the filename of the installer. It is also the number retrieved by this.getClass().getPackage().getImplementationVersion(); mentioned by the accepted answer.
I don't know about .NET assembly numbers, but if you're creating a web application you can certainly put a version number into the manifest of your WAR file.
Any Java package can have a build info text file added to it so you can tell these things.
Your version number could be a build number from Ant, a version number from Subversion, or a combination of the two.
I am attempting to create a JAR based on two separate Java packages. I can compile and run within Eclipse, but cannot get the code to function from the command line. I have Ant and the JDK correctly configured for usage, as I have an almost working Ant build script. The only problem is that the resulting JAR throws a ClassNotFoundException when I attempt to execute it.
The archive contains all the .class files from both packages in the correct directory hierarchy. Regardless, the JAR will throw the above mentioned exception.
The idea is to run this script from the top level directory that contains both packages.
Here are the relevant lines from my build script:
<manifest file="MANIFEST.MF">
<attribute name="Built-By" value="XBigTK13X"/>
<attribute name="Main-Class" value="com.main.MainClass"/>
<attribute name="Class-Path" value="./com/main/ ./secondpackage/shapes/" />
</manifest>
<jar destfile="App.jar"
basedir="./bin"
includes="**/*.class"
manifest="MANIFEST.MF"
excludes="App.jar"
/>
The JAR was correct the whole time. This error was thrown because I was attempting to run the JAR with the following command after creating a JAR:
java MainClass
I now realize that I need to explicitly target the JAR by using the following command:
java -jar MainClass.jar
Look in the resulting JAR file to make sure that the two packages have the correct path from the root. Your Class-Path statement in the manifest may not match the structure of folders containing the .class files.
Verify it by opening the JAR with a zip util.
I use the classpath attribute in custom Ant tasks to tell Ant where to find the external task jar, but how do I do the same for built-in tasks?
In my case I'd like to make sure ant uses my copy of jsch.jar for the scp task, and not one that my already be installed on the system. Is there any way I can <scp> while guaranteeing it's using my jsch.jar?
If your ant call uses $ANT_HOME, you could use just for that ant call a special ANT_HOME value to a custom ant installation, where you make sure your $ANT_HOME/lib contains the right copy of ant-jsch.jar.
See this SO question for more.
I think the best way to do it is to define your own task instead of messing with predefined tasks.
<taskdef name="myscp" class="..." classpath="jsch.jar"/>
<myscp .../>
I had the exact same problem and here's what I did: use Google's Jar Jar to change the package names.
Here's the build.xml i used:
<project name="Admin WAS Jython" default="jar">
<target name="jar" >
<taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask"
classpath="jarjar-1.0.jar"/>
<jarjar jarfile="dist/ant-jsch-copy.jar">
<zipfileset src="ant-jsch.jar"/>
<rule pattern="org.apache.tools.ant.taskdefs.optional.ssh.**" result="org.apache.tools.ant.taskdefs.optional.ssh.copy.#1"/>
</jarjar>
</target>
Then in your ant project use the following:
<taskdef name="scp2"
classname="org.apache.tools.ant.taskdefs.optional.ssh.copy.Scp"
classpath="ant-jsch-copy.jar;jsch-0.1.43.jar"/>
and use the scp2 task instead of scp