Edit: this is the Project Setup:
IDE: Eclipse:
Project1 : "Server"
src:
com/mainpackage/main.java
libs:
commons-x-0.jar
PluginInterface.jar
all jar in libs-folder are on the buildpath.
Project2 : "PluginInterface"
src:
com/interfaces/plugininterface
Project3 : "Plugin"
src:
com/package/class1.java - (this implements plugininterface)
libs:
library1.jar
PluginInterface.jar
all jar in libs-folder are on the buildpath
so when i export the Plugin (Project3) i get a jar like this (excluded PluginInterface.jar from export)
com/
com/package/
com/package/class1.class
com/package/class1.java
libs/
libs/library1.jar
library1.jar looks as follows - it is not written by me:
com/
com/stuff/
com/stuff/libclass.java
com/stuff/libclass.class
now i Want to utilize class1 in the "Server" over the Interface:
ClassLoader loader=URLClassLoader.newInstance(
new URL[]{new URL("file:path/to/plugin.jar")},
ClassLoader.getSystemClassLoader()
);
Class<?> pluginclass = Class.forName("com.package.class1", true, loader);
plugininterface ref = (plugininterface)pluginclass.newInstance();
i can now call methods from class1 using the interface both projects know, because both of them include "PluginInterface.jar" in their buildpath.
THE PROBLEM:
"Server" does not recognize "libclass", because is neither in its path nor did i load the class from the plugin.jar in which the library1 is nested.
how do i access this class if an import as library is not possible at the server?
Thanks for any help!
Edit: just for the sake if someone ever has this Problem again, i'll add the ANT files' build-target that makes it work:
<target name="build">
<javac destdir="bin" includeantruntime="false" source="1.7" target="1.7">
<src path="src"/>
<classpath refid="Plugin.classpath"/>
</javac>
<unzip src="${libs}/library1.jar" dest="bin/">
<patternset>
<include name="**/*.class"/>
</patternset>
</unzip>
<jar destfile="plugin.jar" basedir="bin"></jar>
</target>
Just copy the contents of the Library-jar into the build directory (in my case ./bin/). it then isn't even necessary to feed the libraryclasses to the Classloader, it finds them when loading the Classes use them.
The standard class loader does not support nested jar files. You could programmatically extract the jar, or write your own classloader which will decompress the nested files on demand. However, you'd be swimming against the current: such packaging is just not recommended. Instead it is recommended to explode the nested jar into its parent. This is, for example, what Maven dependency plugin does, and the default way to publish a Clojure application with Leiningen.
To achieve your goal from Eclipse the best approach seems be this:
have Eclipse's Export JAR wizard save the ant build scripts it internally generates to build your JAR;
adapt the resulting script to meet your specific needs;
in the future don't run the wizard anymore, but the ant script.
As mentioned by Marko, your standard class loader will not scan through nested jars and nested jars within them. However, if you're willing to play around with TrueZip, you can easily do this without having to extract archives or anything. What's better is that you can have nested archives within nested archives as deep as as you like. So your path could look like:
/path/to/foo.jar/bar/foo/my.zip/containing/some.tar/com/foo/My.class
If you feel comfortable writing your own classloader using TrueZip, this would be a neat way to do it. If not, then you'd have to write a utility class that parses the path and extracts the archives first, before feeding it into the standard URLClassloader.
Related
I have an ANT script that calls a Java 11 class using a custom classpath
<path id="ant.classpath">
<fileset dir="${basedir}/lib/ant">
<include name="*.jar" />
</fileset>
</path>
<taskdef name="myTaskDef" classname="A.SomeClass" classpathref="ant.classpath" />
The ${basedir}/lib/ant directory contains several jars
A.jar - My library
B.jar - Third-party library
C.jar - Third-party library, different company than B.Jar
These jars all load into the classpath ${ant.classpath} just fine.
The workflow is like this:
A.jar calls B.jar, and B.jar calls C.jar.
So, A.jar calls classes in B.jar no problem. It uses the import statement in JAVA to call the classes:
import B.SomeClass;
This works perfectly.
However, B.jar calls C.jar and it fails.
I was able to inspect the source code code for both third-party libraries and have learned that B.jar calls classes from C.jar using Java's Classloader class. It doesn't use the import statement.
Below is code from a class inside B.jar
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
....
classLoader.loadClass("C.SomeClass");
The exception that I get is:
java.lang.ClassNotFoundException: C.SomeClass
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at B.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
I was able to verify that C.SomeClass does exist in C.jar.
I suspect that it's loading a different classpath than the one provided by the ant taskdef. When I try to load the C.jar class from within my library (A.jar) using the ClassLoader, I get the same exception. But import works just fine.
I'm sort of at a loss at what to do because I can't get B.jar to properly load C.jar through Ant.
EDIT:
In case it's useful, I'm using Java 11, and B.jar is really jaxb-api-2.4.0.jar (javax.xml.bind) and C.jar is jaxb-runtime-2.4.0.jar (com.sun.xml.bind) plus its dependencies (jaxb-core, stax-ex, txw2, etc). I get the ClassNotFoundException, when I call:
JAXBContext jc = JAXBContext.newInstance(Feature.class);
And it can't find the class com.sun.xml.bind.v2.ContextFactory, which I've confirmed does indeed exist.
So, I messed around in A.jar and learned that getClass().getClassLoader() and Thread.currentThread().getContextClassLoader() return different things. The getClass().getClassLoader() contains the ANT classpath that I set in the ANT script, the the Thread classloader does not.
I can't change the code in B.jar since it's a 3rd-party library, however, I was able to set the Thread's classloader in my code using the following:
ClassLoader cl = this.getClass().getClassLoader();
Thread.currentThread().setContextClassLoader(cl);
I put this in the code right before my code calls B.jar, and subsequently C.jar. It worked perfectly!
i was writing a custom task for ant in java and my idea was that i can give someone the .jar which contains the java files like the classes and the libraries and the build.xml for ant and he can use it.
If i export my java project the .jar (antTask.jar) contains :
a folder for the compiled classes, one for the libraries, meta-inf folder and .classpath .project files
The ant build.xml looks like this:
<?xml version="1.0" ?>
<project name="repair" basedir="." default="repairTask">
<taskdef name="antTask" classpath="antTask.jar" classname="def.RepairTask"/>
<target....
i don't really understand all this classpath stuff, so can someone tell me what i have to add in my build file so it will work only with this .jar file without the java code sources?
right now i am getting an error that ant can't find one of the libraries i use in the java code with this error (but the antTask.jar contains this lib as another .jar):
taskdef A class needed by class def.RepairTask cannot be found: org/apache/commons/...
using the classloader AntClassLoader[C:...\AntTask\antTask.jar]
i am trying for hours but i just can't figure out how i have to edit my build.xml so i just have to point to this single .jar file and it works..
Thank you guys
All a taskdef does is associate a task name to a classfile that contains the code to execute that task. However, in order to find that classfile, you need to tell <taskdef/> where to find the jar that contains it. That's all classpath does is.
You don't have to define a classpath with the <taskdef/> task. Ant by default looks for all jars that contain code for the <taskdef/> tasks in $ANT_HOME/lib. If you copy your jar to that folder, you could simply define that task this way:
<taskdef name="antTask" classname="def.RepairTask"/>
No need for the classpath. However, I actually don't recommend doing that. Instead, I recommend putting that jar file into your project, so other developers can use your project without having to install that task jar into their $ANT_HOME/lib folder:
<taskdef name='antTask' classname="def.RepairTask">
<classpath>
<fileset dir="${basedir}/antlib/antjar"/>
</classpath>
</taskdef>
Now, when a developer checks out the project that requires the optional task jar, that task jar comes with the project, so they can simply do their build.
There are two ways to define tasks. One is to give a task a name, and then tell <taskdef/> what classfile is associated with that jar as you did above. However, you can also define a resource that also will associate task names with their classes. Here's a common way to include the Ant-Contrib ant tasks:
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<fileset dir="${basedir}/antlib/antcontrib"/>
</classpath>
</taskdef>
If I expand the antcontrib jar, I'll see it contains a net/sf/antcontrib/antcontrib.properties1 file inside the jar. That file looks something like this:
...
# Logic tasks
if=net.sf.antcontrib.logic.IfTask
foreach=net.sf.antcontrib.logic.ForEach
throw=net.sf.antcontrib.logic.Throw
trycatch=net.sf.antcontrib.logic.TryCatchTask
switch=net.sf.antcontrib.logic.Switch
outofdate=net.sf.antcontrib.logic.OutOfDate
runtarget=net.sf.antcontrib.logic.RunTargetTask
timestampselector=net.sf.antcontrib.logic.TimestampSelector
antcallback=net.sf.antcontrib.logic.AntCallBack
antfetch=net.sf.antcontrib.logic.AntFetch
assert=net.sf.antcontrib.logic.Assert
relentless=net.sf.antcontrib.logic.Relentless
# Math Tasks
math=net.sf.antcontrib.math.MathTask
...
All it does is define each task with a classfile for that task. I would recommend you do something similar with your custom ant task. This way, if you decide to include other tasks, you can simply modify this one file, and developers won't have to change their <taskdef/> definition in their jars, or add in multiple ones.
By the way, you should make good and sure that your class doesn't clash with another class that someone else may use. You might want to give your classname a full path that includes a unique prefix:
<taskdef name='antTask' classname="com.vegicorp.anttasks.RepairTask">
Assuming you work for VegiCorp...
1 Ant contrib tasks contain two such files. One is XML format and the other is in properties format. I always use the XML format, and that's what your suppose to use when you define Ant Task resources. I used the properties file because it's a simpler format and easier to see what's going on.
I am trying to run PMD from Ant in Eclipse when I build the project.
This is my build.xml file:
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>
<target name="check_pmd">
<pmd rulesetfiles="C:\Users\Nikolay\ProjectName\lib\rulesets\java\basic.xml">
<formatter type="html" toFile="pmd_report.html" toConsole="true"/>
<fileset dir="C:\Users\Nikolay\ProjectName\src">
<include name="**/*.java"/>
</fileset>
</pmd>
</target>
It works well for basic.xml, but I want to run for all rulesets in java folder (It has around 20 rulesets) So I have tried:
<pmd rulesetfiles="C:\Users\Nikolay\ProjectName\lib\rulesets\java\*.xml">
<pmd rulesetfiles="C:\Users\Nikolay\ProjectName\lib\rulesets\java\*">
But both of them fail when I try to run. Is there a way to specify folder, not a single file without specifying list of files manually?
For future readers to configure Ant PMD under Eclipse:
Download pmd-bin.zip from official website
Unpack pmd.jar, jaxen.jar and asm.jar
Add jars above to Window - Preferences - Ant - Runtime - Ant Home Entries - Add External JARs
Unpack rulesets folder
Reference location of ruleset from <pmd rulesetfiles=...>
(expanding answer from coolfan for ant task)
The documentation of PMD rulesetfiles says it is comma separated list of files.
rulesetfiles A comma delimited list of ruleset files
('rulesets/basic.xml,rulesets/design.xml'). If you write your own
ruleset files, you can put them on the classpath and plug them in
here. Yes, unless the ruleset nested element is used
Ant provides a way to convert fileset into such a format. The task is pathconvert
here is an example from website
<fileset dir="${src.dir}" id="src.files">
<include name="**/*.java"/>
</fileset>
<pathconvert pathsep="," property="javafiles" refid="src.files"/>
Maybe the param doesn't support wildcard, as the document suggests.
A quick look over its source code also supports my guess, see RuleSetReferenceId.java, line 194.
So, it takes a property which contains a "list" using , as delimiter, like:
"rule1,rule2,rule3,path-to-rule-file4"
The workaround could be scanning the directory, list all the rule-xml files, and build a property in the comma-delimited format and then pass it to <pmd> task.
Unfortunately, I don't know any ant task which can do this. So you may have to write some code.
I can come up with two ways:
write a ant task; there are many Q&As about this for Java, like this.
write groovy inside a <groovy> task; also many Q&As.
EDIT:
Jayan suggests <pathconvert> task, which should be the right answer.
In the pmd library jar there is an all-java.xml where all the rule sets have been included.
Try to use the following:
<pmd rulesetfiles="rulesets/internal/all-java.xml">
This is a really silly question that I can't fine a difinitive answer to.
Background.
I'm using Eclipse (with one of the ANT plugins, on an XP terminal).
I have just started playing with ANT, in the [jar] directive I am setting the location of my finished JAR file and I get the following when I 'unzip' the file
META-INF/MANIFEST.MF
MyMainFile.class
which is consistent with that found on the oracle web site for the internal structure.
(here http://docs.oracle.com/javase/tutorial/deployment/jar/view.html )
But when I try to run my file I get a 'main class not found' error ?
I have seen some other posts where people have 'unzipped' the JAR file and ended up with a structure of the following...
META-INF/MANIFEST.MF
dtvcontrol/DTVControlApp.class
(from here http://www.coderanch.com/t/528312/java/java/standalone-application)
So should I get a structure where my class files are in a directory that reflects the name of the package... eg
META-INF/MANIFEST.MF
MyPackage/MyMainFile.class
and if so, why am I getting the incorrect structure using ANT, or why are there 2 different 'correct' internal structures? (how to specifify main-class and classpath for each / control what I get)
Also in case you are interested, in the MANIFEST file states (build using ANT)
[attribute name="Main-Class" value="MyPackage.MyMainFile"/]
Also the directory structure of the package under development is as follows...
/JavaDev/MyTestPackage/src (contains the source files)
//JavaDev/MyTestPackage/bin (contains the class files from eclipse, or from the ANT JAVAC task, have I named it incorrectly? should I have called it build ? )
Further to this, when I create the jar I am not naming it 'MyTestPackage.jar' but simply 'test.jar' could this be causing a problem? I assume not as if I have well understood that is what the [main-class] definition stuff is all about.
Further to all this...
'MyTestPackage' is actualy a small visual error messaging library that I use elsewhere, and I have a second file that has a main class to use for testing. As such it points to various libraries (do I need to copy all the SWT libraries to a specified directory?)
I have read somewhere that if I load libraries into my main class (which I obviously do to open the window) then trying to run the program will fail on a 'main class not found' if I use them, same is also true for adding in any 'static final' members (which I use for the loggin of errors).
'Static Final' problem...
I tried to adjust the classpath in ANT, and I get a load of other errors for the connection to Log4J and my 'wrapper' that I use (to do with it being a bad import), but the libraries exist where they should as set in the classpath).
I feel like I am almost there.... but not quite...
I'm doing this for the small 'library projects' that I am creating with the intention of using MAVAN for the main outer package that will connect them all together... for now however I just want to get this going so as it works.
I can supply the full source, or any other info as required.
Thanks in advance...
David
It's simple when you know where to look. Say your META-INF/MANIFEST.MF contains the line:
Main-Class: mypackage.MyMainFile
then the structure of the jar needs to be
META-INF/MANIFEST.MF
mypackage/MyMainFile.class
where MyMainFile has to be in the proper package:
package mypackage;
public class MyMainFile {
public static void main(String[] args) {
...
Your error message is caused by MyMainFile being in the wrong place.
Edit: it's been a while since the last time i did that with ant, but i think you need something like this: a source file structure that reflects the package struture, say
src/main/java/mypackage/MyMainFile.java
and a directory to put the compiled class file into, say
target
(I'm using maven conventions here, ant doesn't care and you can use the (rightclick)->properties->Java Build path->Sources tab in eclipse to set the source dir to src/main/java and the target to target/classes). Then in ant, have a compile target that compiles from source to target:
<target name="compile">
<mkdir dir="target/classes"/>
<javac srcdir="src/main/java" destdir="target/classes"/>
</target>
so that after ant compile you should see the class file in the target
target/classes/mypackage/MyMainFile.class
Then have a ant jar task that packages this:
<target name="jar" depends="compile">
<jar destfile="target/MyJarFile.jar" basedir="target/classes">
<manifest>
<attribute name="Main-Class" value="mypackage.MyMainFile"/>
</manifest>
</jar>
</target>
After saying ant compile jar you should have a file MyJarFile.jar inside target and
java -jar MyJarFile.jar
should run the main method.
I want to create javadoc with ant from a java source file and just from the dependent classes of this file. These are in a java project, but i don't need javadoc from all the java files.
Is there a way to create javadoc like javac
javac includes="package/Java_source.java" destdir="dir/classes"
that compiles the source files and just the dependent classes? If there isn't, then is there another way?
Thanks, Tamas
Well you can add a fileset and / or a packageset parameter:
Example with a fileset:
<javadoc
destdir="docs/api"
author="true"
version="true"
use="true"
windowtitle="Test API">
<fileset dir="src">
<include name="foo/bar/BaseClass.java"/>
<include name="foo/bar/baz/DependentClassA.java"/>
<include name="foo/bar/phleem/DependentClassB.java"/>
</filset>
</javadoc>
But you will have to figure out the dependent classes yourself, I'm afraid.
Reference:
Ant javadoc Task
There is no way to find out what the "dependent classes" are without starting the job. The only thing I can think of is a brutal hack:
On the compiled classes, use a byte code analysis tool like ASM and check all classes in the code base for their usage of your given class (source code analyis is not enough because of possible wildcard imports and same-package usage). From the List of used classes, build a list of source files, and pass that to the Javadoc task (probably best to create an Ant task that does all this). But this is heavy stuff.