How to use a .jar file in the Terminal? - java

So I worked on a project and i coded everything in eclipse. I had my codes in folder called src and my libraries in a folder called lib. The problem is that, my code needs to be excecuted in the terminal. Well, now i get tons of errors. All of them are because there are libraries missing. I tried to import the .jar file from the lib folder to the src folder but the code still didn't work.
So, how can I "install" the libraries in the terminal?
btw. the library I'm trying to install is the com.google. I've already cloned it with the following line:
git clone https://github.com/google/gson

First of all, you have to make your project to compile perfectly with your IDE or whatever.
Later, you should create the runnable JAR file (with eclipse if you want, but it's important the world RUNNABLE jar file. Click in your project > Export > runnable jar file and select you main class in "Launch configuration".).
Finally, go to the console to the path of your JAR file and execute
java -jar file.jar
I think it should work :)

If you want to build your project from terminal, you need to make sure of two things.
1. You should have main class attribute in mainfest file.
2. Jar should be compiled with all the dependencies. (This will result in a bigger jar though)
You can do both with maven assembly plugin. Add the following in build/plugins in your pom.xml
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.tanmayvijayvargiya.MainApp</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>
Update the with your mainClass
To build the jar, run mvn package. This will generate jar in your target folder.
Next, to run the jar run java -jar target/jar-name-with-dependencies.jar
Source
Maven Assembly Plugin Usage

Related

How can I specify a classpath for executables created with javapackager?

The javapackager command in Java 8 is able to create standalone executables. The examples on the web usually only use a single jar file, but I have several jar files that need to be bundled into the application. The documentation states that it is possible to tell the bundler the classpath sending classPath=path through the -B option. However, in the resulting <applicationname>.cfg file inside the packaged application there is a line that says
app.classpath=
which is not affected at all by the classPath argument, but I have to manually edit it to include all the jars used by the app to make it work.
All this is on macOS, I couldn't try it on another platform yet.
Any insight greatly appreciated – a working example using more than one jar, for example.
The documentation is slightly flawed:
-Bclasspath=
with small p instead of capital P works (Tested on Windows and MacOS).
I have this problem and found an alternative solution that does not require modifying the cfg file's class path. My approach uses Maven but it can be done with Ant or scripting; just requires more work. The idea is to create a single jar file that has all of the contents of your main jar and all the dependent jars. This can be done with a single Maven plugin like so:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-4</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.yourapp.MainClass</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
I set the execution phase to prepare-package so that it runs before the app bundling, but you can change that as needed. The end result is a single jar named <appName>-<version>-jar-with-dependencies.jar which contains the extracted contents of all the dependent jars. You can test it using java -jar <jarName> before using it with javapackager.

Build java project using jars into one jar (command line)

In Intellij, I'm able to "build an artifact" which allows me to create a jar file, even though my project uses other jar files (like drivers). Traditionally, I would compile a project with jar dependencies by putting them in my classpath like so:
javac -cp .:dependency.jar Main.java
and then be able to run Main by doing:
java -cp .:dependency.jar Main
My question is, how do I create a jar file file with this new Main? I can do:
jar cvf Main.jar Main.java
which will create a jar file, but it doesn't run and says:
no main manifest attribute, in Main.jar
I'd like to know how to package my other jar dependencies into on executable jar.
Option 1: Using Maven plug-in if you are using maven:
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>Path.to.your.main.class</mainClass>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
Option 2: Using spring boot to create fat jar. Which includes all your dependent jar files. Make sure you include spring boot dependency.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.3.3.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
Option 3: Without any help of maven and Spring:
Create a manifest.txt file with the following content:
Main-Class: path.to.your.main.class
To create jar use command : jar -cvfm Application.jar manifest.txt /path/to/*.class

How to include third party jars while running a java program

A very noob question.
I have a java class
package org.foobar;
import thirdparty_jar1;
import thirdparty_jar2;
public class FooBar{
public static void main(String[] args){
// some code
}
}
I use eclipse as my ide and I added these thirdparty jar 1 and jar 2 in its build path. and then I proceeded to export the jar.
Now I have a foobar.jar file and now I want to run it..
I did java -cp /path/to/foobar.jar org.foobar.FooBar
but it complains about missing third party libraries.
How do i run my jar (or probably build a fat jar) . I just want to run my program from command line.
Thanks
A jar has a manifest file called MANIFEST.MF, under the folder META-INF. This contains details about the jar file, the main class etc. Eclipse creates one by default, you can modify that or specify your own manifest file.
See http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html and Understanding the Default Manifest.
To add libraries to the classpath, you need to add the jar files' path to the manifest file, like this:
Class-Path: jar1-name jar2-name directory-name/jar3-name
See Adding Classes to the JAR File's Classpath
If you're using Maven, you can add this to your pom.xml file. This will create an additional "fat" jar whenever you build with Maven. It goes in the 'build.plugins' section:
<build>
<plugins>
...
<!--
The plugin below creates an additional, executable JAR with all dependencies
included in it.
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>${package}.FooBar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
...
</plugins>
</build>
Since you said that you are using Eclipse, did you know you can export a runnable JAR and all its dependecies via the IDE? Right-click on your project and select Export. Search for "Runnable JAR". You should see this:
Now you have a few options:
Extract required libraries into generated JAR.
This will unpack the third party JARs and repack them, along with your class, into a single JAR.
Package required libraries into generated JAR.
This will include the third party JARs into your JAR, as well as some special Eclipse magic to unpack them when needed.
Copy required libraries into a sub-folder
This will copy the third party JARs into a folder and then update the manifest of your JAR, adding the third-party JAR relative file references to your classpath.

Maven Jar Builder: Could not find or load main class

I have been trying for several days now to create an executable jar file for my muli-module maven project. However, when I try to run this jar file I get "Could not find or load main class src.main.java.com.domain.Mainclass" (I have changed the name domain and MainClass for my company's privacy sake)
I have searched for days and none of the obvious tips seem to work.
My project has a main maven project that downloads all of the dependencies (packaging:POM)
and several module projects (Packaging:Jar).
Everything seems to work fine, and all of the files are compiled into class files, but somehow the main class is not being added to the pom.
My Pom File Plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-4</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.domain.project.MainClass</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
The Commands I Use: mvn clean package, then I cd into the target folder and do: java -jar jarfilename.jar
Any tips or help would be most welcomed!
Edit:
My current configuration creates a 2 jar files for every module:
projectname-jar-with-dependencies.jar
projectname.jar
When I navigate to the target folder of the module with my main class, I can successfully run the jar file. However, when I try to run the jar file of my parent maven project (the one with packageing:pom) I still get the same error. Does anyone know why the main jar file cannot find the main class?
Thanks!
You should not have src.main.java as part of the package name of your main class. It's just part of the default maven project folder structure convention. Your configuration should probably read:
<archive>
<manifest>
<mainClass>com.domain.project.MainClass</mainClass>
</manifest>
</archive>
I'm going to necro this post because it is important to have 3 different things set properly:
MainClass.java needs to be in <project_root>/src/main/java/com/domain/project/
Maven assembly plugin needs <mainClass>com.domain.project.MainClass</mainClass>
Your package should be set to com.domain.project
When those three match, Maven should package an executable JAR file.
it seems like you have one of the plugins missing. add the bellow to pom.xml file
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>yourclassnameKt</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
The plugin will add MANIFEST.mf file, which will tell the Java runtime which class to execute.
There is another issue that has the same problem ->
Kotlin + Maven assembling: no main manifest attribute
Reference: https://michaelrice.com/2016/08/hello-world-with-kotlin-and-maven/
I have a bit of a different but similar scenario so I thought I would share. I have a primary maven application packaged into a war through the build (pom.xml packaging configuration). I wanted to add a jar file that is created from one package within our source code, and added into the assembled output along with the webapp war. This allows us to deliver the web application along with a cli tool separately. I didn't want to reconfigure the pom.xml to be multi-module, but just to add a jar as a separate executable within our existing structure. I was banging my head against this for a while.
First, I ended up deleting my entire .m2 directory with maven repositories locally. It appears there may have been an issue for me here, because my ultimate code that worked seems to be the same as what wasn't working originally. I suspect the reasoning for this was I was trying different versions of libraries and was creating conflicts, but who knows. First suggestion I have if you are having issues is delete your .m2 folder and try from scratch.
Also reference #Adam Howell's answer because that is the fundamentals. I created a simplified example project to figure out why nothing was happening and in there I realized i forgot to prefix the folder structure as src/main/java... doh! Of course in my existing project, this was not the case.
And here is my plugin code i inserted in my pom.xml that worked:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.myCompany.app.cli.CLITool</mainClass>
</manifest>
</archive>
<outputDirectory>${project.build.directory}</outputDirectory>
<finalName>our-cli</finalName>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
I am pretty sure you can change the phase you want this done in, I figured earlier on in compile made since to ensure it was available for packaging later. I'm not very experienced with Maven though, so note that this may not be semantically in-line with Maven conventions.
And it worked! Not sure why this took me hours to work out although it did. This I just updated my bin.xml to include the jar file in my assembled deliverable, and Voilah! I have a jar executable separate from my webapp that I can use as a command-line interface tool.

"No Main Manifest Attribute" in ----.jar Netbeans

I recently just started toying around with Maven in java. Time comes to test my project, it works fine in the NetBeans window, running the main class found in App.java (com.MyCompany.App), but when I try to run it from a command line I get an error:
java -jar fileName.jar
"No Main Manifest Attribute" in fileName.jar
I have tried adding a manifest.mf file specifying what main is, I've also been into project properties and added it as the main file...
What's going on?
You need the maven-jar-plugin (see Maven's example). This plugin will create the required entries in the manifest file when the project is built.
<project>
...
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
...
</plugins>
</build>
...
</project>
You need the version, otherwise, the project won't build. The fully.qualified.MainClass starts at the package hierarchy.
Hope there is a problem in your manifest file. Some basic checks might solve your problem.
it should under /META-INF/MANIFEST.MF
Content should have Main-Class:com.MyCompany.App
If you are using any IDE, there should be an option to export project as runnable jar, you can make use of that to let the IDE take care of correct manifest.
From command line jar cfm filename.jar Manifest.txt com/MyCompany/*.class which generates the Manifest file with following contents
Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)
Main-Class: com.MyCompany.App
And then you can run jar command java -jar fileName.jar.
These type of problems are trivial but kills lot of time, just ensure your contents and location of the file is correct.
You could just use this for command line:
java -cp jarFileName.jar full.package.className
You wouldn't have to go into specifics of the Manifest file in this case.
Setting an Entry Point with the JAR Tool:
The 'e' flag (for 'entrypoint') creates or overrides the manifest's Main-Class attribute. It can be used while creating or updating a JAR file. Use it to specify the application entry point without editing or creating the manifest file.
For example, this command creates app.jar where the Main-Class attribute value in the manifest is set to MyApp:
jar cfe app.jar MyApp MyApp.class
You can directly invoke this application by running the following command:
java -jar app.jar
If the entrypoint class name is in a package it may use a '.' (dot) character as the delimiter. For example, if Main.class is in a package called foo the entry point can be specified in the following ways:
jar cfe Main.jar foo.Main foo/Main.class
If you look at the properties dialog for the project (from project tab, right click on your project and select properties) you'll see that there is a "run" item in the "Categories" window. Click on it and you'll see a dialog where you can specify the Main Class for the jar. That information will end up in your manifest.
I have been having this problem with Netbeans 8.0 and the built-in Maven project for the "Java Application" project prototype. Also I have Maven 3 and I found some of the suggestions on the web don't match the maven code used with Netbeans as well.
Anyway here's a simple recipe for having JAR file to run the main-class and embed dependent libraries. I made this work by comparing other project POM files for projects I found that worked with sub-project JAR-s so if someone with better Maven knowledge spots a gottcha, please speak. Also, I left in some normal stuff to provide context. Example follows:
<properties>
<packageName>trials.example</packageName>
<mainClass>${packageName}.CmdApp</mainClass>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<slf4jVersion>1.7.7</slf4jVersion>
<log4jVersion>1.2.17</log4jVersion>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
This section tells Maven about the project.
packageName ... Is the Java package for the main-class
mainClass ..... The fully qualified name for class with main() method.
You will see these used in the maven-jar-plugin.
The other thing the built-in example prototype didn't do was to package my sub-projects into the JAR so I can run from the command line. This is done with the maven-dependency-plugin below. The interesting bit is in the where we don't need to package the system stuff, and we want the dependant classes wrapped into our JAR.
These are used as follows:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>package</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
<configuration>
<excludeScope>system</excludeScope>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<useDefaultManifestFile>true</useDefaultManifestFile>
<archive>
<manifest>
<mainClass>${mainClass}</mainClass>
<packageName>${packageName}</packageName>
<addClasspath>true</addClasspath>
<classpathPrefix>classes/</classpathPrefix>
</manifest>
<manifestEntries>
<mode>development</mode>
<url>${pom.url}</url>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
Hope that saves you the few hours of checking and testing to make it happen. Cheers, Will.

Categories

Resources