Wednesday, 10 September 2014

Create Java project with Maven Example

Create Java project with Maven Example

In this tutorial, we will show you an easy way to create a single Java project, using Apache Maven. Also, we will transform our project, in order to be recognizable and supported by the Eclipse IDE. Finally, we will conclude the tutorial, by presenting how we can package our Java project into an executable “.jar” file.
In this example, we use the following tools on a Windows 7 platform:
  • Apache Maven 3.1.1
  • Eclipse Kepler Service Release 1
  • JDK 1.7

1. Create a Java Project using Maven’s Archetype

Archetype is a Maven project templating toolkit that enables the creation of Maven project templates for users. For more information about Maven Archetype, click here.
First of all, using the terminal (Linux or Mac) or the command prompt (Windows), navigate to the folder where the new project shall be created. Using the command
1$ mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
we create a new Java project, using the maven-archetype-quickstart template. If the argument archetypeArtifactId is missing, Apache Maven uses the maven-archetype-quickstart template by default.
Now, we execute the command:
1$ mvn archetype:generate -DgroupId=com.javacodegeeks -DartifactId=SampleApplication -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command creates a new Java project under the name SampleApplication, along with its entire directory structure.

mvnPackage_WM

2. Layout of the Project’s Directory

The Apache Maven creates a standard directory layout, as shown below:
01SampleApplication
02|-- pom.xml
03`-- src
04    |-- main
05    |   `-- java
06    |       `-- com
07    |           `-- javacodegeeks
08    |                   `-- App.java
09    `-- test
10        `-- java
11            `-- com
12                `-- javacodegeeks
13                        `-- AppTest.java
You can check the official guide for more information.
By default, the source code of the project is located under the folder “/src/main/java/project-package”, while all unit tests are located under the folder “/src/test/java/project-package”.
In addition, a file called pom.xml is generated by Apache Maven. This special file contains all necessary and vital information about the project and looks like Ant’s build.xml. Specifically, this file contains the directory structure, all necessary plugins and all projects’ dependencies. For more information, you can read the official POM guide.
A sample pom.xml file is shown below:
03 <modelVersion>4.0.0</modelVersion>
04 <groupId>com.javacodegeeks</groupId>
05 <artifactId>SampleApplication</artifactId>
06 <packaging>jar</packaging>
07 <version>1.0-SNAPSHOT</version>
08 <name>SampleApplication</name>
10
11 <dependencies>
12   <dependency>
13      <groupId>junit</groupId>
14      <artifactId>junit</artifactId>
15      <version>3.8.1</version>
16      <scope>test</scope>
17   </dependency>
18 </dependencies>
19</project>

3. Add the M2_REPO classpath variable in Eclipse IDE

The “M2_REPO” classpath variable is required by the Eclipse IDE, in order to locate all declared depencencies for a Maven project. This variable must point to Maven’s Local Repository.
We will add the “M2_REPO” variable to Eclipse‘s classpath variables, by undergoing the following steps:
  • Inside the Eclipse IDE, we click on Windows > Preferences.
  • In the left panel, we click on Java > Build path > Classpath Variables.
  • In the right panel, we click on “New:” button and we fill these values:
    Name: “M2_REPO”
    Path: “C:\Users\Username\.m2\repository\”
  • We click on the “OK” button.
If the procedure has been completed successfully, our newly created variable will be placed among the other variables, as shown:
eclipse_classpath_variables_WM

4. Eclipse IDE Integration

Apache Maven is able to transform a project into a form, recognizable by the Eclipse IDE. To achieve this, we must first navigate to the folder of the project. Open a terminal as in Step 1 and navigate to the newly created SampleApplication project. Then, execute the following command:
1$ mvn eclipse:eclipse
This command generates those files required by the Eclipse IDE, in order for the project to be recognized as a valid Apache Maven project.
project_structureEclipse_WM

5. Enrich the “pom.xml” file

The default created pom.xml file is very simple and contains the minimum information required by a Maven project.
It is recommended that you add the compiler plugin, in order to guide Maven for which JDK version to use for compiling your project. Add the following lines to your pom.xml file:
01<build>
02 <plugins>
03  <plugin>
04   <groupId>org.apache.maven.plugins</groupId>
05   <artifactId>maven-compiler-plugin</artifactId>
06   <version>3.1</version>
07   <configuration>
08    <source>1.7</source>
09    <target>1.7</target>
10   </configuration>
11  </plugin>
12 </plugins>
13</build>
In order for our project to be able to support and execute jUnit tests, we must add the following dependency to our pom.xml file:
1<dependencies>
2 <dependency>
3  <groupId>junit</groupId>
4  <artifactId>junit</artifactId>
5  <version>4.11</version>
6  <scope>test</scope>
7 </dependency>
8</dependencies>
The above XML snippet is called a “Maven Coordinate”. In order to declare the jUnit “.jar” file as a dependency to your project, you must find its corresponding Maven Coordinate. The same procedure must be executed for every external “.jar” file that poses as a dependency to your project, such as Apache Common, Spring, etc. For your convenience, visit the Maven Central Repository and choose the most appropriate Maven Coordinate for every dependency of your project.
The final form of our pom.xml file is the following:
pom.xml:
03 <modelVersion>4.0.0</modelVersion>
04 <groupId>com.javacodegeeks</groupId>
05 <artifactId>SampleApplication</artifactId>
06 <packaging>jar</packaging>
07 <version>1.0-SNAPSHOT</version>
08 <name>SampleApplication</name>
10 <dependencies>
11  <dependency>
12   <groupId>junit</groupId>
13   <artifactId>junit</artifactId>
14   <version>4.11</version>
15   <scope>test</scope>
16  </dependency>
17 </dependencies>
18 <build>
19  <plugins>
20   <plugin>
21    <groupId>org.apache.maven.plugins</groupId>
22    <artifactId>maven-compiler-plugin</artifactId>
23    <version>3.1</version>
24    <configuration>
25     <source>1.7</source>
26     <target>1.7</target>
27    </configuration>
28   </plugin>
29  </plugins>
30 </build>
31</project>
Finally, we must again execute the command
1$ mvn eclipse:eclipse
in our terminal, in order for Maven to download all declared plugins and every project dependency. All downloaded files are stored in Maven’s Local Repository.

6. Develop our Application

In this step, we will create a simple Java application that reverses an input string. Inside the folder “/src/main/java/com/javacodegeeks/”,we locate the file App.java. Copy and paste the following code:
App.java:
01package com.javacodegeeks;
02
03public class App {
04   public String reverseString(String src) {
05      return new StringBuilder(src).reverse().toString();
06   }
07
08   public static void main(String[] args) {
09      final String str = "Hello!";
10      App appObject = new App();
11
12      System.out.println("The reverse string of \"" + str + "\" is \"" +
13                         appObject.reverseString(str) + "\"");
14   }
15}
Next, we will create a simple jUnit test, in order to confirm that our application functions properly. Inside the folder“/src/test/java/com/javacodegeeks/”, we locate the file AppTest.java. Copy and paste the following code:
AppTest.java:
01package com.javacodegeeks;
02
03import org.junit.Assert;
04import org.junit.Test;
05
06/**
07* Unit test for simple App.
08*/
09
10public class AppTest {
11   @Test
12   public void testApp() {
13      App appObject = new App();
14      Assert.assertEquals(appObject.reverseString("Test!"), "!tseT");
15   }
16}
In this class, we define a testing method called testApp, in order to verify that our method works properly, using the functionassertEquals. We must be careful not to forget the @Test annotation before the class, otherwise Maven won’t run our test.

7. Package our Application into a .jar file

We can now use Apache Maven to package our application into an executable “.jar” file. The packaging element inside our pom.xmlfile defines the packaging format or output.
1<groupId>com.javacodegeeks</groupId>
2<artifactId>SampleApplication</artifactId>
3<packaging>jar</packaging>
4<version>1.0-SNAPSHOT</version>
5<name>SampleApplication</name>
Open a terminal as in Step 1, navigate to the SampleApplication project folder and execute the command:
1$ mvn package
mvnPackage_WM
This command compiles our project, executes all unit tests and finally, generates the executable “.jar” file inside the “project/target”folder.
Our project shall have the following structure inside the Eclipse IDE:
project_structure_eclipse_2_WM

8. Sample Project Execution

The generated executable file can be executed using the following command:
1$ java –cp target\SampleApplication-1.0-SNAPSHOT.jar com.javacodegeeks.App
mvn_sample_execution_WM

9. Download The Eclipse Project

The Eclipse project of this example: SampleApplication.zip.
This was an example on how to create a Java project, using Apache Maven.
Reference:-JavaCodeGeek

No comments:

Post a Comment