Saturday 18 January 2014

Building Java projects with Maven.

In last post we saw what is maven and how do we install it. Now lets create a java project and use maven to build and then  test by running it.

What you will need?

  1. Maven installed
  2. JDK(6 or higher)
  3. IDE(Eclipse/Intellij IDEA) or a text editor(gedit/vim)

Setting up the project

Projects that are to be built by maven must follow a particular directory pattern. For detailed directory structure you can visit their documentation on directory structure.

For our example we are going to create a HelloWorld sample inside a package called hello.

So our directory structure will be something like





So go ahead and create such structure. You can use following command

mkdir -p src/main/java/hello

Now inside hello directory create two java files - HelloWorld.java  and Greeter.java.

Code for them is provided below. For src/main/java/hello/HelloWorld.java

package hello;

public class HelloWorld {
    public static void main(String[] args) {
        Greeter greeter = new Greeter();
        System.out.println(greeter.sayHello());
    }
}

and for src/main/java/hello/Greeter.java

package hello;

public class Greeter {
    public String sayHello() {
        return "Hello world!";
    }
}



Now that Maven is installed, you need to create a Maven project definition. Maven projects are defined with an XML file named pom.xml. Among other things, this file gives the project’s name, version, and dependencies that it has on external libraries.

Note :  This file must be in the project root directory which means in the folder which has src folder.

Create a file named pom.xml at the root of the project and give it the following contents:


<?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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>HelloWorld</groupId>
    <artifactId>gs-maven-initial</artifactId>
    <version>0.1.0</version>
    <packaging>jar</packaging>
</project>

Now you can build your java project using 

mvn compile

This will download your dependencies and compile you java files. Corresponding .class files will be created in a target folder in the projects root folder.

To make the jar file of your project you can use

mvn package

This will create a jar file in the target folder. Now you can run your code with

java -jar PathToYourJarFile

Maven Build lifecycle

compile and package were some of the initial phases of Maven build lifecycle. All of them are listed in the following diagram



For more details on the maven build life cycle phases you can visit their official site.

I am getting Can't execute jar- file: “no main manifest attribute”. What should i do?

That is because you have not told maven while packaging how do you built the project. You need to provide build information withing <build> and </build> tags in the build file. You can add following tag between <project> and </project>.


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>hello.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

and you are done. By this you essentially say what is your main class so that while executing java knows the entry point from that jar file.

I want to use IDE instead of text editor. How do I import maven projects to my IDE?

Even this is very simple. You can run the following commands in the projects root directory -

  • mvn eclipse:eclipse  (For Eclispe IDE)
  • mvn idea:idea  (For intellij IDEA IDE)
For example idea command will generate all the required files like .ipr(project file), .iws(workspace file) etc. You can open the file by simply opening this .ipr file in IDEA.

Note : As per Mavens official site mvn idea:idea is obsolete. You can directly do File -> Import project and select pom.xml file.

I am getting "Package name does not correspond to the file path" error after importing project in my IDE.

This is because dash(-) is not allowed in package name and your -DgroupId contained  dash(-) which was used as package name. You can refactor and replace dash(-) with underscores(_) which is legal in a package name.



How to install maven on Ubuntu?

What is Maven?

Maven is essentially a build automation tool similar to apache ant but provides much more features that just building. It addresses two important aspects -  
  1. how your software will be built and 
  2. your software dependency resolution
For complete details you can visit the following sites
  1.  Wiki
  2. Apache Maven Homepage
Lets get started then.



How to install Maven?

 You can search for the maven package using the following command

apt-cache search maven


You may see a lot of packages but what we are interested is -

maven - Java software project management and comprehension tool

So lets go ahead and install it. Use the following command to install the package

sudo apt-get install maven

I am using Ubuntu so I have apt-get. You can use yum  if you have Fedora/CentOS.

To verify the installation you can simply execute the following command

 mvn -v

v here stands for version. You can also type complete word i.e  mvn -version.
 You will see some details about the installed maven package.

This indicated maven is successfully installed.

Install latest versions

Using apt-get you may not get the latest version of maven. For latest version download the binary from maven site and install it.

Use the following commands - 

  1. cd ~/Downloads
  2. wget http://apache.mirrors.timporter.net/maven/maven-3/3.1.1/binaries/apache-maven-3.1.1-bin.tar.gz
  3. sudo mkdir -p /usr/local/apache-maven
  4. sudo mv apache-maven-3.1.1-bin.tar.gz /usr/local/apache-maven
  5. cd /usr/local/apache-maven
  6. sudo tar -xzvf apache-maven-3.1.1-bin.tar.gz
  7. Edit ~/.profile with gedit ~/.profile and add these four lines:
    1. export M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1
    2. export M2=$M2_HOME/bin
    3. export MAVEN_OPTS="-Xms256m -Xmx512m"
    4. export PATH=$M2:$PATH


Next immediate question that may come to anyone’s mind - 

Where is maven installed?

Maven by default gets installed in the following directory

/usr/share/maven


and maven configuration files go to the following directory

/etc/maven


settings.xml has default configurations like path to local repository. yes maven downloads dependencies and stores it in a local repository so that there is no need to download same dependency twice.

Path to maven(mvn) executable is not added to $PATH variable then how is the command recognized?

If you print your path variable by using

echo $PATH

You will notice one of the paths in the variable is

/usr/bin

Now if you see the contents of /usr/bin you will notice that it has mvn executable. It is actually soft link to the actual executable. This approach is a common approach. We cannot keep adding all installed packages folder to $PATH. Instead create a soft link to executable and keep it in  /usr/bin and add this to the $PATH.

This was just how do we install maven on ubuntu. In the next post we will see how to compile and run Java code using maven.


Related Links

t> UA-39527780-1 back to top