JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

JSF 2 Installation and Configuration Using Maven 3

March 20, 2014 by Amr Mohammed Leave a Comment

JavaServer Faces (JSF) is a server side component framework for building Java Technology web-based application. JavaServer Faces (JSF) consists of two main parts:

  • The JavaServer Faces API for representing components, managing their states, handling events, handling server side validations, and achieving data conversion; defining pages navigation, supporting internationalization and accessibility and providing extensibility for all these features.
  • Tag libraries for adding components to the web pages and connecting those components into their corresponding server side objects.

This post should clarify how a JSF framework could be installed and configured by using Eclipse IDE and Maven.

Also Read:

  • Introduction to JavaServer Faces
  • Request Processing Lifecycle phases in JSF
  • Navigation model in JSF

Tools Used

This post will use the following tools for achieving the required installation and configuration:

  • Eclipse Java EE IDE
  • JSF 2.2
  • Maven 3.0
  • JDK 1.6
  • Apache Tomcat 7.0.35

Create JSF Project With Maven

To create a Web Project using maven, you should use the maven archetype. The Archetype is a template toolkit that used for creating a standard Java projects. Those templates are used to create several types of Java projects starting from a standard simple Java into very complicated Enterprise application.

Creating a maven Web Project should follow these steps mentioned below:

  • Download the latest maven-archetypes-templates from an official “Github” site Maven Archetypes Zip File using the “Download Zip” link that’s appended at the right panel of the page.
  • Unzip the file inside an empty folder and navigate into quickstart-web-app folder and execute the following maven commands to install the template that will be used to create a simple standard Web Project:
    1. Execute mvn clean archetype:create-from-project. The result of execution should be a new template that must be installed on your local repository to be used later.
    2. Navigate to “target/generated-sources/archetype” and execute mvn install to install the created template into your local repository.
    3. Navigate into an empty folder and execute mvn archetype:generate -DarchetypeCatalog=local -DgroupId=net.javabeat.eclipselink –DartifactId=EclipseLink-Installation -Dversion=1.0
    4. A list of local archetype will be listed if you have different archetypes that have been created.
    5. Enter the number beside of the archetype named “quickstart-web-app-archetype”.
    6. List all folders that created in a step 3 by using dir or ls based on your Os. You should see the artifact JavaBeat-JSF-Installation.
    7. The JavaBeat-JSF-Installation is a standard Web Project that created by the maven. The created project contains your own named package that passed in the -DgroupId.

See the below screen shot that shows you the created project and its structure.

JSF Maven Structure Directory

Import Maven Web Project Into Eclipse IDE

Eclipse IDE provides the developer capability of importing a maven project through an eclipse driven wizard. Follow the following steps to import the project created previously.

  1. Open EclipseIDE.
  2. Right-Click at the “Project Explorer”.
  3. Choose import option and from the right menu click import.
  4. Expand the maven tree.
  5. Choose Existing Maven Projects. And click next.
  6. Navigate into your created project by using the browse and click ok. In our case the path is C:\JavaBeat\archetype.
  7. The Eclipse IDE should read the pom.xml and tell you with the name of the projects found there.
  8. In our case the Eclipse IDE will mention /JavaBeat-JSF-Installation/pom.xml.
  9. Select the project & click finish.
  10. The Web Project should be imported.

The below snapshot shows you the full structure of the imported directory.

Full Maven Imported Project for JSF

At the end of the previous steps, you are now having a Dynamic Web Project that’s ready for next coming installation and configuration of JavaServer Faces (JSF). 

Add JSF Dependencies

If you’ve want to complete adding the JavaServer Faces required library by using a faceted project you can follow the link of installation and configuration of JavaServer Faces using the Facet Dynamic Web Project using Eclipse.

But here’s an adding of the required libraries should be done through the maven dependencies. First of all we have to configure the pom.xml in order to support the JavaServer Faces (JSF). To configure the pom.xml file you’ve to follow the below steps:

  • Double click on the pom.xml file.
  • Navigate into the pom.xml pane that located at the last Tab.
  • Maven dependencies for JavaServer Faces are mentioned at the following link and use the Mojarra Sun’s Reference Implementation.

Add the following dependencies inside the <dependencies> Tag:

[code lang=”xml”]
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>

<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>mojarra-jsf-api</artifactId>
<version>2.0.0-b04</version>
</dependency>

<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>

<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>mojarra-jsf-impl</artifactId>
<version>2.0.0-b04</version>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>

[/code]

Installing the Dependencies

For installing the dependencies that you’ve mentioned in the pom.xml file you have two choice:

  • By invoking the Eclipse IDE Build Project Shortcut Ctrl + B.
  • By invoking the Maven clean install command.

The below snapshots shows you the behavior for each way of installing respectively.

Installing Dependencies By Eclipse

Installing Dependencies By Maven

Configure the Deployment Descriptor (web.xml)

The web.xml file should be configured to make the application capable of invoking the JavaServer Faces (JSF) implementation. Such that configuration should consider the following points:

  • Configure the JavaServer Faces Front Servlet that would be used by the JavaServer Faces implementation and the mapping URL that would be used for triggering that Servlet.
  • Configure the location of the faces-config.xml file that will be used for defining the Managed Beans, Navigation Cases and Custom Components (Validator, Converter and etc ..)
  • Configure the location that will be used for saving the state of the view components.
  • Configure the JavaServer Faces Listener.

The web.xml file should looks like the below

[code lang=”xml”]

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5" metadata-complete="true">
<context-param>
<description>State saving method: ‘client’ or ‘server’ (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping></pre>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<pre>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>

[/code]

Creating Managed Bean

The Managed bean is the place that you’ve used for managing the data back and forth between the user interface and the server. At the Hello World example we are going to define a new Manged Bean in order to make a Hello World ! message readable from the server side instead of mentioning it directly at the page. Before JavaServer Faces 2, the creation of managed server does need a faces-config.xml to mention it.

To create a managed bean, all you need is to do the following:

  • Right Click on the package named net.javabeat.jsf
  • Select New -> Class.
  • Change the name of the class.
  • Define new property helloProperty.

[code lang=”java”]
package net.javabeat.jsf;

public class HelloWorldBackingBean {
private String helloProperty = "Hello World !";

public String getHelloProperty() {
return helloProperty;
}

public void setHelloProperty(String helloProperty) {
this.helloProperty = helloProperty;
}
}
[/code]

Configure faces-config.xml

The faces-config.xml file should also be configured to contains those managed beans that would be used in the JavaServer Faces pages. The below fragment of code shows you the full faces-config.xml for the Hello World application, in case you’ve decided to define your beans in the face-config.xml. Since JavaServer Faces 2 the beans are defined using the annotation of @ManagedBean.

[code lang=”xml”]

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<managed-bean>
<managed-bean-name>helloWorldBackingBean</managed-bean-name>
<managed-bean-class>net.javabeat.jsf.HelloWorldBackingBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>

[/code]

By the way, the following fragment of code will show you the JavaServer Faces (JSF) beans defined using @ManagedBean. The managed bean that created is simply a java class file annotated using @ManagedBean and by that the JavaServer Faces implementation will scan your classpath for finding those classes annotated @ManagedBean.

[code lang=”java”]

package net.javabeat.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class HelloWorldBackingBean {
private String helloProperty = "Hello World !";

public String getHelloProperty() {
return helloProperty;
}

public void setHelloProperty(String helloProperty) {
this.helloProperty = helloProperty;
}
}

[/code]

Configure Apache Tomcat

If you’ve ever been configured the Apache Tomcat for executing a JSF samples, you’ve requested to install and configure it for next coming use. Follow the below steps for making Apache Tomcat for use.

  • From the dynamic project and underneath of Target Runtime -> Select New Runtime

New Runtime

  1. Select Apache Tomcat v7.0 -> Click Next
  2. Type the name of the server that you’ve been installing.
  3. Navigate into the destination path of the Apache Tomcat 7.0 (Download the Apache Tomcat 7.0).
  4. Click on the server pane by Window -> show view -> Servers or Other -> Servers.
  5. You should find the following message (No Servers are available. Click this link to create a new server …)
  6. Choose Tomcat 7.0
  7. Let’s the remaining configuration without touch.
  8. Click next and finish.

Adding of Apache Server

  • The server is installed and is ready for use

Create JavaServer Faces Page

After creating, configuring and installing the all libraries that required to start using of JavaServer Faces, it’s time to create the first Hello World sample.

  • Right-Click the project’s WebContent.
  • Select New -> HTML File.
  • Name your file with an index.xhtml -> Click Next
  • Select New XHTML File (1.0 strict) -> Click Finish
  • Write a JavaServer Faces fragment of code for using the defined bean.
  • The HelloWorldBackingBean contains an attribute with a getter and setter (This is a JSF constraint for showing the bean’s properties).
  • A new property defined in the HelloWorldBackingBean called (helloProperty) with a default value Hello World !.

The page that you will create it must be as below

[code lang=”xml”]

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:view>
<h:outputText value="#{helloWorldBackingBean.helloProperty}"></h:outputText>
</f:view>
</html>

[/code]

Run index.xhtml

To run the index.xhtml you should follow the below steps:

  • Righ-Click on the index.xhtml
  • Select Run As
  • Select the configured Apache Server that you’ve done before.
  • Click finish.
  • You should see the message Hello World !

Download Source Code

What’s The Next

After finishing the installation and configuration of JSF 2, you have the chance to go through another tutorials that clarify you how a different types of JSF componenets could be used.

Filed Under: JSF Tagged With: JSF 2, Maven

How To Create EclipseLink Project Using Maven Archetype

February 16, 2014 by Amr Mohammed Leave a Comment

This article should discuss the installation and configuration of EclipseLink-JPA using Maven dependencies and Maven archetype project creation principle. This article assumes that the machine that used for installation is already have installed a Maven. So the “mvn” command should works. This article will use an Eclipse Kepler release 1 as an Integrated Development Environment, so be sure that you have installed one. To install the Eclipse Kepler refer to the following Eclipse Kepler IDE.

Installation of Maven

Check if the maven has installed or not by using the maven command, “mvn -version”. The proper reply should be as shown at the figure 1.1. (Maven Windows and Maven Ubuntu)

Maven-Check

Figure 1.1

Create Project Using Maven

To create a Java project using maven, you should use the maven archetype. The Archetype is a template toolkit that used for creating a standard Java projects. Those templates are used to create several types of Java projects starting from a standard simple Java into very complicated Enterprise application.

Creating a maven Java project should follow these steps mentioned below:

  • Download the latest maven-archetypes-templates from an official “Github” site Maven Archetypes Zip File using the “Download Zip” link that’s appended at the right panel of the page.
  • Unzip the file inside an empty folder and navigate into quickstart-java-app folder and execute the following maven commands to install the template that will be used to create a simple standard Java project:
  1. Execute mvn clean archetype:create-from-project. The result of execution should be a new template that must be installed on your local repository to be used later.
  2. Navigate to “target/generated-sources/archetype” and execute mvn install to install the created template into your local repository.
  3. Navigate into an empty folder and execute mvn archetype:generate -DarchetypeCatalog=local -DgroupId=net.javabeat.eclipselink –DartifactId=EclipseLink-Installation -Dversion=1.0
  4. A list of local archetype will be listed if you have different archetypes that have been created.
  5. Enter the number beside of the archetype named “quickstart-java-app-archetype”.
  6. List all folders that created in a step 3 by using dir or ls based on your Os. You should see the artifact EclipseLink-Installation.
  7. The EclipseLink-Installation is a Java standard project that created by the maven. The created project contains your own named package that passed in the -DgroupId.

See the Figure 1.2 that shows you the created project and its structure.

MavenProjectStructure

Figure 1.2

Import Maven Project Into Eclipse IDE

Eclipse IDE provides the developer capability of importing a maven project through an eclipse driven wizard. Follow the following steps to import the project created previously.

  1. Open EclipseIDE.
  2. Right-Click at the “Project Explorer”.
  3. Choose import option and from the right menu click import.
  4. Expand the maven tree.
  5. Choose Existing Maven Projects. And click next.
  6. Navigate into your created project by using the browse and click ok. In our case the path is C:\JavaBeat\archetype.
  7. The Eclipse IDE should read the pom.xml and tell you with the name of the projects found there.
  8. In our case the Eclipse IDE will mention /EclipseLink-Installation/pom.xml. See Figure 1.3 as the only project there.
  9. Select the project & click finish.

The project created is imported successfully. See Figure 1.4

EclipseIDEImportMavenProjectWizardResult

Figure 1.4

Compile & Execute the Project

To compile the project, click on the project from the project menu and choose clean. The project must be compiled successfully. See Figure 1.5. Try to run using CTRL+Shift+x & j or by using the run from the menu.

ProjectCompilation

Figure 1.5

If you have noticed that the project execution doesn’t print out “Hello” followed by the entered name. Make sure the log4j.properties uses the correct rootLogger. If the logger uses “debug” while the rootLogger configured to use “info”; the logger will not behave as you expect and thereby it will not print any message. Let they use the same type of message. As you have noticed the logger in the Figure 1.5 uses the info method, so the rootLogger must also use the info.

EclipseLink Artifacts For Maven

Adding external libraries have never been easier than now. To add the EclipseLink-JPA library, you should add the following lines at your project’s pom.xml file.

[code lang=”xml”]
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
</repositories>
[/code]

Also, you should add the required dependency within dependencies tag

[code lang=”xml”]
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
[/code]

Configure persistence.xml

The persistence API requires a persistence.xml that is located under META-INF folder.

To be able to use the persistence API, you should follow the following steps:

  1. Create a folder under src/main/java called META-INF
  2. Create a file named persistence.xml.
  3. Copy the persistence.xml file that produced at the article Eclipse Link – JPA Installation and Configuration Using Eclipse into META-INF.

Testing Application

Add at your default generated HelloService Java class the code that uses the persistence API.

[code lang=”java”]
System.out.println(Persistence.createEntityManagerFactory("EclipseLink-Installation").isOpen());
[/code]

See the Figure 1.6 that shows you the HelloService that uses Persistence API successfully.

TestingApplication

Figure 1.6

Filed Under: Java EE Tagged With: EclipseLink, Maven

How To Build Spring MVC Web Application With Maven?

October 13, 2013 by Krishna Srinivasan Leave a Comment

In my previous tutorial I have explained about how to create a web application using the Maven tool. This tutorial explains how to build your web application project using the Maven artifacts. What is artifacts?. Every framework developer have the repository to store their packages where maven would download from the given artifact id. This artifact id is internally linked to a URL which is the binary distribution of the package. Developers need not spending time on downloading all the dependencies, maven takes care of downloading for them.

You can get the artifacts details for the spring framework project here. In fact they are no more distributing the binary packages, they all recommending to use the Maven or Gradle to build the applications. In the next sections, I will write simple steps which will help you to build and package your first Spring MVC application using Maven. If you have any questions, please write it in the comments section.

I assume that you have already created the web project using Maven. If you have not done, please refer my previous article.

1.  Add Spring Framework Dependencies In pom.xml

This should be the first step on configuring your Maven to work for Spring projects. Lets get the spring artifacts and configure it in the pom.xml. Also add the other required dependencies if any to the pom.xml. Add the below entry to pom.xml:

[code lang=”xml”]
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
[/code]

In the above snippet, ${spring.version} is the exact version name which you want to package your project.

2. Add The Build Details

This is the most important part of the pom.xml to build your project.

[code lang=”xml”]

<build>
<finalName>SpringMVCTestFramework</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>

[/code]

The complete pom.xml file would loom like this:

[code lang=”xml”]
<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>javabeat.net</groupId>
<artifactId>SpringMVCTestFramework</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringMVCTestFramework Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.2.4.RELEASE</spring.version>
<junit.version>4.11</junit.version>
<jdk.version>1.6</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCTestFramework</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
[/code]

3. Create The Spring MVC Files

The above steps completed the Maven configuration for your project. Now its time to create the Spring MVC files for your project. Here we will create a simple controller and jsp file to run the application.

[code lang=”xml”]
package javabeat.net;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class HelloController {
@RequestMapping(value="/hello", method = RequestMethod.GET)
public String welcome(ModelMap model) {
//Your statements
return "hello";
}
 }
[/code]

hello.jsp

[code lang=”html”]
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
[/code]

You can create your spring configurations files or add any more files. I am not diving deep into the Spring MVC specific things, this tutorial is one meant for how to configure on Spring MVC.

  • Spring MVC Framework With Example
  • Spring MVC Annotations

4. Package The Application

The above examples are only for the samples. Once all the required files are created, please run the following command in your project’s root directory.

[code lang=”java”]
$mvn package
[/code]

Spring MVC Maven Package Example

Once the application is packaged, generated war file will be created inside the folder target. The final structure would look like this:

spring-mvc-maven-package-structure

You can copy the ear file and deploy to your server. If you analyse the war file, it will have all the dependency files packaged inside for the deployment.  I hope this tutorial would have helped you to understand the basic idea on how to build and package the web application in Maven. If you are using the ANT for you build, start exploring with advanced management tools like Maven to simplify your development work. If you have any questions, please write it in the comments section.

Filed Under: Spring Framework Tagged With: Maven, Spring Framework, Spring MVC

Create Web Application Project With Maven

October 13, 2013 by Krishna Srinivasan Leave a Comment

This is a simple tutorial explaining how to set up your Web Application Project With Maven and then how it can be converted to the eclipse project. If you have earlier used ANT tool for building the Java projects, it is little difficult to understand the working method for the Maven at first. Maven is not just for the building, it is used for managing the dependencies used in our projects.

In the current scenario, almost every project is moved to the Maven style plugin. Spring Framework is not distributing the binaries to download from their website, they are recommending to use the Maven repositories to get the latest packages. It becomes important for everyone understand how to set up maven project.

1. Install Maven

As a first step, you have to install the Maven tool in your system and set all the environment variables. You can find simple tutorials on setting up maven tools and Ubuntu and Windows. I personally write this tutorial on Ubuntu environment, all my examples are mostly tested in the Ubuntu environment. If you have issues on setting up the environment, please post your questions on comments section.

2. Create Web Project Using Maven

Once you have installed the Maven, it is time to create web project using the console. This tutorial is based on creating the projects in console, not using the eclipse IDE. If you become familiar with this idea, it is very easy for to understand how Maven works. Follow these steps:

  1. Open the console and enter the command “mvn archetype:generate -DgroupId=javabeat.net -DartifactId=MavenTestWebProject -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false”.
    • DgroupId – This parameter specifying the package path
    • DartifactId – This parameter specifies actual project name
    • DarchetypeArtifactId – This parameter specifies the type of project. maven-archetype-webapp is a standard command for creating the web projects. If you want to create simple Java project, then use the parameter maven-archetype-quickstart.
  2. Note that you have the write permission for the current folder when executing the command.
    • If you don’t have the proper right permission, you may get the error org.apache.maven.BuildFailureException: Error merging velocity templates. This error mostly occurs in the Linux environment. You have to change the write permission to 777 to make it work. Just execute the command sudo chmode 777 / in the current directory.
  3. You should see the console with BUILD SUCCESS message to confirm that set up is right.

You would see the below messages if the build is success.

[code lang=”java”]

krishna@krishna-desktop:~/workspace$ mvn archetype:generate -DgroupId=javabeat.net -DartifactId=MavenTestWebProject -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ————————————————————————
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] — maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom —
[INFO] Generating project in Batch mode
[INFO] —————————————————————————-
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
[INFO] —————————————————————————-
[INFO] Parameter: groupId, Value: javabeat.net
[INFO] Parameter: packageName, Value: javabeat.net
[INFO] Parameter: package, Value: javabeat.net
[INFO] Parameter: artifactId, Value: MavenTestWebProject
[INFO] Parameter: basedir, Value: /home/krishna/workspace
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: /home/krishna/workspace/MavenTestWebProject
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 28.279s
[INFO] Finished at: Sun Oct 13 07:56:57 IST 2013
[INFO] Final Memory: 9M/70M
[INFO] ————————————————————————

[/code]

3. Migrate To Eclipse Project

The above steps are only for creating the project in Maven. But, most of the developers are using Eclipse IDE to maintain the Java projects. It is necessary to make the Maven project compatible to Eclipse IDE. It is easily accomplished by executing a command as follows:

[code lang=”java”]
mvn eclipse:eclipse -Dwtpversion=2.0
[/code]

-Dwtpversion=2.0 is extra parameter to tell the Maven that it is a web project.

4. Project Structure in Maven

When you create Java projects in maven or want to work with Maven, the project structures has to be followed. Look at the figure below to know the typical project structure you would see once build is success.

Maven Project Structure

5. POM.xml

pom.xml is the build script for the Maven enabled projects. For our example, initially created file would look like this:

[code lang=”xml”]
<pre><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>javabeat.net</groupId>
<artifactId>SpringMVCTestFramework</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringMVCTestFramework Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCTestFramework</finalName>
</build>
</project>
[/code]

It is done. You have successfully created the maven project in Eclipse. This tutorial explains only how to setup the project, not to run the projects. I would write few more articles about how to build and run the applications using Maven tools. Hope this article helped you to configure Maven in your system. If you have any questions, please write it in the comments section.

Filed Under: Apache Maven Tagged With: Maven

How To Install Maven On Windows?

October 3, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have written about how to install Maven in Ubuntu?. It is much easier in the Linux OS then setting up in the Windows OS. As we know, Linux does the installation through its package manager and there is no need for the mannual settings of path or anything else. In windows, it’s quite easy too but we need to alter the set of environment variables to make it work. It is very easy to set up using the following steps. (Read : What is Maven? and Custom Plug-In for Maven).

1. Install Maven

Download the maven package from here and extract the zip file to the appropriate location. The toot folder
D:\Softwares\apache-maven-3.1.0
is the M2_HOME values when you are setting the environment variables. There is nothing else to be done for installing the maven package.

2. Set M2_HOME

Open the environment variables for your computer and set the M2_HOME as the maven’s home folder. Be sure to omit any quotation marks around the path even if it contains spaces. Also add the M2 variable in the environemnt variables section as “%M2_HOME%\bin”. Using the same dialog, add the MAVEN_OPTS environment variable in the user variables section to pass the JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.
This is only optional parameter.

Maven Settings

3. Set Path

Add/ Update path variavles for environment and user sections. In the user variable, just append the %M2% to reflect the maven bin folder. In the environment variables section, update the path variable by appending %M2_HOME%\bin.

4. Verify the Maven Installation

The above steps ensure that all the required libraries are in the classpath. Now it is the time to check if the maven is installed properly. Open the command prompt and type mvn –version. If this results in the version details of the maven package, then it is installed properly. Otherwise verify the above steps if you have given the correct path for all the variables. mvn –version would out put the following details on your screen.

[java]

D:\>mvn –version
Apache Maven 3.1.0 (893ca28a1da9d5f51ac03827af98bb730128f9f2; 2013-06-28 07:45:3
2+0530)
Maven home: D:\Softwares\apache-maven-3.1.0
Java version: 1.6.0_25, vendor: Sun Microsystems Inc.
Java home: C:\Program Files\Java\jdk1.6.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"
D:\>

[/java]

Filed Under: Apache Maven Tagged With: Maven, Windows

How To Install Maven On Ubuntu?

October 1, 2013 by Krishna Srinivasan Leave a Comment

Apache Maven is project management tool which is following the concept of a project object model (POM). Maven can manage project’s build and documentation from a central place. Maven 1 actually was started as a sub project of Apache Turbine in 2002. It was released in July 2004 as v1.0. Maven 2 was released in Oct 2005. It was a complete rewrite of the previous project. It was not backward compatible. Maven 3 was released in October 2010 (Read : What is Apache Maven?).

This tutorial explains the steps to install the maven on Ubuntu 12.0.

1. Get Maven Package

Open the terminal and type the command $ apt-cache search maven. The command prompt will display the available packages which is matching the maven word. In the list, you also can see maven – Java software project management and comprehension tool. This package will always have the latest package.

Search Maven in Ubuntu

2. Install The Package

Run the command $ sudo apt-get install maven through the same above terminal. It will ask for the root password and some confirmation messages. Just follow and answer the questions till the installation is completed. Since the installation is done by downloading the entire package, it takes several minutes to download the entire mavan files. Note that you should have internet connection for installing the maven through the command prompt. It is the easiest way to install the package. Wait till the installation is completed.

3. Test The Maven Installation in Ubuntu

Run the command mvn -version to check if the maven is installed properly. You will see the below description on the command prompt.

[java]

krishna@krishna-desktop:~$ mvn -version
Apache Maven 3.0.4
Maven home: /usr/share/maven
Java version: 1.6.0_27, vendor: Sun Microsystems Inc.
Java home: /usr/lib/jvm/java-6-openjdk-i386/jre
Default locale: en_IN, platform encoding: UTF-8
OS name: "linux", version: "3.2.0-51-generic", arch: "i386", family: "unix"

[/java]

Maven is installed successfully. I found the installation on Ubuntu is much simpler than installing on Windows operating system. I would continue writing few more tips on using the various tools on Ubuntu OS. It is great experience on using Ubuntu for developing the Java applications. I would recommend you to try once, then you will never look back.

  • Apache Maven for Beginners
  • How to write a Custom Plugin for Maven?

If you are facing any issues, please write it in the comments section.

Filed Under: Apache Maven Tagged With: Maven, Ubuntu

How to write a Custom Plugin for Maven?

July 8, 2010 by Krishna Srinivasan Leave a Comment

In this article, we will learn about Maven which is a project management framework that provides a configurable approach for managing software projects. Maven covers all the necessary phases that happen right from project creation, building, documentation, reporting, installation and deployment. This article begins with the basics of Maven along with the concepts like Project Object Model (aka POM), the various life-cycles in Maven etc. Then it continues with using Maven for creating a project till installation of the project in a local repository. The latter part of the article provides details about creating custom Maven plugins that can be executed in stand-alone mode as well as part of some Maven life-cycle.

Maven Custom Plug-In (Example Code)

  • Download Sample Program for Maven Custom Plug-In

Maven Concepts

In this section, we will see the basics of Maven concepts like Project Object Model, the standard lifecycles available in Maven as well as the dependency scope that comes up while dealing with dependency with projects.

  • How to install maven on Ubuntu

Project Object Model

Project information, its dependencies and the artifacts that can be built are described in POM which is essentially a configuration file in XML. POM basically contains instructions on what needs to be done during the various life-cycles that happen during a build. Note that the POM is not coupled to java projects, in fact the project can be written in any language like C, C# etc. For example, consider the sample minimal POM,

[java]
<project>

<modelVersion>4.0.0</modelVersion>

<name>adder</name>
<url>https://javabeat.net/adder</url>
<groupId>net.javabeat.adder</groupId>
<artifactId>adder</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>
[/java]

Have a look at the above POM. It defines the information about the project and its dependant projects. We will look into more details about the various POM elements.

  • modelVersion – This defines the version of the POM.
  • name – The name of the project.
  • groupId – This identifies the group (or the organization) that created the project. This property usually takes the domain address which represents the group or the organization so that uniqueness is maintained across the groups.
  • artifactId – This identifies the artifact (output component) name that comes from a project. Artifacts can be anything like a JAR, WAR, EAR etc
  • version – This property identifies the version of the artifact. Usually the version takes the format as “majorVersion.minorVersion-qualifier”. For example, “1.1-alpha”, “1.2-beta”, “1.3-SNAPSHOT”.
    packaging – Represents the type of artifact, for example – jar, war, ear etc.

In the next section in the POM, we have included the dependencies of the project. Note that this section is optional. If there are no dependencies for a project (which is unlikely the case), this can be omitted. However, in this example case, we have declared a dependency to junit and it is expected that the project will contain some test resources. It is always a good idea to define the version of the artifact while defining a dependency, so that during runtime, we are not facing any issues because of version match. We have mentioned the scope as test, more details about this element will follow in the forthcoming section.

  • Log4j configurations

Dependency Scope

A project can depend on a number of dependent projects and Maven provides a way for defining the dependencies among projects through configuration. One can control the level of dependency through scope and the default being ‘compile’. The following scopes are available.

  • Compile – This being the default scope will be available at the classpath during the compilation as well as during runtime.
  • Runtime – The presence of this scope ensures that the dependency will be available at the runtime and not during the compile-time. For example, one may use the Servlet API during the compilation phase, however the Servlet implementation (from Sun, Oracle, IBM etc) will be required during the runtime only.
  • Test – This scope ensures that the dependency is available during the compilation of the test resources as well as during the execution of the test resources.
  • Provided – This dependency is mostly used while developing J2EE applications where the dependency is available as part of the J2EE container (or any Container) and it is not necessary for the project to package the dependency as part of the artifact. For example, while developing Enterprise bean applications, as part of the project, we will be using EJB jar for compilation; however, we never package this jar as part of the project because the EJB container will provide this jar.

Build Life-cycle

A life-cycle defines the execution for achieving a set of goals. Each life-cycle defines a sequence of phases for achieving the goals. There are three standard life-cycles defined in Maven and this section provides a brief summary about them.

  • Clean
  • Build (the default life-cycle)
  • Site

Clean life-cycle

The clean life-cycle accomplishes the goal of deleting the output directory, if present. It in-turn accomplishes this goal by running the phases, pre-clean, clean and post-clean. It is possible to configure custom actions/operations in the pre-clean and the post-clean phases.

Build life-cycle

This is the default life-cycle that maven executes uses during the build process. It has a sequence of phases namely validate, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install and deploy. As you can see the list is huge, in general in this cycle, the necessary resources and sources are generated, processed, compiled and various test steps are executed before package and deployment.

Site life-cycle

This life-cycle is used to generate the documentation and reports pertaining to the project. It is also possible to customize the various aspects during site generation like the content, image, layout etc. This life-cycle contains pre-site, site, post-site and site-deploy phases.

Using Maven

In this section, we will see how to use maven for creating, compiling, building, packaging and installing a project. Download the latest version of Maven from here. Installation of maven will be as simple as un-zipping the downloaded file into a desired directory. In this example, we will be seeing the usage of various maven plugins and goals that contributes to the entire project life-cycle. Before proceeding with the sample, create an environment variable MAVEN_HOME that points to the Maven installation directory and ensure that the PATH variable contains %MAVEN_HOME/bin.

Creating a project

Execute the following command which is used to create the initial project structure.

[java]mvn archetype:create -DgroupId=net.javabeat.emailservice -DartifactId=emailservice[/java]

Note that in archetype:create, archetype represents the plugin prefix and create represents the goal. This goal creates a project with the name emailservice. As soon as this command is executed, one can see a directory called emailservice which has the src folder for holding the main java files, along with java files representing test-cases. The POM file with the name pom.file will also be created with the structure as follows,

pom.xml

[java]
<project>
<modelVersion>4.0.0</modelVersion>

<groupId>net.javabeat.emailservice</groupId>
<artifactId>emailservice</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>emailservice</name>
<url>http://maven.apache.org</url>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>
[/java]

Importing the project in Eclipse

This step is optional for those who are not working with Eclipse being the IDE for developing the project. Change the current directory to emailservice and issue the following command. This goal eclipse creates the project metadata files that are complaint with Eclipse. As soon as the following goal is executed there will be two files generated in the current directory which are .project and .classpath. This is for Eclipse to understand so that the newly created project can be imported in Eclipse IDE to work with.

[java]mvn eclipse:eclipse[/java]

Now, for importing the project into Eclipse, Open Eclipse, go to File -> Import -> Existing Projects into Workspace and navigate to the directory containing the .project and .classpath files and Click OK. Now this project gets imported into Eclipse workspace.

Adding files to project

To make the project meaningful, we will add the following files into the main source folder.

EMail.java

[java]package net.javabeat.emailservice;

public class EMail {

private String fromAddress;
private String toAddress;
private String subject;
private String message;
private String status;

public String getFromAddress() {
return fromAddress;
}

public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}

public String getToAddress() {
return toAddress;
}

public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}
}[/java]

The above class represents the Email model object that will be used by EmailService class for sending email. Given below is the code listing for EMailService class.

EMailService.java

[java]package net.javabeat.emailservice;

public class EMailService {

public EMail sendEmail(String fromAddress, String toAddress, String subject, String message){

EMail emailObject = new EMail();
emailObject.setFromAddress(fromAddress);
emailObject.setToAddress(toAddress);
emailObject.setSubject(subject);
emailObject.setMessage(message);
emailObject.setStatus("SUCCESS");

System.out.println("Sending email from " + fromAddress + " to " + toAddress + "with subject "
+ subject + " having the message contents " + message);
return emailObject;
}
}[/java]

Note that there is no real functionality in the above, all it does is to accept the various user inputs and constructs an email object before returning it.

Compiling the project

The next step is to compile to project, by default the compilation process will create a folder called target and it will place the java class files along with any resource files, if present.

[java]mvn compile[/java]

Note that the location of the target folder as well as the location of the target folder is also configurable.

Packaging the project

This step will package the project with the packaging type mentioned in POM, which is JAR. Before packaging it will also execute the test cases (if specified) in the test folder and the packaged jar will be placed in the target folder.

[java]mvn package[/java]

Installing the project

The final step is to install the jar in a local repository so that other projects, if they are dependant on this project can make references to this project. The following command will install (i.e copy the jar) to the local repository.

[java]mvn install[/java]

Note that, by default, the local repository path will be %USER_HOME%/.m2/repository.

Writing Custom Maven plugins

In this section we will see how to write custom maven plugins. It is possible that the custom maven can be made to run outside the standard life-cycle phase or it can be made to be executed as part of the standard life-cycle phase. We will see how to accomplish both of these items in the following sections.

Creating standalone plugins

In this section, we will write a custom plugin and will see how to write it in stand-alone mode – i.e running the plugin directly without establishing any dependencies on any of the standard life-cycles available in Maven.

Creating the project

The first step is to create the project containing the custom maven plugin. This project is quite different from the regular java project because it is not a regular java artifact like JAR, WAR etc. Instead it is going to be a maven plugin. Issue the following command to create the maven plugin project.

[java]mvn archetype:create -DgroupId=net.javabeat.maven -DartifactId=environment-info -DarchetypeArtifactId=maven-archetype-mojo[/java]

The above command creates a project with the name environment-info with the standard directory layout containing the source and test resources. If you look into the POM file, the package type will be maven-plugin to indicate that this is a maven plugin project.

Importing the project into Eclipse

This step is optional and this is for someone who wishes to work with the project in Eclipse IDE. Issuing the following with the current directory being environment-info creates the Eclipse .project and .classpath files. Now, open Eclipse and go to File -> Import -> Existing Project into Workspace and specify the directory to <<path to environment-info>> directory.

[java]mvn eclipse:eclipse[/java]

Creating the plugin

In Maven, the plugin that achieves a specific task is called by the name MOJO (Maven Old Java Object similar to POJO). A MOJO defines the goal which is nothing but the custom action which is executed upon user’s request. In this example, we will see a custom MOJO that will define the goal of storing all the environmental properties in a text file upon execution. Have a look at the following code,

EnvironmentInfoTask.java

[java]package net.javabeat.maven;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
* @goal env-info
*/
public class EnvironmentInfoTask extends AbstractMojo{

/**
* @parameter
* default-value="log.txt"
* expression="${environment.filename}"
*/
private String fileName;

/**
* @parameter
* default-value="C:\\temp"
* expression="${environment.base_dir}"
*/
private File baseDirectory;

/**
* @parameter
* default-value="true"
* expression="${environment.loggingRequired}"
*/
private boolean loggingRequired;

public void execute() throws MojoExecutionException, MojoFailureException {

StringBuilder fileContents = new StringBuilder();

if (baseDirectory.exists()){
baseDirectory.mkdirs();
log("Created base directory ‘" + baseDirectory.getAbsolutePath() + "’");
}

Map&lt;String, String&gt; environment = System.getenv();
Iterator&lt;Map.Entry&lt;String, String&gt;&gt; entries = environment.entrySet().iterator();

fileContents.append("Environment Information:" + newLine());
fileContents.append("———————————————————–" + newLine());

while (entries.hasNext()){

Map.Entry&lt;String, String&gt; entry = entries.next();
fileContents.append(entry.getKey() + "————-&gt;" + entry.getValue() + newLine());
}

fileContents.append("———————————————————–" + newLine());
writeToFile(fileContents);
log("File contents written");
}

private void log(String message){

if (loggingRequired){
System.out.println(message);
}
}

private static String newLine(){
return System.getProperty("line.separator");
}

private void writeToFile(StringBuilder fileContents){

FileWriter fWriter = null;
BufferedWriter bWriter = null;

try{
fWriter = new FileWriter(baseDirectory + File.separator + fileName);
bWriter = new BufferedWriter(fWriter);
bWriter.write(fileContents.toString());
}catch (Exception e){
log("Error in writing the contents to file -&gt;" + e.getMessage());
}finally{
try{
if (bWriter != null){
bWriter.close();
}
if (fWriter != null){
fWriter.close();
}
}catch (Exception e){
log("Error in closing the resources -&gt;" + e.getMessage());
}
}
}
}[/java]

The first thing to notice is the class EnvironmentInfoTask which is going to persist the environmental information into a file extends AbstractMojo class which in turn extends the Mojo interface. Note that the goal for this MOJO is annotated using XDoclet using goal attribute with the name env-info. The method that will be called during execution of the MOJO is execute(). This method does the job of persisting the environmental properties by taking information from the various properties .

  • Base Directory – the directory under which the log file name will be created which is of type ‘java.io.File’. Note that we have used XDoclet ‘parameter’ for annotating this property. This property has the default value ‘C:\\temp’ which means the this is the default location for the log file. However, this value can be overridden at runtime by specifying the property ‘environment.base_dir’ which is an expression and its value will be resolved at runtime
  • Filename – the name of the log file into which the environmental properties will be written. Note that the default value for the log file name is ‘log.txt’. However, during runtime, the value can be overridden through the property ‘environment.filename’
  • Logging Required – whether logging information on what this MOJO is doing has to be shown. The default value being true can be overridden by specifying the value false to the property ‘environment.loggingRequired’.

Compiling the project

Issue the following command for compiling the maven plugin project.

[java]mvn compile[/java]

Packaging the project

The following command is used to package the plugin project.

[java]mvn package[/java]

Installing the project

For installing the project into the local Maven repository, issue the following command.

[java]mvn install[/java]

Usually, on Windows, the local repository is %USER_HOME%/.m2/repository. On Windows XP, USER_HOME will expand to "C:\\Document and Settings\\<<UserName>>", however in Windows Vista it is "C:\\Users\\<<UserName>>".

Running the project

There are several ways to run the maven plugin. We will see them one by one. Generally running a Maven plugin takes the following form,

[java]mvn groupId:artifactId:version:goalName[/java]

In our case, the group id is net.javabeat.maven, artifact id is environment-info, version is 1.0-SNAPSHOT and goal name is env-info. So running the following command will run the custom plugin

[java]mvn net.javabeat.maven:environment-info:1.0-SNAPSHOT:env-info[/java]

Running the above command will create a directory C:\\temp (if not present) and create a file name with log.txt with the environment information. Because logging is enabled by default, the text ‘Created base directory C:\temp‘ and ‘File contents are written’ will be displayed in the console.

It is also possible to configure the plugin by passing alternate input values. Have a look at the following command. This command specifies an alternate base directory C:\\temp-new for the log file newLog.txt with logging turned off. Note that for passing a property to a plugin the standard way is –DpropertyName=propertyValue.

[java]mvn net.javabeat.maven:environment-info:1.0-SNAPSHOT:env-info -Denvironment.base_dir=
C:\temp-new -Denvironment.filename=newLog.txt -Denvironment.loggingRequired=false[/java]

It is also possible to omit the version information while running the plugin in which case, Maven tries to find the recent version for the plugin by comparing the version strings. In our case, this wouldn’t happen, because we have only one version which is 1.0-SNAPSHOT. So the following command will also work.

[java]mvn net.javabeat.maven:environment-info:env-info[/java]

Another approach to run the plugin is by omitting the group id and just specifying the artifact id along with the goal name. However, for this to happen, we have to add the group id to the default list of groups that Maven will look for. Open the file %MAVEN_HOME%/conf/settings.xml and add the following line under the element pluginsGroup.

[java]<pluginGroup>net.javabeat.maven</pluginGroup>[/java]

This ensures that we have added the group net.javabeat.maven to the list of default groups that Maven will search for, because of which the following command will work.

[java]mvn environment-info:env-info[/java]

Attaching plugins to existing life-cycle

So far, we have seen how to run a custom plugin in stand-alone mode. This is not of much-use and Maven provides a way for binding the goals of any custom plugin into existing build cycle. For example, let us consider that we have written a custom plugin which will simply print the current date and we want this plugin to be executed during the compilation phase and the installation phase of a project. We will see how to accomplish this goal in this section.

The following listing shows the custom plugin which will simply emit the date information.

DateInfo.java

[java]package net.javabeat.maven;

import java.util.Date;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
* @goal date-info
*/
public class DateInfo extends AbstractMojo {

public void execute() throws MojoExecutionException, MojoFailureException {

Date currentDate = new Date();
getLog().info("Current date is " + currentDate);
}
}[/java]

Follow the same process of creating the project, then creating the plugin, compilation, packaging and installation as we have discussed before. We will see how to attach this custom plugin during the compile and the install phase. Open POM.xml file and add the following after the project dependencies element,

[java]
<build>
<plugins>
<plugin>
<groupId>net.javabeat.maven</groupId>
<artifactId>environment-info</artifactId>
<version>1.0-SNAPSHOT</version>

<executions>
<execution>
<id>date-info-compile</id>
<phase>compile</phase>
<goals>
<goal>date-info</goal>
</goals>
</execution>

<execution>
<id>date-info-install</id>
<phase>install</phase>
<goals>
<goal>date-info</goal>
</goals>
</execution>

</executions>

</plugin>
</plugins>
</build>
[/java]

Though the above XML fragment is big, it is fairly simple. First thing is, it defines the execution element where we can define goals for executions. We have defined two execution elements one for the compile phase and the other for the install phase and we have given appropriate id for each execution element. Have a note at the goals section. We have included our custom goal date-info which will display the current date information. Note that where to search for the goal’s group id and the artifact id along with optional version is defined just above the executions element.

After this whenever we run mvn compile and mvn install for any project that contains the above definition we will see that the goal date-info getting invoked during the phases.

Conclusion

In this article, we have seen how to use Maven for creating projects and to manage dependencies between projects. We have seen Maven simplifying the task of creating, compiling, packaging, installing projects thereby reducing the pain from developers and build managers. Also discussed in the article are the extension capabilities provided by Maven for pluging-in custom plugins in the form of MOJOs.

Filed Under: Apache Maven Tagged With: Maven

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved