ClassNotFoundEcception when running jar through Terminal (or command prompt) - java

So I know there are tons of questions like this one, and I have been through all of them, but I can't seem to find one like mine.
Basically, I have a java project with a lot of Maven Dependencies. The project compiles and runs just fine when I run it with IntelliJ, but now I am trying to run it through the terminal (or command prompt). In order to do that, I ran mvn package so I can get a jar file and when I run java -jar server.jar, I get the classic ClassNotFoundEcception exception. In my case, it says that it is:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory
and when I suppress it by (temporarily) commenting out the part of the code that uses this class, I end up with the same error for another class. At this point, I know that I need to have some sort of folder (correct me if I'm wrong, but I believe it is called CLASSPATH) which contains the .jar of each dependency. Can anyone explain to me the situation in a clear way and how am I supposed to organize the .jar file of each dependency (if that is even what I have to do to fix my error).

The org.apache.commons.fileupload.FileItemFactory and most likely other dependencies are not in the classpath. Intellij includes dependencies in the classpath automatically, and this is the reason it works.
To run the program from CMD with all your depedecies included define the following plugin in pom.xml:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
and run:
mvn clean package
java -jar server-jar-with-dependencies.jar

Related

PDFBox with Maven - java.lang.NoClassDefFoundError

When installing PDFBox with Maven, it places the libraries in the ~/.m2/repository directory.
My program complies fine with mvn package.
When I try to run it with
java -cp target/java-project-1.0-SNAPSHOT.jar com.example.sub.App
then I get
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/pdfbox/pdmodel/PDDocument
Should I also be specifying the libraries in ~/.m2/repository as part of the classpath? This seems a bit too tedious to do it this way. What is the recommended way to specify the classpath of my PDFBox library while using the library location(s) of Maven?
I wasn't able to find a nice solution with leaving the JAR files in ~/.m2, so the answer below is a workaround based on some other answers. I will be including more clarification though for those who are new to both PDFBox and maven as I am.
1) Add the following to your pom.xml file. If you already have a <build> and <plugins> section, just add the <plugin> section below to that. Otherwise you may need to add the whole code below within the <project> element:
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>**REPLACE THIS WITH THE FULL URI OF YOUR MAIN CLASS**</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-my-jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2) Make sure that you replace the text in the <mainClass> element to match the situation. For example, if your main() method is located in an App class in App.js, and your package name is com.example.sub. Then the above element should read:
<mainClass>com.example.sub.App</mainClass>
3) To compile your app, run mvn package
Note: I have seen some references online using mvn clean compile assembly:single instead of mvn package. I am not sure what the purpose of this is when mvn package seems to run just fine for me.
This will take your project and all of your dependencies and create a single JAR file in the target directory called something like this:
java-project-1.0-SNAPSHOT-jar-with-dependencies.jar
4) To run the project you can do this:
java -cp target/java-project-1.0-SNAPSHOT-jar-with-dependencies.jar com.example.sub.App
Make sure that you modify the above line to it your situation. In other words you may need to change both the name of the jar file and the name of the URI for your main class.

Maven: Could not find or load main class

I have the following configuration for my maven build and I have double checked the class name as well as package name multiple times to ensure it's accuracy. But everytime I run:
java -jar <snapshot-with-dependencies>.jar I get Error: Could not find or load main class com.atlassian.JiraRestCaller.
The excerpt from my pom file is as below
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.atlassian.JiraRestCaller</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
I also tried adding <sourceDirectory>src/main/java/com/atlassian/</sourceDirectory> but still get the same error
Solution1:
I spent a decent amount of time trying to solve this problem. I thought that I was somehow setting my classpath incorrectly but the problem was that I typed:
java -cp C:/java/MyClasses C:/java/MyClasses/utilities/myapp/Cool
instead of:
java -cp C:/java/MyClasses utilities/myapp/Cool
I thought the meaning of fully qualified meant to include the full path name instead of the full package name.
Solution2:
If you use Maven to build the JAR file, please make sure to specify the main class in the pom.xml file:
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>class name us.com.test.abc.MyMainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
This might help you if your case is specifically like mine: as a beginner I also ran into this problem when I tried to run a Java program.
I compiled it like this:
javac HelloWorld.java
And I tried to run also with the same extension:
java Helloworld.java
When I removed the .java and rewrote the command like java HelloWorld, the program ran perfectly. :)
So we had this today
[myproject]-[master] $ mvn
[MVNVM] Using maven: 3.5.2
Error: Could not find or load main class html
and we had an issue with Proxies.
Check your MAVEN_OPTS and make sure that if you are sending in a proxy to maven, that it exists and you can use it.
MAVEN_OPTS=-Dhttp.proxyHost=www-proxy.myproxyprovider.com -Dhttp.proxyPort=80 -Dhttps.proxyHost=www-proxy.myproxyprovider.com -Dhttps.proxyPort=80
or if it is set and you shouldnt have one, then get rid of it.
[myproject]-[master] $ mvn -version
[MVNVM] Using maven: 3.5.2
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T08:58:13+01:00)
Maven home: /Users/bamcgill/.mvnvm/apache-maven-3.5.2
I experienced the same error. I fixed it by upgrading from Maven 3.3.3 to Maven 3.6.3. I am not sure whether that fix is related to this question, because I did not debug my issue.

Kafka Producer Class Not Found Exception

I tried to implement a simple producer consumer example with kafka and I achieved with the following properties:
Properties configProperties = new Properties();
configProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:" + portNumber);
configProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.ByteArraySerializer");
configProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
// Belirtilen property ayarlarına sahip kafka producer oluşturulur
org.apache.kafka.clients.producer.Producer producer = new KafkaProducer(configProperties);
However when I try the exact same configs, and everything else the same, in another project which is a plugin for a data visualization software, I got this error:
.... // Here there is some other stuff but I thing the important one is the below one
Caused by: java.lang.NoClassDefFoundError: org/apache/kafka/clients/producer/Producer
at App.MyControlPanel.<init>(MyControlPanel.java:130)
at App.CytoVisProject.<init>(CytoVisProject.java:29)
... 96 more
Caused by: java.lang.ClassNotFoundException: org.apache.kafka.clients.producer.Producer
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 98 more
In the first one that I said it worked, I was using "mvn clean compile assembly:single", but in the second one I created a jar file for the whole project. Because the visualization software wants a jar file to install the plugin. Since every thing is same (At least I could not find any difference, I used same code) I guess the problem is about the way build the project. What happened here? What is the difference between "mvn clean compile assembly:single" and building a jar file in IntelliJ? Why I got this error and how to fix this? Thanks a lot for help!
As I said in the last comment of the first answer, I have a plugin which has manifest and transform as goal. Here:
<plugin>
<groupId>com.springsource.bundlor</groupId>
<artifactId>com.springsource.bundlor.maven</artifactId>
<version>1.0.0.M2</version>
<configuration>
<outputManifest>C:\Users\USER\AppData\Local\Temp\archetype2tmp/META-INF/MANIFEST.MF</outputManifest>
<failOnWarnings>false</failOnWarnings>
<removeNullHeaders>true</removeNullHeaders>
<manifestHeaders><![CDATA[Bundle-ManifestVersion: 2
Bundle-Name: CytoVisProject
Bundle-SymbolicName: CytoVisProject
Spring-DM-Version: ${pom.version}
]]></manifestHeaders>
</configuration>
<!-- generate the manifest automatically during packaging -->
<executions>
<execution>
<id>bundle-manifest</id>
<phase>package</phase>
<goals>
<goal>manifest</goal>
<goal>transform</goal>
</goals>
</execution>
</executions>
</plugin>
If I use a shade plugin like below:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<configuration>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
It does not works, because I need to use manifest and transform as goals in my plugin. How can I add kafka classes to the jar file that IntelliJ creates to solve this problem (I am not sure if this can solve or not)?
I've found an easier solution. I have changed
kafkaProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
to this
kafkaProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
And afterwards my code run, also as part of a pre-compiled plug-in.
What the problem is
At compile time kafka-clients-0.10.0.0.jar is available, so the code compiles successfully, but at runtime it is missing, hence the error you get.
How to fix it
You have 2 options:
Include the kafka JAR inside your JAR
Add the kafka JAR to your plugin's classpath
Also, make sure you don't have a dependency for kafka-clients marked with provided scope.

Setting classpath for a java project with many libraries and external resources in command line

I have the following project. It has some property files in the conf folder, some data in the data folder, some jar files in the lib folder and also some external libraries that are not shown in the photo due to size limitation. Imagine I want to run the RecDriver class. How exactly should I set the classpath so that I can run it in command line? This is how I did it but it does not work as it cannot fine some other files in the project.
C:\Users\myUserName\Downloads\librec-2.0.0\librec-2.0.0\core\src\main\java\net\librec\tool\driver> javac RecDriver.java
The project can be downloaded here:
https://github.com/guoguibing/librec
You can use bin/librec or bin/librec.cmd to run it from commandline.
If you want to build your launch command you can see those start scripts and adapt them for your purposes.
To run your app through command line, once you have the .class files in some dir (usually build) all you have to do is run your application with java -cp "path where jvm can find every .class that you project needs" MainClass.
The -cp flag only tells where to look for compiled .class files, since you are using IntellIJ you can see the command it runs when executing your program, there is a class path that it uses.
Class Path points to where your .class files are, they can be in separate folders, but you need to include every dir when giving the class path, separated by ";"
Example taken from another question in SO.
java -cp "Test.jar;lib/*" my.package.MainClass
Three things to do:
Use the Maven Shade Plugin to create a fat jar (jar with dependencies)
Use the Maven-Jar-Plugin to make the Jar executable
Set <project><build><finalName> to ${artifactId}
Now, after your build ran successfully, you can run your app with
java -jar target/YourArtifactId.jar
(Substitute your project's artifactId for "YourArtifactId")
Okay, here's the full setup.
Add a build section like this to your pom.xml (merge it with any existing one).
<build>
<plugins>
<!-- number 1 -->
<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>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
</plugin>
<!-- number 2 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
<!-- number 3 -->
<finalName>${project.artifactId}</finalName>
</build>

Building and executing JAR file error: could not find main class and unsupported major.minor version 52.0

After building the Java program in NetBeans, I compressed the dist folder, placed the program in a USB. In another computer, after extracting all the files, I tried running the JAR file but a Window prompt said:
"Could not find the main class: logic.Main. Program will exit."
After researching and tried the solutions of similar problems (i.e. creating Manifest file, creating .bat file) but nothing works.
Then I ran it in command prompt and these were the results:
Are there 2 problems: could not find main class and that in the other computer, the Java is not updated? How to solve this?
It was actually able to find a logic.Main, but it wasnt able to load it because it was compiled with Java 8 and the user's machine is running an earlier version of Java. Compiling the file on an earlier version of Java or updating Java on the target machine will fix the issue.
There are multiple ways of creating executable jar.
In netbeans there is a option
Project Properties -> Build -> Packaging -> Build JAR after compiling
Maven Build can also be used for creating executable jar. Define main class in below maven plugin. Also you can select the compiler version to avoid major minor issue.
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.kulhade.elasticsearch.Indexer</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.dstovall</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>1.4.4</version>
<executions>
<execution>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>

Categories