Ant Error when invoking it inside Eclipse - java

I have tried invoking Ant programmatically, but I am encountering this error
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/tools/ant/launch/AntMain
I tried to run build.xml separately using the console and via right-clicking it in eclipse running as ant build. It runs with no problems.
My sample ant testing class
public class AntTest {
public static void main(String[] args) {
File buildFile = new File("build.xml");
Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
p.executeTarget(p.getDefaultTarget());
}
}
My sample build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="testproject" default="test" basedir=".">
<target name="test">
<echo message="Hello World" />
</target>
</project>
What am I missing?

Make sure that the ant libraries are in your classpath.
It seems, that ant-launcher-VERSION.jar (where Version is the ant version you are using) is missing in your classpath.

Related

Set project ant classpath programatically

I'm working on a Java project that exec Ant target task on runtime.
On my pom file I have this dependency:
pom.xml
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>${ant.version}</version>
</dependency>
I have to run <scp> task that is included in a target container task (called scp-test-target).
Below you can see the ant file:
deploy.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="test" basedir="./">
<target name="scp-test-target" description="scp desc">
<echo message="Test SCP"/>
<scp file="..." todir="..."/>
</target>
</project>
I have created a junit file to exec 'scp-test-target':
Test.java
#Test
public void testAnt1(){
Project antProject = new Project();
ProjectHelper projectHelper = ProjectHelper.getProjectHelper();
antProject.addReference("ant.projectHelper", projectHelper);
antProject.setUserProperty("ant.file", "deploy.xml");
antProject.fireBuildStarted();
antProject.init();
projectHelper.parse(antProject, new File("deploy.xml"));
antProject.executeTarget("scp-test-target");
antProject.fireBuildFinished(null);
}
But when I run my junit test, the program failed because it not find jsch library.
Problem: failed to create task or type scp
Cause: the class org.apache.tools.ant.taskdefs.optional.ssh.Scp was not found.
This looks like one of Ant's optional components.
So, how can I tell to Ant to link jsch libraries on my file system in programmatically way (so in my Test.java)?
Thanks in advance

NoClassDefFoundError: org/netbeans/lib/awtextra/AbsoluteLayout Wrapping Problem Launch4j

I'm getting an error when I try to wrap the Jar to exe through Launch4j.
I have added the library already in the NetBeans IDE and also for the Project but still the error persists.
The Jar is running without any problems but when I try to wrap it, I'm getting always that issue warning:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/netbeans/lib/awtextra/AbsoluteLayout
....
....
Caused by: java.lang.ClassNotFoundException: org.netbeans.lib.awtextra.AbsoluteLayout
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)
... 17 more
How can I resolve this?
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="HelaTergo" default="default" basedir=".">
<description>Builds, tests, and runs the project HelaTergo.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="HelaTergo-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>
CSS:
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Class-Path: lib/AbsoluteLayout.jar
HTML:
<?xml version="1.0" encoding="UTF-8"?>
<launch4jConfig>
<dontWrapJar>false</dontWrapJar>
<headerType>gui</headerType>
<jar>C:\Users\ckoca\Documents\NetBeansProjects\HelaTergo\dist\HelaTergo.jar</jar>
<outfile>C:\Users\ckoca\OneDrive - COMPUTACENTER\Desktop\SerkoBib.exe</outfile>
<errTitle>Bitte Java vorerst installieren</errTitle>
<cmdLine></cmdLine>
<chdir>.</chdir>
<priority>normal</priority>
<downloadUrl>http://java.com/download</downloadUrl>
<supportUrl></supportUrl>
<stayAlive>false</stayAlive>
<restartOnCrash>false</restartOnCrash>
<manifest></manifest>
<icon>C:\Users\ckoca\Documents\Icons\Icons8-Windows-8-Business-Department.ico</icon>
<classPath>
<mainClass>helaTergo.HomeHelaTergo</mainClass>
<cp>lib/AbsoluteLayout.jar</cp>
</classPath>
<jre>
<path></path>
<bundledJre64Bit>false</bundledJre64Bit>
<bundledJreAsFallback>false</bundledJreAsFallback>
<minVersion>1.6.0</minVersion>
<maxVersion></maxVersion>
<jdkPreference>preferJre</jdkPreference>
<runtimeBits>64/32</runtimeBits>
</jre>
<versionInfo>
<fileVersion>1.0.0.0</fileVersion>
<txtFileVersion>1.0.0.0</txtFileVersion>
<fileDescription>Serko Library Software</fileDescription>
<copyright>Computacenter</copyright>
<productVersion>1.0.0.0</productVersion>
<txtProductVersion>1.0.0.0</txtProductVersion>
<productName>SerkoBib</productName>
<companyName>Computacenter</companyName>
<internalName>SerkoBib</internalName>
<originalFilename>SerkoBib.exe</originalFilename>
<trademarks></trademarks>
<language>ENGLISH_US</language>
</versionInfo>
</launch4jConfig>

execute jar error could not find or load main class

sorry for another "could not find or load main class" question.
I'm new to Java. I searched for a while but couldn't find the reason.
My project is a very simple one created with maven.
mvn archetype:generate -DgroupId=mycompany -DartifactId=faker -DinteractiveMode=false
pom.xml(default, not change)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mycompany</groupId>
<artifactId>faker</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>faker</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
and source code(default, not change)
package mycompany;
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World!" );
}
}
I build jar file with jar command.
~$ jar cvfm MyCompany.jar manifest.txt src/main/java/mycompany/App.java
# added manifest
# adding: src/main/java/mycompany/App.java(in = 705) (out= 352)(deflated 50%)
manifest.txt
~$ cat manifest.txt
Main-Class: mycompany.App
# (has an empty new line here)
but whenever I executed it, it give me following error:
~$ java -jar MyCompany.jar
Error: Could not find or load main class mycompany.App
Where is wrong ?
openjdk version "1.8.0_181"
Apache Maven 3.5.2
Thanks #ohlec and #Kayaman, to be more specific, here's the way to solve it.
# get App.class
~$ cd src/main/java/mycompany/ && javac App.java
# back to faker folder
~$ jar cvfm MyCompany.jar manifest.txt -C src/main/java mycompany/App.class
~$ java -jar MyCompany.jar
# Hello World!
Your jar should have a directory structure that mirrors the package structure; in your case, src/main/java is included, although that is not a package prefix. Use -C to specify the root directory:
jar cvfm MyCompany.jar manifest.txt -C target mycompany/App.class
Edit: Also, as Kayaman pointed out, you need to include the .class file, not the .java file.

JavaFX application fail to launch with native exe bundle

I have build a JavaFX application which can be executed by its jar file. However if i try to run it using the native exe bundle i am receiving two popups:
com/npap/dicomrouter/Main - no main class
failed to launch JVM
and the application fails to start.
This is my Main class (most of its part):
package com.npap.dicomrouter;
public class Main extends Application {
...
public static void main(String[] args) throws IOException {
try {
JUnique.acquireLock(appId);
alreadyRunning = false;
log.info("application is going to start running!!!!");
} catch (AlreadyLockedException e) {
alreadyRunning = true;
log.info("application is already running!!!!");
}
if (!alreadyRunning) {
Application.launch(Main.class, (java.lang
.String[])null);
}
}
#Override
public void start(Stage primaryStage) throws IOException {
...
try {
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("FXMLDocument.fxml"));
Scene scene = new Scene(page, initWidth, initHeight);
primaryStage.setScene(scene);
Platform.setImplicitExit(false);
createTrayIcon(primaryStage);
primaryStage.setTitle(appTitle);
primaryStage.show();
} catch (IOException ex) {
log.log(Level.INFO, null, ex);
}
}
My build.xml is configured this way:
<target name="-post-jfx-deploy">
<fx:deploy width="${javafx.run.width}" height="${javafx.run.height}"
nativeBundles="all"
outdir="${basedir}/${dist.dir}" outfile="${application.title}">
<fx:application name="${application.title}"
mainClass="${javafx.main.class}"/>
<fx:resources>
<fx:fileset dir="${basedir}/${dist.dir}"
includes="*.jar"/>
</fx:resources>
<fx:info title="${application.title}"
vendor="${application.vendor}"/>
</fx:deploy>
</target>
I am building the application (Java FX 2.1) using Netbeans, in the way described here:
https://netbeans.org/kb/docs/java/native_pkg.html
and i have succesfully build and run other javafx applications with native exe bundle. I am also attaching a screenshot showing how i declare the main project's class.
So i profoundly assume that this is a project specific issue. During the build in the console i get:
The jar lib\hibernate-commons-annotations-4.0.2.Final.jar has a main class org.hibernate.annotations.common.Version that does not match the declared main com.xxxx.yyyy.Main
The jar lib\javassist-3.15.0-GA.jar has a main class javassist.CtClass that does not match the declared main com.xxxx.yyyy.Main
The jar lib\h2-1.3.176.jar has a main class org.h2.tools.Console that does not match the declared main com.xxxx.yyyy.Main
Apart from these jars, i use several other classes which contain "main" methods (are runnable).
#SuppressWarnings("unchecked")
public static void main(String args[]) throws Exception {
...
Most of them are 3-rd party utility classes.
I am also adding the contents of package.cfg file just FYI:
app.mainjar=DicomRouterAffidea0_2_2.jar
app.version=1.0
app.id=com.npap.dicomrouter
app.preferences.id=com/npap/dicomrouter
app.mainclass=com/npap/dicomrouter/Main
app.classpath=lib/antlr-2.7.7.jar lib/c3p0-0.9.2.1.jar lib/clibwrapper_jiio.jar .....
... //jars listing
Finally i am attaching 3 screenshots of Libraries, Compiling and Deployment Netbeans configuration. Hope that can also help:
Just answering my question since after some trials i managed to build a functional .exe file by removing the code from build.xml.
So i removed all these lines from build.xml:
<target name="-post-jfx-deploy">
<fx:deploy width="${javafx.run.width}" height="${javafx.run.height}"
nativeBundles="all"
outdir="${basedir}/${dist.dir}" outfile="${application.title}">
<fx:application name="${application.title}"
mainClass="${javafx.main.class}"/>
<fx:resources>
<fx:fileset dir="${basedir}/${dist.dir}"
includes="*.jar"/>
</fx:resources>
<fx:info title="${application.title}"
vendor="${application.vendor}"/>
</fx:deploy>
and i am just importing:
<import file="nbproject/build-impl.xml"/>

Error in a build.xml when using ANT

I write a java package, and I want to compile it into .class files first and then package it. Following codes are what I do in my ant script. Under the directory of "src/compressScript" are four java class I wrote.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><project basedir="."default="compileJava" name="compileJava">
<target name="compileJava">
<mkdir dir="buildTest"/>
<javac includeantruntime="false" srcdir="src/compressScript" destdir="buildTest"/>
</target>
</project>
When I try to use javac task of ANT to run this scirpt, the error is like this:
Buildfile: C:\Users\di_yu\workspace\AffirmedNetworks\buildTest.xml
compileJava:
BUILD FAILED
C:\Users\di_yu\workspace\AffirmedNetworks\buildTest.xml:6:java.lang.UnsupportedClassVersionError: com/sun/tools/javac/Main : Unsupported major.minor version 52.0
Total time: 545 milliseconds
I check my compiler, the installed JRE is JRE 7.0 and the compiler compliance level is 1.7. So what's the problem?

Categories