Maven | Creating and running JAR files. (Part-2)

Maven helps us to package our project into the jar file to distribute the program on multiple machines.

In the first session, we have learned how to create a Maven project using TestNG. Now in this session will learn how to generate jar files and how to use them.

Maven Packaging and execution process

To understand this, we will backtrack the basic steps as mentioned below:

  1. The output of the packaging process would be a .jar file.
  2. And to run the jar file, the package should have a main method in any of the classes in the program.
  3. The path of the main method and class should be defined in the pom.xml file.
  4. The configuration in the pom.xml file would be done by the Maven compiler and assembly plugins.

Step 1: Create the main method in the project

First of all, we have to create a main method in our project. This main method can be either under “src/main/java” or “src/test/java”. Suppose we have declared the main method with the below code.

MainClass.java

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 * @author ashok.kumar
 */
public class MainClass {

	public static void main(String[] args) {
		
		System.out.println("Method from MainClass");
		System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		
		driver.get("http://www.allinoneblogs.com");

		System.out.println("allinoeblogs lanuched.");
	}
}

Step 2: Update pom.xml for main method and packaging information

Basically, we have to add <Build> section before the <dependencies> tag in the XML file. Few important points are given below:

  1. maven-compiler-plugin: This plug-in helps to compile all the java file and convert into the class files. These files get stored in the “target” folder. (For more info: https://maven.apache.org/plugins/maven-compiler-plugin/)
  2. maven-assembly-plugin: This plug-in is used to combine all the output files(.class), resources, dependencies(library files) into one package. This package can be in any format like a jar, war, zip as per usability. (For more info: https://maven.apache.org/plugins/maven-assembly-plugin/index.html)
  3. jar-with-dependencies: Instructs the compiler to generate the type of output.
  4. manifest tag: This tag provides a further <mainClass> tag, which points to the class where we have put our main(). This would be the entry point of the program execution.
  5. execution tag: This will define the execution setting.
    • id: make-assembly – Combines all the output files into a single unit.
    • phase: package – Generate a package for distribution purposes.
    • goal: single – It will create all the assemblies in one go.
<build>
		<!-- Default path of the source files-->
		<sourceDirectory>src</sourceDirectory>
		<plugins>
		
			<!-- Contains Maven compiler plugin information-->
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<release>10</release>
				</configuration>
			</plugin>
			
			<!-- Contains Maven Assembly plugin information-->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					
					<!-- This will combine all the supporting library files defined in dependencies tag.-->
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					
					<!-- This section contains the exact path till Class file haing the main() in it.-->
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.allinoneblogs.MavenDemo.MainClass</mainClass>
						</manifest>
					</archive>
				</configuration>
				
				<!-- Setting execution methods and packing-->
				<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>

Step 3: Generate JAR file

Now we have to activate few commands to generate the JAR files. These commands also known as “Goals“. We can activate these commands via two methods:

  1. Right-click on the Project and Select Run As it will pop-up all the commands. Click on any command from the context menu like
    • Maven clean
    • Maven build
    • Maven generate-source
    • Maven test
    • Maven install
Context menu options for Maven project.

2. Another way is to click on the option “Maven build…”. It will open the “Edit Configuration” dialog box. We can enter the command in Goals and click on Run to execute.

Edit Configuration dialog box to activate the maven commands.

We can use the below keywords as “Goals”. Please note that the console should reflect “Build Success” after running each goal. If we are getting “Build Failure” then we have to locate and fix the bug.

Purpose of Goals

  1. compile: Compile the files present in the main folder. Output generated in the “target” folder.
  2. test-compile: Compiles the files present in the test folder. Output generated in the “target” folder.
  3. test: It will verify that there won’t be any issue while executing the program.
  4. clean: To clear all the data from the “target” folder.
  5. install: It will generate jar files with and without dependency.

Step 4: Create a Package to distribute the program

The next step is to put all the supportive files like input, drivers, resources, screenshot folder, etc. in one folder along with the generated jar with the dependency file. In the below example, we have put the chromedriver.exe file under the drivers folder.

Putting all the resource files with Jar file.

Step 5: Program execution

Now the last step is to execute the program. To run a jar file we have to use Command Prompt.

  1. Open the command prompt.
  2. Locate the folder where the Jar file is placed.
  3. type command java -jar <filename.jar>
  4. Press Enter
Output on command prompt.

You will observe that the browser will open and action would be performed as we have done coding in the main(). Also, the command prompt will display the output.

Creating batch file to run the java command

We can also create a batch file to execute the program. The end-user will directly double-click on that file to start the program execution. A batch file is a file with a .bat extension.

  1. Navigate to the folder where the .jar file is present and you want to execute it.
  2. Create a text file and enter the same command “java -jar <filename.jar>” as below
    • java -jar MavenDemo-0.0.1-SNAPSHOT-jar-with-dependencies.jar
    • pause
  3. Save the file with a .bat extension like “run.bat”.
  4. Double click on the run.bat file to execute the program.

Maven:


Leave a Comment

Your email address will not be published. Required fields are marked *

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.