I am trying to run a Java class as part of the deployment of my project (I want to create some resources at deployment, which can then be read at runtime).
For the most part, I am using maven for the build cycle - in particular for dependency management.
This what I've got to; creating a path (run), and adding the dependencies from maven using the maven ant tasks, and then running a target that calls a java class (MyClass), which has been compiled to ...MyClass.class in the target\src directory, using a classpath of that directory and the run path specified above.
<path id="run" />
<artifact:dependencies pathid="run">
<artifact:pom file="pom.xml" id="my_project" />
</artifact:dependencies>
<target name="runMyClass">
<java classname="...MyClass" fork="yes" maxmemory="512M" append="true">
<classpath>
<pathelement location="target\classes"/>
<pathelement id="run" />
</classpath>
</java>
</target>
I know that the target\classes is correct - if I comment out the addition of the run path, it finds the class, but reports that some of the imports in the class are not available on the classpath.
However, when I run this, I get the following stack trace:
C:\somepath\my_project\build.xml:118: java.lang.NullPointerException
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:116)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:390)
at org.apache.tools.ant.Target.performTasks(Target.java:411)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
at org.apache.tools.ant.Main.runBuild(Main.java:809)
at org.apache.tools.ant.Main.startAnt(Main.java:217)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:32)
Caused by: java.lang.NullPointerException
at org.apache.tools.ant.types.resources.FileResourceIterator.addFiles(FileResourceIterator.java:104)
at org.apache.tools.ant.types.resources.FileResourceIterator.<init>(FileResourceIterator.java:95)
at org.apache.tools.ant.types.Path$PathElement.iterator(Path.java:124)
at org.apache.tools.ant.types.resources.Union.getCollection(Union.java:123)
at org.apache.tools.ant.types.resources.Union.getCollection(Union.java:107)
at org.apache.tools.ant.types.resources.BaseResourceCollectionContainer.cacheCollection(BaseResourceCollectionContainer.java:265)
at org.apache.tools.ant.types.resources.BaseResourceCollectionContainer.iterator(BaseResourceCollectionContainer.java:142)
at org.apache.tools.ant.types.Path.iterator(Path.java:710)
at org.apache.tools.ant.types.resources.Union.getCollection(Union.java:123)
at org.apache.tools.ant.types.resources.Union.list(Union.java:86)
at org.apache.tools.ant.types.Path.list(Path.java:378)
at org.apache.tools.ant.types.Path.addExisting(Path.java:331)
at org.apache.tools.ant.types.Path.addExisting(Path.java:319)
at org.apache.tools.ant.types.Path.concatSpecialPath(Path.java:572)
at org.apache.tools.ant.types.Path.concatSystemClasspath(Path.java:532)
at org.apache.tools.ant.types.CommandlineJava.haveClasspath(CommandlineJava.java:647)
at org.apache.tools.ant.types.CommandlineJava.addCommandsToList(CommandlineJava.java:437)
at org.apache.tools.ant.types.CommandlineJava.getCommandline(CommandlineJava.java:405)
at org.apache.tools.ant.types.CommandlineJava.describeCommand(CommandlineJava.java:482)
at org.apache.tools.ant.taskdefs.Java.checkConfiguration(Java.java:176)
at org.apache.tools.ant.taskdefs.Java.execute(Java.java:107)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
... 16 more
To me, this looks like an exception is being thrown in the ant code in the process of adding the path set to the classpath, but I could be wrong.
Can anyone suggest (any of the following):
how I might go about debugging this?
an alternative approach to do what I'm trying to do (described
above)?
A little further playing gave me a workable solution...
Rather than refering to the maven dependencies as a path, I can refer to them using a fileset:
<fileset id="run" />
<artifact:dependencies filesetid="run">
<artifact:pom file="pom.xml" id="my_project" />
</artifact:dependencies>
<target name="runMyClass">
<java classname="...MyClass" fork="yes" maxmemory="512M" append="true">
<classpath>
<pathelement location="target\classes"/>
<fileset refid="run" />
</classpath>
</java>
</target>
I don't know what was going on with the other approach, whether it's user error or a bug, so if anyone has any suggestions, I would appreciate comments.
Related
So I made an ANT target to deploy our app to Tomcat on a remote development server. The ANT deploy to tomcat target works 100% perfect on a local Tomcat instance. When I deploy to the remote server I get a fat 500 error but the application actually deploys to the server and we can view and use it just fine as if there were no errors.
Super cool that it works but the 500 error causes the ANT target to say the build failed. If ANT says the build failed, so will Hudson our build server, which means we will have sad red dots instead of happy green ones.
We are using the latest and greatest ANT with Tomcat v9.
Below is the error I get when I execute my "ant deploy-dev" target.
[username#localhost app.directory]$ ant deploy-dev
Buildfile: /home/username/git/app.directory/build.xml
Trying to override old definition of datatype resources
deploy-dev:
[echo] Deploying app to: https://dev.myapp.com
BUILD FAILED
/home/username/git/app.directory/build.xml:73: The following error occurred while executing this line:
/home/username/git/app.directory/build.xml:146: java.io.IOException: Server returned HTTP response code: 500 for URL: https://dev.myapp.com/manager/text/deploy?path=%2Fmy-app%2F
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at org.apache.catalina.ant.AbstractCatalinaTask.execute(AbstractCatalinaTask.java:254)
at org.apache.catalina.ant.DeployTask.execute(DeployTask.java:194)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:293)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.taskdefs.Sequential.execute(Sequential.java:68)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:293)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.taskdefs.MacroInstance.execute(MacroInstance.java:396)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:293)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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:1405)
at org.apache.tools.ant.Project.executeTarget(Project.java:1376)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1260)
at org.apache.tools.ant.Main.runBuild(Main.java:854)
at org.apache.tools.ant.Main.startAnt(Main.java:236)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:285)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:112)
Total time: 3 minutes 3 seconds
To get an idea of what is running, here is the important parts of the ANT build.xml.
<property environment="env"/>
<property file="build.properties"/>
<!-- Import -->
<import file="${env.CATALINA_HOME}/bin/catalina-tasks.xml" optional="true"/>
<!-- The deploy to Tomcat target -->
<target name="deploy-local" description="Deploy the app to local Tomcat">
<tomcat-deploy base-url="${url.base.local}"/>
</target>
<target name="deploy-dev" description="Deploy the app to dev Tomcat">
<tomcat-deploy base-url="${url.base.dev}"/>
</target>
<target name="undeploy-local" depends="stop-local" description="Undeploy the app from local Tomcat">
<tomcat-undeploy base-url="${url.base.local}"/>
</target>
<target name="undeploy-dev" depends="stop-dev" description="Undeploy the app from dev Tomcat">
<tomcat-undeploy base-url="${url.base.dev}"/>
</target>
<target name="stop-local" description="Stop the app on local Tomcat">
<tomcat-stop base-url="${url.base.local}"/>
</target>
<target name="stop-dev" description="Stop the app on dev Tomcat">
<tomcat-stop base-url="${url.base.dev}"/>
</target>
<macrodef name="tomcat-deploy">
<attribute name="base-url"/>
<sequential>
<echo>Deploying app to: #{base-url}</echo>
<deploy url="#{base-url}/manager/text" username="${username}" password="${password}"
path="/${app.name}" war="file:${war.path}.war"/>
</sequential>
</macrodef>
<macrodef name="tomcat-undeploy">
<attribute name="base-url"/>
<sequential>
<echo>Un-deploying app from: #{base-url}</echo>
<undeploy
failonerror="no"
url="#{base-url}/manager/text"
username="${username}"
password="${password}"
path="/${app.name}"
/>
</sequential>
</macrodef>
<macrodef name="tomcat-stop">
<attribute name="base-url"/>
<sequential>
<echo>Stopping the app at: #{base-url}</echo>
<stop url="#{base-url}/manager/text" username="${username}"
password="${password}" path="/${app.name}" />
</sequential>
</macrodef>
Anyone have any idea why the deploy to remote works but still returns an error? The error I get is kind of vague so I don't know what I could do to debug it.
The problem was the server was taking too long to deploy the app. Somewhere the Tomcat Deploy target is waiting for a response from the server saying the app was deployed. Unfortunately the only error is the 500 and there is nothing else to go on.
The solution, I simply re-installed Tomcat with Version 9, up from 8, and everything turned on much faster and the build was successful.
I can't really say this is the best answer but I got everything working.Hopefully someone has a better solution one day.
I am writing an ant task which uses below code :
public class Klazz extends Task{
public void execute() throws BuildException{
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.get("file:///C:/sample/alltests-fails.html");
}
In eclipse the project named is "test-project" and used "libs" folder which contains the jars (ant.jar, selenium-server-standalone-2.44.0.jar) to be added in the classpath . If I run the code in Eclipse its working fine but while running as an ant task it throws java.lang.ExceptionInInitializerError . Below is the build.xml snippet to create the jar(named custom-task.jar) file which needs to be put in the %ant_home%\lib folder.
<target name="jar" depends="compile" >
<mkdir dir="build/jar" />
<jar destfile="${env.ANT_HOME}/lib/custom-task.jar">
<fileset dir="build/classes" />
<restrict>
<name name="**/*.class" />
<archives>
<zips>
<fileset dir="${basedir}/libs/" includes="**/*.jar" />
</zips>
</archives>
</restrict>
</jar>
</target>
May be the external jars/classes not added properly in the class path while creating the jar through the "jar" task above, resulting some missing class files causing the ExceptionInInitializerError.
Advance thanks for any help on this .
below is the stack trace :
java.lang.ExceptionInInitializerError
at org.cyberneko.html.HTMLScanner.scanEntityRef(HTMLScanner.java:1415)
at org.cyberneko.html.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2
059)
at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:920)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:499
)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:452
)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.pars
e(HTMLParser.java:926)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:2
45)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.ja
va:191)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(Defau
ltPageCreator.java:268)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPa
geCreator.java:156)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient
.java:455)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:329)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:394)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:4
77)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:4
66)
at mypkg.Klazz.execute(Klazz.java:15)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.jav
a: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(DefaultExe
cutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
at org.apache.tools.ant.Main.runBuild(Main.java:851)
at org.apache.tools.ant.Main.startAnt(Main.java:235)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at org.cyberneko.html.HTMLEntities.load0(HTMLEntities.java:101)
at org.cyberneko.html.HTMLEntities.<clinit>(HTMLEntities.java:53)
... 33 more
Total time: 2 seconds
Should there have been any class loading difficulties, I would assume a NoClassDefFoundError or a ClassNotFoundException would occur
The ExceptionInInitializerError is usually not what should draw attention, because it only says "Hey, programmer, an exception happened inside an initialization block"
More about initialization blocks here
Therefore, dealing with the NPE will fix the issue, but unfortunately I've no access to the code that could've caused this. Let me know and I shall edit the answer.
#Vlad Ilie thanks for having a look , its solved now.. the problem is with jar creation ant script .
The earlier ant task for the jar creation is not able to club all the jars in the class path and resulting... classnotfoundexception which in turn caused the ExceptionInInitializerError and NullPointerException .
Below is the fixed "jar" task which is successfully able to add all the jars in the class path .
<target name="jar" depends="compile">
<jar destfile="${env.ANT_HOME}/lib/custom-task.jar" basedir="build/classes" >
<zipgroupfileset dir="${basedir}/libs/" includes="*.jar"/>
</jar>
</target>
Above I used zipgroupfileset which is very handy .
I have the following project directory structure:
MyProject/
src/main/java/
All of my Java sources
build/
build.xml
build.properties
ivy.xml
ivy-settings.xml
ivy-settings.properties
The build.xml looks like this:
<project name="MyProject" default="audit" basedir=".." xmlns:ivy="antlib:org.apache.ivy.ant">
<property file="build/build.properties"/>
<property environment="env"/>
<path id="ant.lib.path">
<fileset dir="${env.ANT_HOME}/lib" includes="*.jar"/>
</path>
<taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ant.lib.path"/>
<target name="configIvy">
<echo message="Configuring Ivy."/>
<echo message="URL is: ${ivy.settings.home}"/>
<ivy:settings url="${ivy.settings.home}"/>
<!-- Clear/flush the Ivy cache. -->
<echo message="Cleaning the local Ivy cache for the current build."/>
<ivy:cleancache/>
</target>
</project>
When I run ant -buildfile /<path-to-my-project>/MyProject/build/build.xml configIvy, I get the following console output:
Buildfile: /<path-to-my-project>/MyProject/build/build.xml
configIvy:
[echo] Configuring Ivy.
[echo] URL is: file:////<path-to-my-project>/MyProject/build/ivy-settings.xml
[ivy:cleancache] :: Apache Ivy 2.3.0-rc1 - 20120416000235 :: http://ant.apache.org/ivy/ ::
BUILD FAILED
/<path-to-my-project>/MyProject/build/build.xml:85: java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.apache.ivy.util.url.URLHandlerRegistry.getHttp(URLHandlerRegistry.java:47)
at org.apache.ivy.ant.IvyAntSettings.configureURLHandler(IvyAntSettings.java:367)
at org.apache.ivy.ant.IvyAntSettings.createIvyEngine(IvyAntSettings.java:267)
at org.apache.ivy.ant.IvyAntSettings.getConfiguredIvyInstance(IvyAntSettings.java:237)
at org.apache.ivy.ant.IvyTask.getIvyInstance(IvyTask.java:92)
at org.apache.ivy.ant.IvyTask.prepareTask(IvyTask.java:256)
at org.apache.ivy.ant.IvyTask.execute(IvyTask.java:276)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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:392)
at org.apache.tools.ant.Target.performTasks(Target.java:413)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
at org.apache.tools.ant.Main.runBuild(Main.java:811)
at org.apache.tools.ant.Main.startAnt(Main.java:217)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
Caused by: java.lang.NullPointerException
at org.apache.log4j.Category.isDebugEnabled(Category.java:129)
at org.apache.commons.logging.impl.Log4JLogger.isDebugEnabled(Log4JLogger.java:239)
at org.apache.commons.httpclient.HttpClient.<clinit>(HttpClient.java:69)
... 25 more
My ivy-settings.xml file specifies a URL resolver of an Artifactory repo that is hosted on my local machine (http://localhost:8080/artifactory/myrepo). I'm wondering if Ivy uses HttpClient under the hood (as the stacktrace suggests), and for some reason, is choking because its an HTTP URL on the same machine? Maybe?!? And yes, I'm sure that the URL is correct and that Artifactory is running while I run the Ant build!
Can anyone spot what is going on here? Why would <ivy-cleancache> throw a NPE? I'm looking at its source code and can't seem to find where the NPE is coming from, or why. I can supply more details if needed. Thanks in advance!
I thought I gave a response to this, but I don't see it here...
Don't put extra jars for your projects into $ANT_HOME/lib. There are several reasons for this:
As you've found out, there can be jar clash as each set of optional tasks tries to setup the classpath they need. Yes, it's nice not having to set a classpath when you do a <taskdef>, but it's not that bad.
If you give your project to someone else, they'll have to install all of the optional jars too before they can do a build.
The better way is to create a ${basedir}/ant.lib directory, and then put each set of ant task jars in their own sub-directory. For example, you'd put Ivy jars in ${basedir}/ant.lib/ivy and you put Checkstyle jars in ${basedir}/ant.lib/checkstyle. Then, you define your taskdef with a classpath pointing to the directory like this:
<taskdef resource="org/apache/ivy/ant/antlib.xml"
uri="antlib:org.apache.ivy.ant">
<classpath>
<fileset dir="${basedir}/lib/ivy"/>
</classpath>
</taskdef>
This way, Ivy doesn't pick up the wrong jars. As a bonus, you can also give someone your project, and Ivy is already installed and running for them. No need for them to download Ivy and setup the jar in the right classpath.
By the way, $ANT_HOME/lib is already in the Ant classpath, so if you didn't specify a classpath, all the jars in $ANT_HOME/lib will be picked up automatically. You could have simply done this:
<taskdef resource="org/apache/ivy/ant/antlib.xml"
uri="antlib:org.apache.ivy.ant"/>
with no classpath required.
I have some trouble with getting a Java application to run in the console and/or with Ant.
I know that a lot of starting issues are related to the classpath being not set or incorrectly set, though I'm fairly sure I set it correctly, so my search only yielded results on that.
Here is the general setup of my application:
classes are in packages model, view and controller. controller.Controller is the class with the main method. I am using objectdb as my JPA provider.
I am using Ant to compile my application.
After compiling, I can run my application from ant with the following script:
<target name="run" description="default build process">
<java fork="true" classname="${main-class}">
<classpath>
<path refid="classpath" />
</classpath>
</java>
</target>
where ${main-class} is controller.Controller and classpath consists of /lib and /dist folders (the application's jar file is compiled to /dist)
Now I tried copying all .jar files from /lib and /dist to one separate folder and run them withjava -jar cooking.jar -cp . which results in
Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/Persistence
at model.jpa.JPAModelFactory.<init>(JPAModelFactory.java:28)
at model.jpa.JPAModelFactory.<init>(JPAModelFactory.java:24)
at controller.Controller.<init>(Controller.java:59)
at controller.Controller.main(Controller.java:116)
Caused by: java.lang.ClassNotFoundException: javax.persistence.Persistence
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more
So I tried ant and slightly modified above build target to:
<target name="run2" description="default build process">
<java fork="true" jar="${dist.dir}/${ant.project.name}.jar">
<classpath>
<path refid="classpath" />
</classpath>
</java>
</target>
which results in the same error. I don't understand why.
Just to test it, I tried running from the command line by specifying the main class directly: java -cp . controller.Controller which for some reason cannot even locate the class (it's there, I confirmed it):
Exception in thread "main" java.lang.NoClassDefFoundError: controller/Controller
Caused by: java.lang.ClassNotFoundException: controller.Controller
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: controller.Controller. Program will exit.
I have set JAVA_HOME to my JDK's path, and CLASSPATH to my JRE's/lib path.
OS is Windows 7 64 bit, Java version is 1.6.0_25-b06
I am puzzled by two things:
a) Why is Java unable to locate controller.Controller, even though it is present in the .jar file and the .jar file is in the current directory?
b) What am I doing wrong that calling Java with -jar seems to mess up the lookup mechanisms.
Any help is highly appreciated.
The class path should consist of
directories with class files (in their proper package directory)
jar files.
You cannot point the class path to a directory of jars. Things are different when running a application server (eg Tomcat), which will load jars from a directory for you.
though I'm fairly sure I set it correctly
The evidence is against you. The JVM is telling you that you have not set it correctly.
What do you think that ref 'classpath' pointing to? Where do you assume its values are coming from? They should be defined inside the Ant build.xml, right? Like this:
<path id="production.class.path">
<pathelement location="${production.classes}"/>
<pathelement location="${production.resources}"/>
<fileset dir="${production.lib}">
<include name="**/*.jar"/>
<exclude name="**/junit*.jar"/>
<exclude name="**/*test*.jar"/>
</fileset>
</path>
<path id="test.class.path">
<path refid="production.class.path"/>
<pathelement location="${test.classes}"/>
<pathelement location="${test.resources}"/>
<fileset dir="${test.lib}">
<include name="**/junit*.jar"/>
<include name="**/*test*.jar"/>
</fileset>
</path>
If you're creating an executable JAR, you need to specify the main class and classpath in the manifest, as CoolBeans correctly pointed out in the comment. The 3rd party JAR locations have to be relative to the executable JAR. You should package them with your executable JAR in such a way that the relative path is easy to sort out and understand.
I've found this happens when I specify both the <classpath> and the jar="..." in the target. I removed the jar="...", placed that .jar into the <classpath> list and it ran after that.
I am trying to compile and run a simple java class within eclipse. The compile task works fine, and since I do not specify a destination folder the build files are in the same directory as the source. Which is alright, at the moment all I need is to learn how I can run the class with the main() method.
I have tried using the fully qualified name of the class (with package name, etc) and the classname alone, but always I get a java.lang.ClassNotFoundException
Buildfile: C:\Users....\build.xml
run:
[java] java.lang.NoClassDefFoundError: code/control/MyClass
[java] Caused by: java.lang.ClassNotFoundException: code.control.MyClass
[java] at java.net.URLClassLoader$1.run(Unknown Source)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClass(Unknown Source)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClassInternal(Unknown Source)
[java] Could not find the main class: code.control.MyClass. Program will exit.
[java] Exception in thread "main"
[java] Java Result: 1
compile:
default:
BUILD SUCCESSFUL
Total time: 234 milliseconds
Below, are the targets taken from my build.xml file:
<target name="default" depends="compile" description="learn">
</target>
<target name="compile" depends="run">
<javac srcdir="src/" />
</target>
<target name="run">
<java classname="code.control.MyClass" fork="true"/>
</target>
I can't figure out why the class is not found. MyClass contains the main() method and since i specify no classpath it should look at the current directory, which is the src/ right?
The development directory is the usual eclipse file structure:
projectName/src/code/control/MyClass
If it is a classpath problem how could I resolve it? I always had problem grasping the concept "put it on your classpath" ... If someone could provide a little bit of explanation with the classpath in the ant context, I would be very thankful.
Thanks for any help on this. The version of ant is 1.7.0
The classpath is where the Java runtime looks for your .class files, similar to how your OS uses the PATH variable to find executables.
Try this in your build script:
<target name="run">
<java fork="true" classname="code.control.MyClass">
<classpath>
<path location="src/"/>
</classpath>
</java>
There's a HelloWorld version for ant that walks through building a Java program with ant.
you should include classpath, e.g.
<java classpath="${bin}" classname="code.control.MyClass">
where ${bin} is your output folder.
change your build.xml as below and try out:
<target name="default" depends="run" description="learn">
</target>
<target name="compile" >
<javac srcdir="src/" />
</target>
<target name="run" depends="compile">
<java classname="code.control.MyClass" fork="true"/>
</target>