Java- export to jar- i/o problems - java

I work on Eclipse (Juno with JDK7), and the program runs (on Eclipse) fine.
My problematic lines are:
URL imageURL = new URL("http://www.idautomation.com/ocr-a-and-ocr-b-fonts/new_sizes_ocr.png");
RenderedImage img = ImageIO.read(imageURL);
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);
But when i export the project to a jar file and try to run it via windows (7- 64 bit) command line, the following error appears:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.util.ServiceConfigurationError: javax.imageio.spi.ImageReaderSpi: Providercom.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReaderSpi could not be instantiated: java.lang.IllegalArgumentException: vendorName == null!
at java.util.ServiceLoader.fail(Unknown Source)
at java.util.ServiceLoader.access$100(Unknown Source)
at java.util.ServiceLoader$LazyIterator.next(Unknown Source)
at java.util.ServiceLoader$1.next(Unknown Source)
at javax.imageio.spi.IIORegistry.registerApplicationClasspathSpis(Unknow
n Source)
at javax.imageio.spi.IIORegistry.<init>(Unknown Source)
at javax.imageio.spi.IIORegistry.getDefaultInstance(Unknown Source)
at javax.imageio.ImageIO.<clinit>(Unknown Source)
at SimpleQueueServiceSample.testOCR(SimpleQueueServiceSample.java:75)
at SimpleQueueServiceSample.main(SimpleQueueServiceSample.java:69)
... 5 more
Caused by: java.lang.IllegalArgumentException: vendorName == null!
at javax.imageio.spi.IIOServiceProvider.<init>(Unknown Source)
at javax.imageio.spi.ImageReaderWriterSpi.<init>(Unknown Source)
at javax.imageio.spi.ImageReaderSpi.<init>(Unknown Source)
at com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReaderSpi.<init>(CLibJPEGImageReaderSpi.java:80)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
... 13 more
I also using that imports:
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
Please, someone know the problem?
Thanks in advance!

If you export using "Runnable JAR file" then Eclipse will add a custom ClassLoader and a custom main class into the jar file.
On the same time it seems you have installed some Image-IO extensions into the JDK - something providing the class CLibJPEGImageReaderSpi. On my system (Ubuntu, JDK 1.7) there is no such class but JPEGImageReaderSpi. The CLib part makes me think, that you have installed a native library doing the JPEG reading.
These two parts together seem to make the trouble. Solution - Try to export as a simple jar, start by hand providing the classpath on the commandline. If that works, provide a shell wrapper providing the classpath for easier use.
EDIT Googling around I have found an article with exactly that problem:
https://www.java.net//node/695773

I guess I can provide another solution as to this question since I got this error a few days ago and finally solve it.
You can check this article first, here explained the reason: Exception when trying to save images
==> To sum up, the required META-INF the jar need to use is missing, so it can't find the "vender-Name" in the MANIFEST.MF.
As a result, I use MAVEN to generate the required runnable jar instead of using Eclipse to generate it. How? You can write a pom.xml to achieve it and remember to use "maven-assembly-plugin" to generate the required MANIFEST.MF in the jar file. This is the key step. And I can also give you a sample(pom.xml) for it:
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xxxProject</groupId>
<artifactId>xxxProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>Sonatype Snapshot Repository</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.demo.Main</mainClass>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
<manifestEntries>
<Specification-Vendor>Sun Microsystems, Inc.</Specification-Vendor>
<Implementation-Vendor>Sun Microsystems, Inc.</Implementation-Vendor>
</manifestEntries>
</archive>
</configuration>
<executions>
<execution>
<id>create-my-bundle</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
</dependencies>
So, the most important part is:
<manifestEntries>
<Specification-Vendor>Sun Microsystems, Inc.</Specification-Vendor>
<Implementation-Vendor>Sun Microsystems, Inc.</Implementation-Vendor>
</manifestEntries>
That means maven will add the required META-INFO for you in the jar so that you can solve this issue.
That's it. Hope these info can help you. =)

Related

MigLayout ClassNotFoundException when creating maven jar

I'm trying to create a jar file of my simple java gui application. I'm using Intellij IDEA and maven.
I have imported Mig Layout as a maven dependency, when I run the program inside Intellij IDEA everything works fine, but when I create a jar by doing mvn clean install or mvn clean package, although maven says BUILD SUCCESSFUL, when I try to open the jar file I get the following Stacktrace (I believe it's a stack trace). The image Stacktrace
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: net/miginfocom/swing/MigLayout at BotGui.<init>(BotGui.java:29) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: net.miginfocom.swing.MigLayout 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) ... 15 more
this is my dependencies in maven.
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ptcontact.testdiscord</groupId>
<artifactId>Discord_Bot</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.miglayout</groupId>
<artifactId>miglayout-swing</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>3.8.0_436</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jcenter</id>
<name>jcenter-bintray</name>
<url>https://jcenter.bintray.com</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<target>8</target>
<source>8</source>
</configuration>
</plugin>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>BotGui</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
</plugins>
</build>
</project>
Yes I have tried out version 5.0, 4.2 and 5.2.
Additionally, I have tried to add miglayout-core as a dependency as well, but that didn't change anything.
I Resolved the problem!
Like #CrazyCoder said, I needed to create a Fat Jar, in other words I needed to actually include the dependencies inside my jar file. Because I'm a beginner I thought that maven did that for you automatically, oh well.
To create a fat jar, I followed this guide:
http://tutorials.jenkov.com/maven/maven-build-fat-jar.html

Exception in thread "main" java.lang.NoClassDefFoundError: when running with console. Possibly Maven-related

I have 2 java files:
package com.pokebot;
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
public class App {
public static void main(String[] args)
{
try {
JDA jdaBot = new JDABuilder(AccountType.BOT).setToken("my_token").buildBlocking();
jdaBot.addEventListener(new Pokebot());
} catch (LoginException e) {
// System.out.println("LoginException");
} catch (InterruptedException e) {
// System.out.println("InterruptedException");
} catch (RateLimitedException e) {
// System.out.println("RateLimitedException");
}
}
}
and:
package com.pokebot;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class Pokebot extends ListenerAdapter {
#Override
public void onMessageReceived(MessageReceivedEvent e) {
//Obtains properties of the received message
Message objMsg = e.getMessage();
MessageChannel objChannel = e.getChannel();
User objUser = e.getAuthor();
//Responds to any user who says "hello"
if (objMsg.getContent().equals("hello")) {
objChannel.sendMessage("Hello, " + objUser.getAsMention() +"!").queue();
}
}
}
When I run the application (the main class is App from 1st file) from Netbeans, I get only one notice:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
but the application still works.
When I try to run it from command line:
java -jar target/pokebotapp-1.0-SNAPSHOT.jar
then I get an exception like this:
Exception in thread "main" java.lang.NoClassDefFoundError: net/dv8tion/jda/core/exceptions/RateLimitedException
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: net/dv8tion/jda/core/
exceptions/RateLimitedException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetMethodRecursive(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: net.dv8tion.jda.core.exceptions.Rat
eLimitedException
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)
... 7 more
And the application does not even start.
I'm using Maven for this project. My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pokebot</groupId>
<artifactId>pokebotapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<!--<classpathPrefix>lib/</classpathPrefix>-->
<mainClass>com.pokebot.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/dependency-jars/
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>3.3.1_291</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jcenter</id>
<name>jcenter-bintray</name>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
</project>
Before I try to run the project from the console, i run maven compile. I think it might possibly be the fault of the way I run the program, or the way I set up maven for this project. Is there anyone that knows what can be the problem?
That's because java doesn't know where to take this libs from. Few options:
Construct jar with all your dependencies included (so called uber-jar). This is done with maven shade plugin. Docs are available here: https://maven.apache.org/components/plugins/maven-shade-plugin/examples/executable-jar.html
Do java -jar -cp
Docs are here: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
First option is definitely better :) I guess there should be plenty of examples on stackoverflow how to configure maven-shade-plugin. Like this:
What is the maven-shade-plugin used for, and why would you want to relocate java packages?
With gradle
This can be fixed by using the shadow plugin and building your jar with shadowJar instead. The jar will then be present in the build/libs directory with a name like example-1.0-all.jar
With Maven
You need the shade plugin in your pom to add dependencies to your package task. You can see the shade plugin being applied in this example pom.xml
From https://jda.wiki/using-jda/troubleshooting/

Maven not finding apache RandomStringGenerator

I am trying to use the new Apache Commons Text new random string generator, but I can't find any usage on the Internet on how to properly import it. Maven builds successfully, but when I try to run my jar file from the command line with the following command
java -cp target/my-app-1.0.jar com.mycompany.app.App
…I get the below error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/text/RandomStringGenerator$Builder
at com.mycompany.app.App.main(App.java:8)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.text.RandomStringGenerator$Builder
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)
... 1 more
I also have this warning during the build:
The POM for org.apache.commons:commons-text:jar:1.1 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more detail
Here is the Maven debug version:
[WARNING] The POM for org.apache.commons:commons-text:jar:1.1 is invalid, transitive dependencies (if any) will not be available: 1 problem was encountered while building the effective model
[FATAL] Non-parseable POM C:\Users\me\.m2\repository\org\apache\commons\commons-text\1.1\commons-text-1.1.pom: only whitespace content allowed before start tag and not a (position: START_DOCUMENT seen a... #1:1) # line 1, column 1
Here is my App.java code:
package com.mycompany.app;
import org.apache.commons.text.RandomStringGenerator;
public class App {
public static void main(String[] args) {
// Generates a 20 code point string, using only the letters a-z
RandomStringGenerator generator = new RandomStringGenerator.Builder()
.withinRange('a', 'z').build();
String randomLetters = generator.generate(20);
System.out.println( randomLetters );
}
}
Here is my pom.xml:
<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>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>my-app</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
If you want to run you application from a jar, you will need an exploded jar. The default class loader will not find the apache jar from your jar.
You can use the shade plugin to create an exploded jar. Add something like below to your pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.mycompany.app.App</Main-Class>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Then, you can run with the following:
java -jar target/my-app-1.0.jar

Running .jar file using Apache POI in Maven project

I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:
My pom.xml looks like this:
<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>com.mycompany.app</groupId>
<artifactId>calendar</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>calendar</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
</dependencies>
</project>
From what I can tell, my dependencies are alright.
This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:
public class App
{
private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";
public static void main( String[] args ) throws IOException
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
Object[][] datatypes = {
{"Datatype", "Type", "Size(in bytes)"},
{"int", "Primitive", 2},
{"float", "Primitive", 4},
{"double", "Primitive", 8},
{"char", "Primitive", 1},
{"String", "Non-Primitive", "No fixed size"}
};
int rowNum = 0;
System.out.println("Creating excel");
for(Object[] datatype : datatypes) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for(Object field : datatype) {
Cell cell = row.createCell(colNum++);
if(field instanceof String) {
cell.setCellValue((String) field);
}
else if(field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
//workbook.close()
} catch (FileNotFoundException e) {
System.out.println("Couldn't find file to write out to");
} catch (IOException e) {
System.out.println("IO Exception in printing");
}
}
}
I have workbook.close() commented out since this caused an error (deprecated method?).
With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.
I am attempting to run this file using
java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App
...and I get the following error message
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetMethodRecursive(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
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)
... 7 more
If this question requires any more information let me know. I'm at a loss here.
You need to create a fat/uber jar with Maven Assembly Plugin. Which means create a Jar together with its dependency Jars into a single executable Jar file. When you run it then it would have all the dependencies available.
Add following plugin inside your POM
<build>
<plugins>
<!-- Maven Assembly Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<!-- get all project dependencies -->
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<!-- MainClass in mainfest make a executable jar -->
<archive>
<manifest>
<mainClass>com.your.path.to.main.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<!-- bind to the packaging phase -->
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Run following:
mvn package
Two jar files will be created in the target folder.
calendar-1.0-SNAPSHOT.jar – Only your project classes
calendar-1.0-SNAPSHOT-with-dependencies.jar – Project and dependency classes in a single jar.
You can run it follwoing;
java -cp target/calendar-1.0-SNAPSHOT-with-dependencies.jarcom.mycompany.app.App
You can review the contents of calendar-1.0-SNAPSHOT-with-dependencies.jar
jar tf target/calendar-1.0-SNAPSHOT-with-dependencies.jar
You are packaging your maven artifact as a jar and by default a jar packaged by the maven jar plugin doesn't include the dependency jars with the built artifact.
Whereas the missing class at runtime.
If you want to include dependency jars of your application inside your jar, you should use the maven assembly plugin and specify jar-with-dependencies for the descriptorRef parameter.
You could bind the assembly singlegoal execution to the package phase so that the mvn package execution that you are using actually creates automatically the expected jar.
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>YourMainClassPrefixedByItsPackage</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
The problem is that at compile time POI libraries are available but not at run time. The reason why they are available is that they are in Maven Dependency. Also I don't see any build wrapper in your pom file. You will need to add a build wrapper to build jar file that you can run outside of your IDE.
Now coming back to your problem, either you need to add POI jar in your CLASSPATH environment variable so that java run-time can access it or build a fat jar including dependencies.
You can use this template to add a build wrapper in pom file to build jar with dependencies.
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Maven package task just packs compiled classes of your project into a single jar file. All 3rd party libraries are not included, that's why you're getting error - POI class is not found.
You should build a runnable jar file that includes all dependencies. Please, refer to this question - you should use some additional maven plugins to achieve that

exception in ClassLoader executing jar outside of build environment

A simple Cassandra client app using netflix astyanax driver is built in Eclipse. Here is the pom.xml file:
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CCL1</groupId>
<artifactId>CCL10</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>CassandraCL1</name>
<description>Cassandra Client 1</description>
<dependencies>
<dependency>
<groupId>com.netflix.astyanax</groupId>
<artifactId>astyanax</artifactId>
<version>1.56.44</version>
</dependency>
</dependencies>
</project>
The app works fine when started from Eclipse. But when the jar file is copied to an external machine it fails to start with the following exception:
ubuntu#ip-172-31-31-41:~/tmp$ java -cp ./CCL10-0.0.1-SNAPSHOT.jar AppCCL1
Exception in thread "main" java.lang.NoClassDefFoundError: com/netflix/astyanax/connectionpool/exceptions/ConnectionException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.netflix.astyanax.connectionpool.exceptions.ConnectionException
at java.net.URLClassLoader$1.run(Unknown Source)
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)
... 6 more
The external machine is Amazon t1.micro Ubuntu-12 instance. The only software installed there is Oracle’s Java Runtime Environment 1.7.
It looks like some dependency is missing, but I cannot even see the name of the missing class.
Why did Maven fail to insert some dependency in jar? How do I troubleshoot and resolve such a problem?
It turns out Maven does not include all the dependencies in jar. (I assumed Maven does this automatically). Including all dependencies in jar is explained here:
How can I create an executable JAR with dependencies using Maven?
So I solved the problem by adding the following fragment in my xml file:
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>AppCCL1</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

Categories