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
  • Contact Us

Hibernate One-To-One Mapping(XML mapping)

March 15, 2013 by Manisha Patil Leave a Comment

In this tutorial we will write a simple Java project to demonstrate Hibernate one to one Mapping. We shall use HSQL as the database and Maven for creating the project and making it compatible with eclipse. We will first create a Java project using Maven and then will add Hibernate on it. HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here. If you are beginner for hibernate, please read the articles about introduction to hibernate, interceptors in hibernate and spring & hibernate integration. We also recommend good reference books for learning hibernate in our post about hibernate books.

  • [download id=”15″]

hibernate-mapping

One To One Relationship

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. Consider the following relationship:

hibernate_onetoone_mapping

According to the relationship each Person should have a unique address. Hence we will need two tables namely PERSON and ADDRESS to create this relation. The relational model is shown below:
onetoone_table_relation

Hence following points would be included in our example project demonstrating One-to-One relationship :

  1. We will write two POJO classes (Person.java and Address.java ) and corresponding mapping files would be Person.hbm.xml and Address.hbm.xml respectively. Here the relation is, one address is assigned for one person only.
  2. To achieve one to one relationship, both tables have the same PERSON_ID as primary key. In ADDRESS table, PERSON_ID is the primary key and also a foreign key to PERSON table. This is the common way of define “one-to-one” table relationship.

Pre-Requisites

Following are the tools and technologies required for this project:

  1. Java JDK 5 or above
  2. Eclipse IDE 3.2 or above
  3. Maven 3.0 or above
  4. Hibernate 3.0 or above (Download from http://hibernate.org/downloads)
  5. HsqlDB (Download from http://hsqldb.org/)

1. Generating Maven Java project compatible with Eclipse

We will create a Java project using Maven (Refer post Creating Simple Java Project Using Apache Maven). Open the command line window and execute the following command:

[java]
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateOneToOneXML
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
[/java]

On execution of the above command, a java project HibernateOneToOneXML is created (In our case we have created it in the directory C:\HibernateProject). This java project already has a directory structure (as explained in the post (Refer post Creating Simple Java Project Using Apache Maven). To make this project compatible with eclipse, let’s execute the following command:

[java]
mvn eclipse:eclipse
[/java]

2. Import project into Eclipse

Open Eclipse and import the above Java project as explained below:

File > Import… > General > Existing Projects into Workspace > Choose above Java project

Build-path settings
Goto Window > Preferences… > Java > Build Path > Classpath Variables >

  • Define new variable M2_REPO pointing to your local maven repository. (In our case it is:C:/Documents and Settings/Manisha/.m2/repository).
  • Define new variable HSQLDB pointing to the hsqldb.jar. (C:/tools/hsqldb-2.2.9/hsqldb/lib/hsqldb.jar).

classpath_setting

3. Adding the Hibernate and HSQLDB Dependency to pom.xml

We need to add the Hibernate, HSQLDB and some other dependencies to the Maven pom.xml as shown below:

[java]
<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>net.javabeat.hibernate</groupId>
<artifactId>HibernateOneToOneXML</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateOneToOneXML</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!– Hibernate library dependecy start –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>4.1.9.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>hibernate-tools</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>jta</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>oscache</groupId>
<artifactId>oscache</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>persistence-api</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!– Hibernate library dependecy end –>
</dependencies>
</project>
[/java]

As a next step, let’s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath.

[java]
mvn eclipse:eclipse
[/java]

4. Create Model Classes

As a next step let’s create the model classes
src\main\java\net\javabeat\hibernate\Person.java and src\main\java\net\javabeat\hibernate\Address.java as below:

Person.java

[java]
package net.javabeat.hibernate;

import java.io.Serializable;

/**
* Model class for Person
*/
public class Person implements Serializable {
private Long personId;
private String name;

private Address address;

public Person() {
}

public Long getPersonId() {
return personId;
}

public void setPersonId(Long personId) {
this.personId = personId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

}
[/java]

Address.java

[java]
package net.javabeat.hibernate;

import java.io.Serializable;

public class Address implements Serializable {
private String street;
private String city;
private String state;
private String zipcode;
private Person person;
private Long personId;

public Address() {

}

public Address(String street, String city, String state, String zipcode) {
this.street = street;
this.city = city;
this.state = state;
this.zipcode = zipcode;

}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getZipcode() {
return zipcode;
}

public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}

public Long getPersonId() {
return personId;
}

public void setPersonId(Long personId) {
this.personId = personId;
}

}
[/java]

Hibernate Mapping Files

Next let’s write a Hibernate XML Mapping files to the directory:/src/main/resources . Create the resources directory as follows: Right click on Project > New > Source Folder > Give folder name “/src/main/resources/” and click Finish.
Write the file src\main\resources\net\javabeat\hibernate\Person.hbm.xml for the model Person and
src\main\resources\net\javabeat\hibernate\Address.hbm.xml for the model class Address.
The contents of these files are as below:

Person.hbm.xml

[java]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="net.javabeat.hibernate.Person" table="person">
<id name="personId" type="java.lang.Long">
<column name="PERSON_ID" />
<generator class="native" />
</id>

<property name="name" type="string">
<column name="NAME" length="10" not-null="true" unique="true" />
</property>
<one-to-one name="address" class="net.javabeat.hibernate.Address"
cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
[/java]

Address.hbm.xml

[java]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="net.javabeat.hibernate.Address" table="address">
<meta attribute="class-description">This class contains the address of each person
details.</meta>
<id name="personId" type="java.lang.Long">
<column name="PERSON_ID" />
<generator class="foreign">
<param name="property">person</param>
</generator>

</id>
<one-to-one name="person" class="net.javabeat.hibernate.Person"
constrained="true"></one-to-one>
<property name="street" column="ADDRESS_STREET" type="string"
length="250" />
<property name="city" column="ADDRESS_CITY" type="string"
length="50" />
<property name="state" column="ADDRESS_STATE" type="string"
length="50" />
<property name="zipcode" column="ADDRESS_ZIPCODE" type="string"
length="10" />

</class>
</hibernate-mapping>
[/java]

In the above hibernate mapping file we are implementing One-to-One relationship. For both the model classes we are using a single primary key personId. In Adress hbm file we have defined a foreign identifier generator so that primary it uses primary key of Person table.

5. Adding Hibernate Configuration file

As a next step let’s add the hibernate.cfg.xml to the directory:/src/main/resources . Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:

[java]
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!– Database connection settings, Connect to HSQL, IN Memory –>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:test</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>

<!– JDBC connection pool (use the built-in) –>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property><property name="format_sql">true</property>

<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!–create the database schema on startup if required –>
<property name="hbm2ddl.auto">update</property>
<!– <mapping class="entities.Subscriber"/> –>
<mapping resource="net/javabeat/hibernate/Person.hbm.xml"></mapping>
<mapping resource="net/javabeat/hibernate/Address.hbm.xml"></mapping>

</session-factory>
</hibernate-configuration>

[/java]

In the above file we have set the database connection to HSQL-In memory database (mem is in-memeory, and test is the database name). The show_sql option, if set to true will display all the executed SQL queries on the console. The property hbm2ddl.auto , if set to update, will change the existing database schema on each start up. In the end we add the Person.hbm.xml and Address.hbm.xml files to the configuration.

Note : In case you want to use any other database then, you need to change these properties –
“dialect”, “connection.driver_class”, “connection.url”, “connection.username”, and “connection.password”

6. Create Utility class

Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file src\main\java\net\javabeat\hibernate\HibernateUtil.java as below:

[java]
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
[/java]

7. Revise the App class

Next we will revise the App.java (generated by Maven). This class tests the one-to-one relationship by creating and listing the person names and coressponding addresses as below:

[java]
package net.javabeat.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
* Main class
*
*/
public class App {
public static void main(String[] args) {
System.out.println("Maven + Hibernate + HSQL XML One to One Mapping ");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
App app = new App();

Address address1 = new Address("M.G.Road", "Bangalore", "Karnataka",
"56000");
Address address2 = new Address("Tilak Road", "Pune", "Maharashtra",
"411207");

app.savePersonInfo("Jiya", address1);
app.savePersonInfo("Manisha", address2);

app.listPersonInfo();

}

public Long savePersonInfo(String personName, Address address) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Long personId = null;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Person person = new Person();
person.setName(personName);

person.setAddress(address);
address.setPerson(person);
session.save(person);

transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return personId;
}

/*
* Lists the person’s from database table
*/
public void listPersonInfo() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
@SuppressWarnings("unchecked")
List<Person> personList = session.createQuery("from Person").list();
for (Iterator<Person> iterator = personList.iterator(); iterator
.hasNext();) {
Person person = (Person) iterator.next();
System.out.println(person.getName());
System.out.println(person.getAddress().getStreet() + " "
+ person.getAddress().getCity() + " "
+ person.getAddress().getState() + " "
+ person.getAddress().getZipcode());
}
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}
[/java]

Here the savePersonInfo() method is used to save a new Person object and Address object to the database. In the savePersonInfo() method a new object of the Person class is created and the name value and address is set. The personId value is auto generated so the value need not be set here. We then save the Person object to the Address object. The session.save() method is used to persist the value in the database and once the value is saved, the id value (Primary key) is returned. Once the object is saved, the transaction is committed. If any exception occurs then the transaction is rolledback. The transaction ends either through commit or rollback action. Once the transaction ends the session is closed.

The listPersonInfo() method is used to list name of each person in PERSON table and their corresponding addresses from ADDRESS table. Here we use Hibernate Query Language (HQL). The query “from Person” returns a list of all the data in the PERSON table and their corresponding addresses from ADDRESS table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Person and corresponding Address table and hence display them on the console.

8. Final project structure

Once you have created all these source files, your project structure should look like following:
onetoone_dir_struct

9. Execution of the above code

Now let us execute the code we created above. Let’s run the App class.
Right click on App.java >Run As > Java Application.
On start of each thread, a database schema will be created and the following actions will happen.

Output on the console:
Following output is displayed on the console:

[java]
Maven + Hibernate + HSQL XML One to One Mapping
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
person
(PERSON_ID, NAME)
values
(null, ?)
Hibernate:
insert
into
address
(ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIPCODE, PERSON_ID)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
person
(PERSON_ID, NAME)
values
(null, ?)
Hibernate:
insert
into
address
(ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIPCODE, PERSON_ID)
values
(?, ?, ?, ?, ?)
Hibernate:
select
person0_.PERSON_ID as PERSON1_0_,
person0_.NAME as NAME0_
from
person person0_
Hibernate:
select
address0_.PERSON_ID as PERSON1_1_0_,
address0_.ADDRESS_STREET as ADDRESS2_1_0_,
address0_.ADDRESS_CITY as ADDRESS3_1_0_,
address0_.ADDRESS_STATE as ADDRESS4_1_0_,
address0_.ADDRESS_ZIPCODE as ADDRESS5_1_0_
from
address address0_
where
address0_.PERSON_ID=?
Hibernate:
select
address0_.PERSON_ID as PERSON1_1_0_,
address0_.ADDRESS_STREET as ADDRESS2_1_0_,
address0_.ADDRESS_CITY as ADDRESS3_1_0_,
address0_.ADDRESS_STATE as ADDRESS4_1_0_,
address0_.ADDRESS_ZIPCODE as ADDRESS5_1_0_
from
address address0_
where
address0_.PERSON_ID=?
Jiya
M.G.Road Bangalore Karnataka 56000
Manisha
Tilak Road Pune Maharashtra 411207

[/java]

Summary

  • [download id=”15″]

In this post we first created a simple Java project using Maven and made it compatible with eclipse. Then we added the Hibernate one to one relation by creating two hibernate XML files Person and Address and relating them uing the one-to-one tag in both the files. We used a simple HSQL database, to insert records into Person and Address table and also listed these records. In the next article we shall look into Hibernate One-To-One Mapping using Java Annotations. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here

Filed Under: Hibernate Tagged With: Hibernate

Hibernate, Maven and HSQL – Example Project (Using Annotations)

March 11, 2013 by Manisha Patil Leave a Comment

In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven using Java 5 Annotations. For this we will use our previous example in the post Hibernate, Maven and HSQL – Example Project (XML Mapping)) as base and convert it from XML Mapping to Annotation.
HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here. If you are beginner for hibernate, please read the articles about introduction to hibernate, interceptors in hibernate and spring & hibernate integration. We also recommend good reference books for learning hibernate in our post about hibernate books.hibernate.

Following are the tools and technologies required for this project:

    1. Java JDK 5 or above
    2. Eclipse IDE 3.2 or above
    3. Maven 3.0 or above
    4. Hibernate 3.0 or above (Download from http://hibernate.org/downloads)
    5. HsqlDB (Download from http://hsqldb.org/)

1. Generating Maven Java project compatible with Eclipse

Follow the steps in the post Hibernate, Maven and HSQL – Example Project (XML Mapping)) to create project structure. Or you can directly download the source code from above post in Eclipse and rename the project in eclipse as HibernateHelloWorldAnnotation.

2.Updating the Hibernate dependency in pom.xml

As we are going to use Annotation mapping in Hibernate we will update our existing pom.xml file as below:

[java]
<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>net.javabeat.hibernate</groupId>
<artifactId>HibernateHelloWorldXML</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateHelloWorldXML</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!– Hibernate library dependecy start –>
<b> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>4.1.9.Final</version>
</dependency></b>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>hibernate-tools</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>jta</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>oscache</groupId>
<artifactId>oscache</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>persistence-api</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!– Hibernate library dependency end –>
</dependencies>
</project>
[/java]

As a next step, let’s execute the following command so that maven will download all the required JARs and update eclipse classpath. Go to the directory of the project (in our case it is C:\HibernateHelloWorldXML) and execute the following command:

[java]
mvn eclipse:eclipse
[/java]

This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project > Maven > Enable Dependency Management.

3. Delete the unused Hibernate Mapping file

The file src\main\resources\net\javabeat\hibernate\Contact.hbm.xml is not required anymore. Delete this file from the project.

4. Update the Model class file

We will add simple annotations to the model class (src\main\java\net\javabeat\hibernate\Contact.java) as below:

[java]
package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* Model class for Conact
*/
@Entity
@Table(name="CONTACT")
public class Contact implements Serializable {
@Id
@GeneratedValue
private Integer contactId;

@Column(name="name")
private String name;

public Contact() {
}

public Integer getContactId() {
return contactId;
}

public void setContactId(Integer contactId) {
this.contactId = contactId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
[/java]

5.Update the Hibernate Utility class

In our previous post for XML mapping, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:

[java]
sessionFactory = new Configuration().configure().buildSessionFactory();
[/java]

We will update this and use AnnotationConfiguration instead of Configuration(). The updated HibernateUtil.java file is as below:

[java]
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
[/java]

6. Update Hibernate Configuration file

The configuration file hibernate.cfg.xml, needs to be changed to add the new Annotation based entity class Contact.java instead of old XML Mapping Contact.hbm.xml. The updated src\main\resources\hibernate.cfg.xml is as below:

[java]
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!– Database connection settings, Connect to HSQL, IN Memory –>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:test</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>

<!– JDBC connection pool (use the built-in) –>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property><property name="format_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!–create the database schema on startup if required –>
<property name="hbm2ddl.auto">update</property>
<mapping class="net.javabeat.hibernate.Contact"></mapping>
</session-factory>
</hibernate-configuration>
[/java]

Here we have replaced

[java]
<mapping resource="net/javabeat/hibernate/Contact.hbm.xml"></mapping>
[/java]

with

[java]
<mapping class="net.javabeat.hibernate.Contact"></mapping>
[/java]

7. Final project structure

Once you have created all these source files, your project structure should look like following:
final_proj_stuct_annotation

8. Execution of the above code

Now let us execute the code we created above. Let’s run the App class.
Right click on App.java >Run As > Java Application.
On start of each thread, a database schema will be created and the following actions will happen.

    • Each time a new thread starts the database schema will change the existing one as we have set hbm2ddl.auto option to update.
    • The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.

Output on the console:

[java]
Maven + Hibernate + HSQL
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
CONTACT
(contactId, name)
values
(null, ?)
Hibernate:
insert
into
CONTACT
(contactId, name)
values
(null, ?)
Hibernate:
insert
into
CONTACT
(contactId, name)
values
(null, ?)
Hibernate:
select
contact0_.contactId as contactId0_,
contact0_.name as name0_
from
CONTACT contact0_
Jiya
Manisha
Riya
[/java]

Summary

In this post we updated our previous Java project from post Hibernate, Maven and HSQL – Example Project (XML Mapping)) using Maven and made it compatible with eclipse. Then we updated the Hibernate configuration file and also deleted the hibernate mapping file. We also updated our Model class with Java annotations. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into Hibernate Association (One-to-one mapping(XML mapping)). If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here

Filed Under: Hibernate Tagged With: Hibernate, MySQL

Hibernate, Maven and HSQL – Example Project (XML Mapping)

March 2, 2013 by Manisha Patil Leave a Comment

In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven. We will first create a Java project using Maven and then will add Hibernate on it. HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here. If you are beginner for hibernate, please read the articles about introduction to hibernate, interceptors in hibernate and spring & hibernate integration. We also recommend good reference books for learning hibernate in our post about hibernate books.hibernate.

Following are the tools and technologies required for this project:

    1. Java JDK 5 or above
    2. Eclipse IDE 3.2 or above
    3. Maven 3.0 or above
    4. Hibernate 3.0 or above (Download from http://hibernate.org/downloads)
    5. HsqlDB (Download from http://hsqldb.org/)
  • Download Source Code: [download id=”11″]

1. Generating Maven Java project compatible with Eclipse

We will create a Java project using Maven (Refer post Creating Simple Java Project Using Apache Maven). Open the command line window and execute the following command:

[java]
mvn archetype:generate
-DgroupId=net.javabeat.hibernate
-DartifactId=HibernateHelloWorldXML
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
[/java]

On execution of the above command, a java project HibernateHelloWorldXML is created (In our case we have created it in the directory C:\HibernateProject). This java project already has a directory structure (as explained in the post (Refer post Creating Simple Java Project Using Apache Maven)). To make this project compatible with eclipse, let’s execute the following command:

[java]
mvn eclipse:eclipse
[/java]

The goal eclipse:eclipse generates the following eclipse configuration files:

  • .project and .classpath files.
  • .setting/org.eclipse.jdt.core.prefs with project specific compiler settings.
  • Various configuration files for WTP (Web Tools Project), if the parameter wtpversion is set to a valid version (WTP configuration is not generated by default).

2. Import project into Eclipse

Open Eclipse and import the above Java project as explained below:

File > Import… > General > Existing Projects into Workspace > Choose above Java project

Once the project is imported the directory structure would be as in the screen below:
dir_struct_eclipse

Build-path settings
Goto Window > Preferences… > Java > Build Path > Classpath Variables >

  • Define new variable M2_REPO pointing to your local maven repository. (In our case it is:C:/Documents and Settings/Manisha/.m2/repository).
  • Define new variable HSQLDB pointing to the hsqldb.jar. (C:/tools/hsqldb-2.2.9/hsqldb/lib/hsqldb.jar).

classpath_setting

3. Adding the Hibernate and HSQLDB Dependency to pom.xml

We need to add the Hibernate, HSQLDB and some other dependencies to the Maven pom.xml as shown below:

[java]
<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>net.javabeat.hibernate</groupId>
<artifactId>HibernateHelloWorldXML</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateHelloWorldXML</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!– Hibernate library dependecy start –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>4.1.9.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>hibernate-tools</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>jta</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>oscache</groupId>
<artifactId>oscache</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>persistence-api</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!– Hibernate library dependecy end –>
</dependencies>
</project>
[/java]

As a next step, let’s execute the following command so that maven will download all the required JARs and add the same to eclipse classpath.

[java]
mvn eclipse:eclipse
[/java]

This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project > Maven > Enable Dependency Management.

4. Create Model Class and Hibernate Mapping file

As a next step let’s create the model class (src\main\java\net\javabeat\hibernate\Contact.java) as below:

[java]
package net.javabeat.hibernate;
import java.io.Serializable;
/**
* Model class for Contact
*/
public class Contact implements Serializable {
private Integer contactId;
private String name;

public Contact() {
}

public Integer getContactId() {
return contactId;
}

public void setContactId(Integer contactId) {
this.contactId = contactId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
[/java]

Next let’s write a Hibernate XML Mapping file to the directory:/src/main/resources . Create the resources directory as follows: Right click on Project > New > Source Folder > Give folder name “/src/main/resources/” and click Finish. Write the file src\main\resources\net\javabeat\hibernate\Contact.hbm.xml for the Model class as below:

[java]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="net.javabeat.hibernate.Contact" table="contact">
<id name="contactId" type="java.lang.Integer">
<column name="CONTACT_ID" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="NAME" length="10" not-null="true" unique="true" />
</property>
</class>
</hibernate-mapping>
[/java]

The details of the above file are as below:

  • The hibernate-mapping element is the root element.
  • The class element is used to map the Java class with the database table.
  • The Java class name is specified using the name attribute of the class element
  • The database table name is specified using the table attribute of the class element.
  • The id element is used to create the primary key.
  • The name attribute of the id element refers to the property in the Contact class and the column attribute refers to the column in the CONTACT table.
  • The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type and vice versa.
  • The generator element within the id element is used to automatically generate the primary key values.
  • The property element is used to link a property in the Java class to a column in the database table.

5. Adding Hibernate Configuration file

As a next step let’s add the hibernate.cfg.xml to the directory:/src/main/resources . Write the new file hibernate.cfg.xml in this directory. The hibernate.cfg.xml is as follows:

[java]
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!– Database connection settings, Connect to HSQL, IN Memory –>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:test</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>

<!– JDBC connection pool (use the built-in) –>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property><property name="format_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!–create the database schema on startup if required –>
<property name="hbm2ddl.auto">update</property>
<mapping resource="net/javabeat/hibernate/Contact.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
[/java]

In the above file we have set the database connection to HSQL-In memory database (mem is in-memeory, and test is the database name). The show_sql option, if set to true will display all the executed SQL queries on the console. The property hbm2ddl.auto , if set to update, will change the existing database schema on each startup. In the end we add the Contact.hbm.xml file to the configuration.

Note : In case you want to use any other database then, you need to change these properties –
“dialect”, “connection.driver_class”, “connection.url”, “connection.username”, and “connection.password”

6. Create Utility class

Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file src\main\java\net\javabeat\hibernate\HibernateUtil.java as below:

[java]
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
[/java]

7. Revise the App class

Next we will revise the App.java (generated by Maven), to create and list the contact names as below:

[java]
package net.javabeat.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class App {
public static void main(String[] args) {
System.out.println("Maven + Hibernate + HSQL");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
App app = new App();
app.saveContact("Jiya");
app.saveContact("Manisha");
app.saveContact("Riya");
app.listContact();
}

public Integer saveContact(String contactName) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Integer contactId = null;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Contact contact = new Contact();
contact.setName(contactName);
contactId = (Integer) session.save(contact);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return contactId;
}

public void listContact() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
@SuppressWarnings("unchecked")
List<Contact> contactList = session.createQuery("from Contact")
.list();
for (Iterator<Contact> iterator = contactList.iterator(); iterator
.hasNext();) {
Contact contact = (Contact) iterator.next();
System.out.println(contact.getName());
}
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}
[/java]

Here the saveContact() method is used to save a new Contact object to the database. In the saveContact() method a new object of the Contact class is created and the contactName value is set, the contactId value is auto generated so the value need not be set here. The session.save() method is used to persist the value in the database and once the value is saved, the id value (Primary key) is returned. Here the contactId value is of type Integer so we typecast the returned value to Integer. Once the object is saved, the transaction is committed. If any exception occurs then the transaction is rolledback. The transaction ends either through commit or rollback action. Once the transaction ends the session is closed.

The listContact() method is used to list all the contacts. The session.createQuery() method is used to create a query object which helps in retrieving the persistant objects. Here we use Hibernate Query Language (HQL). “from Contact” returns a list of all the contacts in the CONTACT table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list of contacts and display them on the console.

8. Final project structure

Once you have created all these source files, your project structure should look like following:
final_proj_stuct

9. Execution of the above code

Now let us execute the code we created above. Let’s run the App class.
Right click on App.java >Run As > Java Application.
On start of each thread, a database schema will be created and the following actions will happen.

    • Each time a new thread starts the database schema will change the existing one as we have set hbm2ddl.auto option to update.
    • The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.

Output on the console:
console

Summary

  • Download Source Code: [download id=”11″]

In this post we first created a simple Java project using Maven and made it compatible with eclipse. Then we added the Hibernate XML mapping to this project. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into creating hibernate project using Java Annotations. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here

Filed Under: Hibernate Tagged With: Hibernate

Creating Simple Web Application Using Apache Maven

February 23, 2013 by Manisha Patil Leave a Comment

In the previous post we saw how to create simple Java project using Maven. We will create a simple web application. The goal of this post is to highlight the basic features Maven provides to develop web applications. This post covers the following :

  • Create simple web application using Maven Archetype plugin.
  • Prepare the Tomcat Manager application.
  • Define Tomcat Server in Maven settings.
  • Point POM to Tomcat Server.
  • Build and Deploy the web application to Tomcat server.

If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here.

  • Apache Maven 2.0 – Maven Plugins
  • Buy: Apache Maven Implementation from flipkart.com

apache maven

Create Simple Web Application using Maven

To create a web application we will use maven-archetype-webapp plugin. Run mvn archetype:generate with an artifactId and a groupId. Open command line window, point to the desired directory (here we are creating project under C:MVNProject project) and execute the following command:

[java]
C:MVNProject&amp;gt;mvn archetype:generate -DgroupId=net.javabeat -DartifactId=SampleWebapp
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
[/java]

Maven Commands

    • mvn : is the Maven command.
    • archetype:generate : is called a Maven goal, analogous to an ANT target. It describes a unit of work to be completed in a build. The purpose of this goal is to quickly create(goal) a project from an archetype(plugin).
    • -Dname=value pairs : (DgroupId, DartifactId, DarchetypeArtifactId, DinteractiveMode) These are the arguments which are passed to the goal.They take the form of -D properties, similar to the system property options which you pass to the Java Virtual Machine via the command line.

The output on executing the above command is:

[java]
C:MVNProject&amp;gt;mvn archetype:generate -DgroupId=net.javabeat -DartifactId=SampleWebapp
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
[INFO] Scanning for projects…
Downloading: https://www.javabeat.net/pluginrepo1/org/codehaus/mojo/maven-metadata.xml
Downloading: https://www.javabeat.net/pluginrepo1/org/apache/maven/plugins/maven-metadata.xml
[WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xml from pluginrepo1
(https://www.javabeat.net/pluginrepo1/): Error transferring file: Connection reset
[WARNING] Could not transfer metadata org.codehaus.mojo/maven-metadata.xml from pluginrepo1
(https://www.javabeat.net/pluginrepo1/): Error transferring file: Connection reset
Downloading: https://www.javabeat.net/pluginrepo1/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml
[WARNING] Could not transfer metadata org.apache.maven.plugins:maven-archetype-plugin/maven-metadata.xml
from pluginrepo1 (https://www.javabeat.net/pluginrepo1/): Error transferring file: Connection reset
[INFO]
[INFO] ————————————————————————
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ————————————————————————
Downloading: https://www.javabeat.net/pluginrepo1/org/apache/maven/plugins/maven-metadata.xml
Downloading: https://www.javabeat.net/pluginrepo1/org/codehaus/mojo/maven-metadata.xml
[WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xml from pluginrepo1
(https://www.javabeat.net/pluginrepo1/): Error transferring file: Connection reset
[WARNING] Could not transfer metadata org.codehaus.mojo/maven-metadata.xml from pluginrepo1
(https://www.javabeat.net/pluginrepo1/): Error transferring file: Connection reset
Downloading: https://www.javabeat.net/pluginrepo1/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml
[WARNING] Could not transfer metadata org.apache.maven.plugins:maven-archetype-plugin/maven-metadata.xml
from pluginrepo1 (https://www.javabeat.net/pluginrepo1/): Error transferring file: Connection reset
[INFO]
[INFO] &amp;gt;&amp;gt;&amp;gt; maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom &amp;gt;&amp;gt;&amp;gt;
[INFO]
[INFO] &amp;lt;&amp;lt;&amp;lt; maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom &amp;lt;&amp;lt;&amp;lt;
[INFO]
[INFO] — maven-archetype-plugin:2.0: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: net.javabeat
[INFO] Parameter: packageName, Value: net.javabeat
[INFO] Parameter: package, Value: net.javabeat
[INFO] Parameter: artifactId, Value: SampleWebapp
[INFO] Parameter: basedir, Value: C:MVNProject
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] project created from Old (1.x) Archetype in dir: C:MVNProjectSampleWebapp
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 10:01.500s
[INFO] Finished at: Fri Feb 22 21:32:54 IST 2013
[INFO] Final Memory: 8M/24M
[INFO] ————————————————————————
[/java]

Maven creates the complete web based java application project structure as in the screen below:
webapp_struct

We see that a default pom.xml has been created. POM file generated is:

[java]
&amp;lt;project xmlns=&amp;quot;http://maven.apache.org/POM/4.0.0&amp;quot; xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;
xsi:schemaLocation=&amp;quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&amp;quot;&amp;gt;
&amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;
&amp;lt;groupId&amp;gt;net.javabeat&amp;lt;/groupId&amp;gt;
&amp;lt;artifactId&amp;gt;SampleWebapp&amp;lt;/artifactId&amp;gt;
&amp;lt;packaging&amp;gt;war&amp;lt;/packaging&amp;gt;
&amp;lt;version&amp;gt;1.0-SNAPSHOT&amp;lt;/version&amp;gt;
&amp;lt;name&amp;gt;SampleWebapp Maven Webapp&amp;lt;/name&amp;gt;
&amp;lt;url&amp;gt;http://maven.apache.org&amp;lt;/url&amp;gt;
&amp;lt;dependencies&amp;gt;
&amp;lt;dependency&amp;gt;
&amp;lt;groupId&amp;gt;junit&amp;lt;/groupId&amp;gt;
&amp;lt;artifactId&amp;gt;junit&amp;lt;/artifactId&amp;gt;
&amp;lt;version&amp;gt;3.8.1&amp;lt;/version&amp;gt;
&amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;
&amp;lt;build&amp;gt;
&amp;lt;finalName&amp;gt;SampleWebapp&amp;lt;/finalName&amp;gt;
&amp;lt;/build&amp;gt;
&amp;lt;/project&amp;gt;
[/java]

Here we notice that the packaging element has a value war. A project with a war packaging creates a WAR file in the target directory. Default name of this file is ${artifactId}-${version}.war. Hence our WAR generated would be in target/SampleWebapp-1.0-SNAPSHOT.war. The element finalName customizes the name of the generated WAR.

Maven also created a sample JSP Source file index.jsp:

[java]
&amp;lt;html&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;h2&amp;gt;Hello World!&amp;lt;/h2&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
[/java]

Prepare the Tomcat Manager application

We will deploy our web application to Tomcat server. We first need to ensure that we can access the Tomcat Manager application at: http://localhost:8080/manager/html. Just ensure that the <tomcat>/conf/tomcat-users.xml file has the following defined:(where <tomcat> is the Tomcat installed directory).

[java]
&amp;lt;?xml version=’1.0′ encoding=’utf-8′?&amp;gt;
&amp;lt;tomcat-users&amp;gt;
&amp;lt;role rolename=&amp;quot;manager&amp;quot;/&amp;gt;
&amp;lt;role rolename=&amp;quot;admin&amp;quot;/&amp;gt;
&amp;lt;user username=&amp;quot;admin&amp;quot; password=&amp;quot;admin&amp;quot; roles=&amp;quot;admin,manager&amp;quot;/&amp;gt;
&amp;lt;/tomcat-users&amp;gt;
[/java]

To login into Tomcat Manager app we will use:

[java]

Username=admin
Password=admin

[/java]

 

Define Tomcat Server in Maven settings

Edit the Maven settings.xml (e.g:C:Documents and SettingsManisha.m2settings.xml), add a server myserver. Add the credentials to log into the Tomcat Manager application:

[java]
&amp;lt;settings&amp;gt;
&amp;lt;servers&amp;gt;
&amp;lt;server&amp;gt;
&amp;lt;id&amp;gt;myserver&amp;lt;/id&amp;gt;
&amp;lt;username&amp;gt;admin&amp;lt;/username&amp;gt;
&amp;lt;password&amp;gt;admin&amp;lt;/password&amp;gt;
&amp;lt;/server&amp;gt;
&amp;lt;/servers&amp;gt;
…….
…..
[/java]

Point POM to Tomcat Server

Edit section in the the pom.xml file (under the directory C:MVNProjectSampleWebapppom.xml) as follows:

[java]
&amp;lt;build&amp;gt;
&amp;lt;finalName&amp;gt;SampleWebapp&amp;lt;/finalName&amp;gt;
&amp;lt;plugins&amp;gt;
&amp;lt;plugin&amp;gt;
&amp;lt;groupId&amp;gt;org.codehaus.mojo&amp;lt;/groupId&amp;gt;
&amp;lt;artifactId&amp;gt;tomcat-maven-plugin&amp;lt;/artifactId&amp;gt;
&amp;lt;configuration&amp;gt;
&amp;lt;server&amp;gt;myserver&amp;lt;/server&amp;gt;
&amp;lt;path&amp;gt;/SampleWebapp&amp;lt;/path&amp;gt;
&amp;lt;/configuration&amp;gt;
&amp;lt;/plugin&amp;gt;
&amp;lt;/plugins&amp;gt;
&amp;lt;/build&amp;gt;
[/java]

We have added the Tomcat plugin for Maven. The <configuration> section points to the server we defined in settings.xml (‘myserver’). Through <finalName> and the <path> we define the web context we want to deploy to. We’ll be able to access our application at http://localhost:8080/SampleWebapp.

Build and Deploy the web application to Tomcat server

Open the command window console, and go to the directory where pom.xml is located (C:MVNProjectSampleWebapppom.xml). Execute the following command:
mvn tomcat:deploy
If “BUILD SUCCESS” message appears, then access the application at:
http://localhost:8080/SampleWebapp/.
If you want to deploy again, then use the following command:
mvn tomcat:redeploy

Summary

  • Apache Maven 2.0 – Maven Plugins
  • Buy: Apache Maven Implementation from flipkart.com

In this post we did learn how to create a simple webapp using the Maven archetype plugin. We checked the directory structure and the generated source code. We then did learn about how to build and deploy this simple web app in the Tomcat server using Maven command. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here.

Filed Under: Apache Maven Tagged With: Apache Maven

Creating Simple Java Project Using Apache Maven

February 20, 2013 by Manisha Patil Leave a Comment

Maven is a build and project management tool for java based application development. In previous article(“Apache Maven for Beginners“), we talked about installing and configuring maven on windows operating system. In this article, we shall see how to create a simple Maven project, check the created directories and build the project.

If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here.

  • Buy: Apache Maven Implementation from flipkart.com

Maven uses archetype plugins to create projects. To create a simple java application, we’ll use maven-archetype-quickstart plugin from command line. In the example below, We’ll create a maven based java application project in C:\MVNProject folder.

Open the command line window and type the below command, Maven creates a blank java project with all default options.

[java]
C:\MVNProject>mvn archetype:generate -DgroupId=net.javabeat -DartifactId=
SampleJavaProject -DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
[/java]

Note: If you have just installed Maven, and if its your first run, it may take a while, because Maven downloads the most recent artifacts (plugin jars and other files) into your local repository (to your .m2 directory). You may also need to execute the command a couple of times before it succeeds. This is because the remote server may time out before your downloads are complete.

Maven commands

    • mvn : is the Maven command.
    • archetype:create : is called a Maven goal, analogous to an ANT target. It describes a unit of work to be completed in a build. The purpose of this goal is to quickly create(goal) a project from an archetype(plugin)
    • -Dname=value pairs : (DgroupId, DartifactId, DarchetypeArtifactId, DinteractiveMode) These are the arguments which are passed to the goal.They take the form of -D properties, similar to the system property options which you pass to the Java Virtual Machine via the command line.

The output on executing the above command is

[java]
[INFO] Scanning for projects…
[INFO] ————————————————————————
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ————————————————————————
[INFO]
[INFO] >>> maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] — maven-archetype-plugin:2.0: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-quickstart:1.0
[INFO] —————————————————————————-
[INFO] Parameter: groupId, Value: net.javabeat
[INFO] Parameter: packageName, Value: net.javabeat
[INFO] Parameter: package, Value: net.javabeat
[INFO] Parameter: artifactId, Value: SampleJavaProject
[INFO] Parameter: basedir, Value: C:\MVNProject
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] project created from Old (1.x) Archetype in dir: C:\MVNProject\SampleJavaProject
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 13:03.812s
[INFO] Finished at: Sun Feb 17 08:37:52 IST 2013
[INFO] Final Memory: 8M/24M
[INFO] ————————————————————————
[/java]

Once the project is created, a directory structure is created as shown below. This directory structure adheres to the standard Maven directory layout.

dir_struct
The details of the basic directories is as follows:

    • SampleJavaProject: This directory contains src folder and pom.xml. Maven Archetype plugin creates this directory, value matching the artifactId SampleJavaProject
    • src/main/java: This directory contains java code files under the package structure (net/javabeat).
    • src/main/test: This directory contains test java code files under the package structure (net/javabeat).

We see that a default pom.xml has been created. POM file generated is:

[java]
<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>net.javabeat</groupId>
<artifactId>SampleJavaProject</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SampleJavaProject</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]

Maven Archetype plugin also created a sample Java Source file(C:\MVNProject\SampleJavaProject\src\main\java\net\javabeat\App.java) and Java Test file(C:\MVNProject\SampleJavaProject\src\test\java\net\javabeat\AppTest.java).

App.java, is a single 13-line Java class, with a static main function that prints a simple “Hello World!” message.

[java]
package net.javabeat;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
[/java]

AppTest.java

[java]
package net.javabeat;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}

/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}

/**
* Rigourous Test 🙂
*/
public void testApp()
{
assertTrue( true );
}
}

[/java]

Build project

Once the project is created with the Maven Archetype plugin as seen above, we can build and package the application. To do so, run mvn install from the directory that contains the pom.xml(in our case it is C:\MVNProject\SampleJavaProject):

[java]
C:\MVNProject\SampleJavaProject>mvn install
[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building SampleJavaProject 1.0-SNAPSHOT
[INFO] ————————————————————————
[INFO]
[INFO] — maven-resources-plugin:2.4.3:resources (default-resources) @ SampleJavaProject —
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVNProject\SampleJavaProject\src\main\resources
[INFO]
[INFO] — maven-compiler-plugin:2.3.2:compile (default-compile) @ SampleJavaProject —
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\MVNProject\SampleJavaProject\target\classes
[INFO]
[INFO] — maven-resources-plugin:2.4.3:testResources (default-testResources) @ SampleJavaProject —
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVNProject\SampleJavaProject\src\test\resources
[INFO]
[INFO] — maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ SampleJavaProject —
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\MVNProject\SampleJavaProject\target\test-classes
[INFO]
[INFO] — maven-surefire-plugin:2.5:test (default-test) @ SampleJavaProject —
[INFO] Surefire report directory: C:\MVNProject\SampleJavaProject\target\surefire-reports

——————————————————-
T E S T S
——————————————————-
Running net.javabeat.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.453 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] — maven-jar-plugin:2.3.1:jar (default-jar) @ SampleJavaProject —
[INFO] Building jar: C:\MVNProject\SampleJavaProject\target\SampleJavaProject-1.0-SNAPSHOT.jar
[INFO]
[INFO] — maven-install-plugin:2.3.1:install (default-install) @ SampleJavaProject —
[INFO] Installing C:\MVNProject\SampleJavaProject\target\SampleJavaProject-1.0-SNAPSHOT.jar to C:\Documents and Settings\Manisha\.m2\repository\net\javabeat\SampleJavaProject\1.0-SNAPSHOT\SampleJavaProject-1.0-SNAPSHOT.jar
[INFO] Installing C:\MVNProject\SampleJavaProject\pom.xml to C:\Documents and Settings\Manisha\.m2\repository\net\javabeat\SampleJavaProject\1.0-SNAPSHOT\SampleJavaProject-1.0-SNAPSHOT.pom
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 37.375s
[INFO] Finished at: Sun Feb 17 12:17:10 IST 2013
[INFO] Final Memory: 11M/27M
[INFO] ————————————————————————
[/java]

Executing the mvn install, we have just created, compiled, tested, packaged and installed the simple java project by Maven. We can also clean the target directories by using the clean command as mvn clean install.

Execute the program from command line as follows:

[java]
C:\MVNProject\SampleJavaProject\target\classes>java net.javabeat.App
Hello World!
[/java]

Summary

  • Buy: Apache Maven Implementation from flipkart.com

In this article we saw how to create a simple Java project using Maven archetype plugins. We checked the directory structure, the generated source code.We then did learn about how to build this simple Java project using Maven command.In the next article we shall create a web application project using Maven.

If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here.

Filed Under: Apache Maven Tagged With: Apache Maven

Apache Maven for Beginners

February 13, 2013 by Manisha Patil Leave a Comment

What is Maven?

Apache Maven is project management tool which is following the concept of a project object model (POM). Mavan 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 (by Sonatype’s Jason van Zyl). 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. It is same as Maven 2 but more stable. This article explores the very basic concepts needed for the beginners who want to learn and get started with the Maven. Before the popularity of using Maven, most of the projects used Ant Script for the projects build which is used only for the build purpose.

If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe here.

apache maven

Maven Definition

Definition of Maven from the Maven site(http://maven.apache.org/):
“Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.

Maven is an open source software engineering platform. The intent of Maven is to make intra-project development highly manageable in the hopes of providing more time for cross-project development. You may say it as sharing of project development knowledge. The core functionality of Maven is automated project building, distribution and website creation.

Maven features

  • Dependency System: Superior dependency management including automatic updating, dependency closures (also known as transitive dependencies). Maven encourages the use of a central repository of JARs and other dependencies. Maven has a mechanism which helps your project’s clients to download any required JARs for building your project from a central JAR repository.This allows reuse of JARs across projects for Maven users.This also helps in dealing with backward compatibility issues.
  • Multi-module builds: Able to easily work with multiple projects at the same time
  • Consistent project structure: Consistent structure across all projects means no ramp up time for new developers coming onto a project
  • Consistent build model: Maven is able to build any number of projects into predefined output types such as a JAR, WAR, or distribution based on metadata about the project, without the need to do any scripting in most cases.
  • Plugin oriented: The Maven functionality is implemented in terms of plugins.
  • Project generated sites: Maven generates a website or a PDF file using the same metadata as for the build process.You can include any documentation to this site and the standard report about the state of development of the project.Examples of this information can be seen at the bottom of the left-hand navigation of this site under the “Project Information” and “Project Reports” sub menus.

Comparison of Maven with Apache ANT:

Major differences between Maven and ANT are:

  1. Maven is description of a project whereas ANT is development of a build script per project.
  2. Maven follows conventions like a common project directory structure whereas ANT needs to be told about the exactly where to find the source and where to put the output.
  3. Maven has invocation of defined goals (targets) whereas in ANT script you have invocation of project specific targets.
  4. Maven has build life cycle, standard project layout where as ANT doesn’t and it has too complex scripts(You have to define goals and goal dependencies). You have to attach a sequence of tasks to each goal manually.
  5. Maven has reusable plugins, repositories whereas ANT scripts are not reusable.
  6. Maven is declarative.All you have to do is create a pom.xml file and put your source in the default directory. Maven takes care of the rest.ANT is procdeural which means you need to tell it to compile,copy and then compress.

Maven POM

POM stands for Project Object Model.It describes following data about a project:

  1. Metadata: Location of Directories, Developers/Contributors, Dependencies, Repositories
  2. Dependencies (Transitive Dependencies), Inheritance, and Aggregation
  3. Key Elements
    • Project
    • Model Version
    • Group ID
    • Packaging
    • Artifact ID
    • Version
    • Name
    • URL
    • Description
    • Plugins
    • Profiles (Alternate build configurations)

(Note:Transitive Dependencies definition- A dependency that should be included when declaring project itself is a dependency.Example: ProjectA depends on ProjectB. If ProjectC depends on ProjectA then ProjectB is automatically included. Only compile and run time scopes are transitive)

POM has four categories

  1. General project information-this includes project information like name,URL for project,sponsor organization,list of developers,license for the project.
  2. Build settings-This include customization of default Maven build behaviour.
  3. Build environment-This inlcudes profiles that can be used and activated for working in different environments(example development server,production server).
  4. POM relationships-This includes inheritance of POM settings of parent projects.

Standard Directory Layout
structure

Install Maven

  1. Download the latest Maven from http://maven.apache.org/download.cgi.
    • The installed file is:apache-maven-3.0-bin.zip
    • Extract the archive to the directory you wish to install Maven.We have extracted to the following folder:
    • C:\tools\apache-maven-3.0
  2. Test Maven
    In order to test Maven setup,you need Java installed/configured on your machine.Assuming you have JDK installed at C:\Program Files\Java\jdk1.7.0_11\bin, execute the following commands which sets your System Environment with Java and Maven paths.[java]
    set MAVEN_HOME=C:\tools\apache-maven-3.0
    set MAVEN_OPTS=-Xms256m -Xmx512m
    set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_11
    set path=%path%,%JAVA_HOME%\bin;%MAVEN_HOME%\bin
    [/java]
  3. Verify Maven installation
    Open the command prompt and execute the following command:[java]c:\> mvn –version[/java]

    This should give the current installed version of Maven.

    [java]
    Apache Maven 3.0 (r1004208; 2010-10-04 17:20:56+0530)
    Java version: 1.7.0_11
    Java home: C:\Program Files\Java\jdk1.7.0_11\jre
    Default locale: en_US, platform encoding: Cp1252
    OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows"
    [/java]

Basic User specific Maven Configuration

Now that you have installed Maven, it is a good idea to setup the .m2 directory, where Maven creates its local repository. To create .m2 directory, assuming “Manisha” is logged in user, open the command console and execute the following command, to create the .m2 directory.

[java]
mkdir C:\Documents and Settings\Manisha\.m2
[/java]

The settings.xml file(under the .m2 directory) contains user-specific configuration for authentication, repositories,and other information to customize the behavior of Maven. Sample settings file is:

[java]
<settings>
<servers>
<server>
<id>server1</id>
<username>user1</username>
<password>password1</password>
</server>
<server>
<id>server2</id>
<username>user2</username>
<password>password2</password>
</server>
<!– Server settings for repositories Ends –>
</servers>

<!– Mirror settings for repositories Starts –>
<mirrors>
<mirror>
<id>mirror1</id>
<name>Internal network access to any repository</name>
<mirrorOf>repo1</mirrorOf>
<url>https://www.javabeat.net/repo1/</url>
</mirror>
</mirrors>
<!– Mirror settings for repositories Ends –>
<!– Profiles settings for repositories Starts –>
<profiles>
<profile>
<id>profile1</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>repo1</id>
<url>https://www.javabeat.net/repo1/</url>
</repository>
<pluginRepositories>
<pluginRepository>
<id>pluginrepo1</id>
<name>Repos (public/proxied)</name>
<url>https://www.javabeat.net/pluginrepo1/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</profile>
</profiles>
<!– Profiles settings for repositories Ends –>
</settings>
[/java]

Summary

In this article we saw basic overview about Apache Maven, its installation and basic configuration.The next article would deal with creating a simple Java project using Maven. I would write the series of tutorials on Apache Maven and how to use Apache Maven in your projects. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on  Java topics, please subscribe here.

Filed Under: Apache Maven Tagged With: Apache Maven

Apache ANT Listeners and Loggers

February 4, 2013 by Manisha Patil Leave a Comment

This article explains in brief about two features of ANT which are used to monitor the build process: Listeners and Loggers. In the previous articles on ANT we saw that ANT has logging feature(logging using external log4j). If the logger is not specified then ANT uses the DefaultLogger. Along with logger, Ant also has a log message handling category known as a listener. At a low level a logger is in fact a listener with a little difference.

  • Logger has the ability to write to log output device, such as a console or a file supplied by the “-logfile” command line argument.
  • Another difference is ANT build file can have multiple listeners but only one logger.
  • The logger is something which ANT connects to the System.out and System.err streams

The article briefly explains about loggers, listeners and built-in loggers/listeners.

Books:

  • Ant: The Definitive Guide
  • Apache Maven 2 Effective Implementation

Apache-Ant-Logo-java

Ant Listeners

A build life has events, which alerts the listener.These events are:

  • Build started
  • Build finished
  • Target started
  • Target finished
  • Task started
  • Task finished
  • Message logged

As these events trigger some action in listener, they are used for various recording and maintenance operation. New listeners may be registered on the command line through the -listener argument.

Ant Loggers

A logger is built on top of a listener, extends the capabilities of listeners and logs information about the build. You use a logger whenever you run ANT, whether or not you specify one. If a logger is not specified in ANT, then you are using the DefaultLogger. Loggers have following features:

  1. Loggers receive a handle to the standard output and error print streams and hence log information to the console or to a specified file(command for specifying file -logfile).
  2. Loggers are aware of logging level (-quiet, -verbose, -debug)
  3. Loggers are aware of Emacs-mode

Built-in Listeners/Loggers

In addition to the DefaultLogger, Ant comes with following standard loggers and listeners:

  • DefaultLogger
  • NoBannerLogger
  • MailLogger
  • AnsiColorLogger
  • XmlLogger
  • Log4jListener
  • TimestampedLogger
  • BigProjectLogger
  • ProfileLogger

Here’s a brief overview of what each one does:
(Note:The source file and build file used in all the examples below shown are from previous article(Tutorial of java programming with Apache Ant) )

DefaultLogger

DefaultLogger is used implicitly by ANT unless overridden to use some other logger.Though the logging is not so impressive, but it does its job well. Use the following command-line option to override this logger:
ant -logger org.apache.tools.ant.DefaultLogger

Output

[java]
C:\>ant -logger org.apache.tools.ant.DefaultLogger
Buildfile: build.xml
clean:
[delete] Deleting directory C:\build
compile:
[mkdir] Created dir: C:\build\classes
[javac] Compiling 1 source file to C:\build\classes
jar:
[mkdir] Created dir: C:\build\jar
[jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar
run:
[java] 0 [main] INFO net.javaBeat.WelcomeToJavaBeat – Welcome To JavaBeat
main:
BUILD SUCCESSFUL
[/java]

NoBannerLogger

The NoBannerLogger is very similar to the DefaultLogger, except it omits output from targets that don’t log anything. When you run Ant, the console is printed as follows:
Each target’s name prints at the left-most column, followed by a colon, and then the name of corresponding task is printed in brackets. This occurs even if there is no useful output from any of the tasks.Here at such scenarios NoBannerLogger can be used to suppress output of empty target output.

Use the following command-line switch to use NoBannerLogger:
ant -logger org.apache.tools.ant.NoBannerLogger

Output

[java]
C:\>ant -logger org.apache.tools.ant.NoBannerLogger
Buildfile: build.xml
clean:
[delete] Deleting directory C:\build
compile:
[mkdir] Created dir: C:\build\classes
[javac] Compiling 1 source file to C:\build\classes
jar:
[mkdir] Created dir: C:\build\jar
[jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar
run:
[java] 0 [main] INFO net.javaBeat.WelcomeToJavaBeat – Welcome To JavaBeat
BUILD SUCCESSFUL
[/java]

Here you see that the logger has omitted the main target.

MailLogger

This logger extends the DefaultLogger, such that it captures all the output logged through DefaultLogger,then send a success or failure messages to unique email lists. A group of properties must be set for MailLogger to do its job. These properties can be passed into Ant from the command line using the standard Java -D syntax or statements in your init target or,by specifying a properties file.
The properties are:

  • MailLogger.mailhost-Mail server to use.Defaults to “localhost”.
  • MailLogger.port -SMTP Port for the Mail server.Defaults to “25”.
  • MailLogger.user-user name for SMTP auth.This field is required, if SMTP auth is required on your SMTP server the email message will be then sent using Mime and requires JavaMail
  • MailLogger.password-password for SMTP auth.This field is required, if SMTP auth is required on your SMTP server the email message will be then sent using Mime and requires JavaMail.
  • MailLogger.ssl-on or true if ssl is needed.This feature requires JavaMail.
  • MailLogger.from-You have to set this to a good “from” address
  • MailLogger.replyto-You have to set this to a “replyto” address(es),comma-seperated.
  • MailLogger.failure.notify-Whether to send an e-mail on build failure; defaults to true
  • MailLogger.success.notify-Whether to send an e-mail on build success; defaults to true
  • MailLogger.failure.to-A comma-separated list of e-mail addresses to send to on build failure
  • MailLogger.success.to-A comma-separated list of e-mail addresses to send to on build success
  • MailLogger.failure.subject-The subject of the e-mail on build failure; defaults to “Build Failure”
  • MailLogger.success.subject-The subject of the e-mail on build success; defaults to “Build Success”
  • MailLogger.failure.body-The fixed body of the e-mail on build failure;default is to send full log output
  • MailLogger.success.body-The fixed body of the e-mail on build success;default is to send full log output
  • MailLogger.mimeType-MIME-type of the message being sent;defaults to text/plain
  • MailLogger.charset-character set of message being sent.
  • MailLogger.starttls.enable-on or true if STARTTLS should be supported (requires JavaMail);deafults to “false”
  • MailLogger.properties.file-The name of a properties file that contains properties for the logger and which overrides other values.

Use the following command-line option to use this logger:
ant -logger org.apache.tools.ant.listener.MailLogger

AnsiColorLogger

AnsiColorLogger can produce color output(standard ANT output) by prefixing and suffixing ANSI color code escape sequences to it.It extends the DefaultLogger features.You can specify certain ANSI color sequences for different types of messages based on severity. In other words, info messages are a different color than errors. There are lots of codes that you can use to specify which colors you want. Consult the Ant documentation for the full list.

AnsiColorLogger is designed to work on terminals that support ANSI color codes. It works on XTerm, ETerm, Win9x Console (with ANSI.SYS loaded.), etc.

NOTE: It doesn’t work on WinNT and successors, even when a COMMAND.COM console loaded with ANSI.SYS is used.
The recognized keys and their default values are shown below:

[java]
AnsiColorLogger.ERROR_COLOR=2;31
AnsiColorLogger.WARNING_COLOR=2;35
AnsiColorLogger.INFO_COLOR=2;36
AnsiColorLogger.VERBOSE_COLOR=2;32
AnsiColorLogger.DEBUG_COLOR=2;34
[/java]

Each key takes as value a color combination defined as Attribute;Foreground;Background.In the above example, background value has not been used.

Command line option to use this logger:
ant -logger org.apache.tools.ant.listener.AnsiColorLogger

Log4jListener

Log4jListener passes events to Log4j for highly customizable logging. Log4j JAR need to be installed and a ‘log4j.xml’ configuration file configured for this listener to work.Each build event is passed to Log4j, using the full classname of the generator of each build event as the Log4j category:

  • build started / build finished – org.apache.tools.ant.Project
  • target started / target finished – org.apache.tools.ant.Target
  • task started / task finished – the fully qualified classname of the task
  • message logged – the classname of one of the above, so if a task logs a message, its classname is the Log4j category used, and so on.

All the start events are logged as INFO-level messages; finish events are sent as INFO if they succeed, and ERROR otherwise. Message events are logged according to their Ant logging level, mapping directly to a corresponding Log4j level.

Example:
log4j.xml file:

[java]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="fileAppender" class="org.apache.log4j.FileAppender">
<param name="Threshold" value="INFO" />
<param name="File" value="build.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%t %-5p %c{2} – %m%n"/>
</layout>
</appender>

<root>
<priority value ="debug" />
<appender-ref ref="fileAppender" />
</root>
</log4j:configuration>
[/java]

Place Log4j JAR in your Ant classpath.Set the following attributes:
set ANT_OPTS=-Dlog4j.debug -Dlog4j.configuration=file:///c:/lib/log4j.xml
To use this listener, use the command:
ant -listener org.apache.tools.ant.listener.Log4jListener

Output in build.log file:

[java]
INFO Project : Build started.
INFO Target : Target "clean" started.
INFO Delete : Deleting directory C:\build
INFO Target : Target "clean" finished.
INFO Target : Target "compile" started.
INFO Mkdir : Created dir: C:\build\classes
INFO Javac : C:\build.xml:21: warning: ‘includeantruntime’ was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
INFO Javac : Compiling 1 source file to C:\build\classes
INFO Target : Target "compile" finished.
INFO Target : Target "jar" started.
INFO Mkdir : Created dir: C:\build\jar
INFO Jar : Building jar: C:\build\jar\WelcomeToJavaBeat.jar
INFO Target : Target "jar" finished.
INFO Target : Target "run" started.
INFO Java : 0 [main] INFO net.javaBeat.WelcomeToJavaBeat – Welcome To JavaBeat
INFO Target : Target "run" finished.
INFO Target : Target "main" started.
INFO Target : Target "main" finished.
INFO Project : Build finished.
[/java]

XmlLogger

XmlLogger logs all the build information to an XML file. This logger behaves differently depending on whether it is invoked as a listener or a logger.This logger writes to XML file named log.xml, or the value of the XmlLogger.file (set in your init target, at the command line with -D, or in a properties file) property if present, when used as a listener. In logger mode, all output goes to the console or to the file specified in -logfile of command-line option.
You can set a property called ant.XmlLogger.stylesheet to point to the XSLT stylesheet. If you don’t specify a style sheet, the XML file will point to one called log.xsl by default in the current directory(ANT_HOME/etc). If you don’t want stylesheet support built into your XML file, set this property to an empty string “”.
Whether XmlLogger is used as a listener or logger, the output is generated only on build completion, as it buffers the information in order to provide timing information for task, targets, and the project.

Command lines for starting Ant with the XmlLogger in both listener and logger modes are:
ant -listener org.apache.tools.ant.XmlLogger
The output is logged in log.xml

ant -logger org.apache.tools.ant.XmlLogger -logfile output.xml
The output is logged in output.xml

TimestampedLogger
TimestampedLogger includes the build completion time at the final success/failure.It extends the fetaures of DefaultLogger.

To use this listener, use the command:
ant -logger org.apache.tools.ant.listener.TimestampedLogger
Output:

[java]
C:\>ant -logger org.apache.tools.ant.listener.TimestampedLogger
Buildfile: C:\build.xml
clean:
[delete] Deleting directory C:\build
compile:
[mkdir] Created dir: C:\build\classes
[javac] C:\build.xml:21: warning: ‘includeantruntime’ was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to C:\build\classes
jar:
[mkdir] Created dir: C:\build\jar
[jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar
run:
[java] 0 [main] INFO net.javaBeat.WelcomeToJavaBeat – Welcome To JavaBeat

main:

BUILD SUCCESSFUL – at 1/30/13 12:53 PM
[/java]

BigProjectLogger
BigProjectLogger is used in big projects which build complex systems,especialy those run with continuous integration tools and use subant.

  • When entering a child project, prints its name and directory
  • When exiting a child project, prints its name
  • Includes the name of the project when printing a target
  • Omits logging the names of all targets that have no direct task output
  • Includes the build finished timestamp of the TimeStamp logger

This is useful when using to build a large project from many smaller projects;the output shows which particular project is building.

To use this listener, use the command:
ant -logger org.apache.tools.ant.listener.BigProjectLogger
Output:

[java]
C:\>ant -logger org.apache.tools.ant.listener.BigProjectLogger
Buildfile: C:\build.xml

======================================================================
Entering project
In C:\
======================================================================

WelcomeToJavaBeat.clean:
[delete] Deleting directory C:\build

WelcomeToJavaBeat.compile:
[mkdir] Created dir: C:\build\classes
[javac] C:\build.xml:21: warning: ‘includeantruntime’ was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to C:\build\classes

WelcomeToJavaBeat.jar:
[mkdir] Created dir: C:\build\jar
[jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar

WelcomeToJavaBeat.run:
[java] 0 [main] INFO net.javaBeat.WelcomeToJavaBeat – Welcome To JavaBeat

======================================================================
Exiting project "WelcomeToJavaBeat"
======================================================================

BUILD SUCCESSFUL – at 1/30/13 12:54 PM
Total time: 2 seconds
[/java]

ProfileLogger
The ProfileLogger is a default logger which adds start time,end time and durations for each task and target.The output contains a timestamp when entering the build, target or task and a timestamp and the needed time when exiting.

To use this listener, use the command:
ant -logger org.apache.tools.ant.listener.ProfileLogger

Output

[java]
C:\>ant -logger org.apache.tools.ant.listener.ProfileLogger
Buildfile: C:\build.xml
property: started Wed Jan 30 12:55:11 IST 2013
property: finished Wed Jan 30 12:55:12 IST 2013 (360ms)
property: started Wed Jan 30 12:55:12 IST 2013
property: finished Wed Jan 30 12:55:12 IST 2013 (0ms)
property: started Wed Jan 30 12:55:12 IST 2013
property: finished Wed Jan 30 12:55:12 IST 2013 (0ms)
property: started Wed Jan 30 12:55:12 IST 2013
property: finished Wed Jan 30 12:55:12 IST 2013 (0ms)
property: started Wed Jan 30 12:55:12 IST 2013
property: finished Wed Jan 30 12:55:12 IST 2013 (0ms)
property: started Wed Jan 30 12:55:12 IST 2013
property: finished Wed Jan 30 12:55:12 IST 2013 (0ms)
path: started Wed Jan 30 12:55:12 IST 2013
path: finished Wed Jan 30 12:55:12 IST 2013 (62ms)
Target clean: started Wed Jan 30 12:55:12 IST 2013
delete: started Wed Jan 30 12:55:12 IST 2013
[delete] Deleting directory C:\build
delete: finished Wed Jan 30 12:55:12 IST 2013 (31ms)
Target clean: finished Wed Jan 30 12:55:12 IST 2013 (31ms)
Target compile: started Wed Jan 30 12:55:12 IST 2013
mkdir: started Wed Jan 30 12:55:12 IST 2013
[mkdir] Created dir: C:\build\classes
mkdir: finished Wed Jan 30 12:55:12 IST 2013 (47ms)
javac: started Wed Jan 30 12:55:12 IST 2013
[javac] C:\build.xml:21: warning: ‘includeantruntime’ was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to C:\build\classes
javac: finished Wed Jan 30 12:55:13 IST 2013 (782ms)
Target compile: finished Wed Jan 30 12:55:13 IST 2013 (829ms)
Target jar: started Wed Jan 30 12:55:13 IST 2013
mkdir: started Wed Jan 30 12:55:13 IST 2013
[mkdir] Created dir: C:\build\jar
mkdir: finished Wed Jan 30 12:55:13 IST 2013 (0ms)
jar: started Wed Jan 30 12:55:13 IST 2013
[jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar
jar: finished Wed Jan 30 12:55:13 IST 2013 (78ms)
Target jar: finished Wed Jan 30 12:55:13 IST 2013 (93ms)
Target run: started Wed Jan 30 12:55:13 IST 2013
java: started Wed Jan 30 12:55:13 IST 2013
[java] 0 [main] INFO net.javaBeat.WelcomeToJavaBeat – Welcome To JavaBeat
java: finished Wed Jan 30 12:55:14 IST 2013 (844ms)
Target run: finished Wed Jan 30 12:55:14 IST 2013 (859ms)
Target main: started Wed Jan 30 12:55:14 IST 2013
Target main: finished Wed Jan 30 12:55:14 IST 2013 (0ms)
BUILD SUCCESSFUL
[/java]

Summary

Books:

  • Ant: The Definitive Guide
  • Apache Maven 2 Effective Implementation

To summarize,we saw the difference between loggers and listerners.Each built-in logger and listerner is expalined in brief with a simple example.For any further queries please leave your comments.

Filed Under: Apache Ant

Tutorial of java programming with Apache Ant

January 28, 2013 by Manisha Patil Leave a Comment

This article guides you through java programming with Apache Ant with the steps listed as below. The following are the steps used in the articles to explain the Ant script creation. If you have any questions, please write it in the comments section. If you are interested in receiving the future articles on Java, please subscribe here.

  1. Create a simple java program(WelcomeToJavaBeat) and run it from command prompt.
  2. Build the JAR and use the JAR to run the WelcomeToJavaBeat application.
  3. Use Apache Ant to create a buildfile for WelcomeToJavaBeat application.
  4. Build WelcomeToJavaBeat application to include external library(log4j) and hence create Apache Ant buildfile for this application

We have taken some references from the Apache Ant web site for the above tasks. We created this post as there was chance for better clarification.

Task 1: Create a simple java program(WelcomeToJavaBeat) and run it from command prompt

  1. Create the following directory structure ( here [basedir] can be any directory):[basedir]\src\net\javaBeat
    [basedir]\build\classes
    [basedir]\build\jarFolder build contains all the generated files.Folder [basedir]\build\classes shall include all compiled files and [basedir]\build\jar folder shall contain the JAR-file.
  2. Create a simple java program(WelcomeToJavaBeat.java) in [basedir]\src\net\javaBeat and run it from command prompt.[java]
    package net.javaBeat;
    public class WelcomeToJavaBeat {
    public static void main(String[] args) {
    System.out.println("Welcome To JavaBeat");
    }
    }[/java]
  3. Compile and run the code as follows:
    javac -sourcepath src -d build\classes src\net\javaBeat\WelcomeToJavaBeat.java
    java -cp build\classes net.javaBeat.WelcomeToJavaBeat

    The second command runs the application by calling the class fileOutput:

    Welcome To JavaBeat

Task2: Build the JAR and use the JAR to run the WelcomeToJavaBeat application

Build a JAR file for the java application and use the JAR command to run the application

  1. Create a manifest file.
    • echo Main-Class: net.javaBeat.WelcomeToJavaBeat>myManifest:
    • Do not have blanks around the “>”sign in the echo Main-Class instruction because it would falsify it.
    • This command creates a myManifest file in the [basedir]
  2. Create the JAR. (Don’t miss the “dot” at the end of the command.)
    • jar cfm build\jar\WelcomeToJavaBeat.jar myManifest -C build\classes .
  3. Run the application.
    • java -jar build\jar\WelcomeToJavaBeat.jar

Task3: Use Apache Ant to create a buildfile for WelcomeToJavaBeat application

Ant uses build.xml as the name for a build file by default, so our [basedir]\build.xml would be as follows. It’s a good practice to have a “clean” target, which deletes all the existing stuff from the directories. The clean target must be the first task to be running after starting the Ant script.

[java]
<project>

<target name="clean">
<delete dir="build"/>
</target>

<target name="compile">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>
</target>

<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/WelcomeToJavaBeat.jar" basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="net.javaBeat.WelcomeToJavaBeat"/>
</manifest>
</jar>
</target>

<target name="run">
<java jar="build/jar/WelcomeToJavaBeat.jar" fork="true"/>
</target>

</project>[/java]

Use the following command to compile,package and run the application:
ant compile jar run

The above build file can be enhanced as follows:

  • Many a times we reference the same directories and main-class.We can address this problem using properties.
  • jar-name are hard coded,which can be taken care of by using a special property – an attribute of the <project>-tag
  • While invocation we need to remember right order of build steps.This can be dealt with by using dependencies.

[java]
<project name="WelcomeToJavaBeat" basedir="." default="main">

<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}/jar"/>
<property name="main-class" value="net.javaBeat.WelcomeToJavaBeat"/>

<target name="clean">
<delete dir="${build.dir}"/>
</target>

<target name="compile">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}"/>
</target>

<target name="jar" depends="compile">
<mkdir dir="${jar.dir}"/>
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
<manifest>
<attribute name="Main-Class" value="${main-class}"/>
</manifest>
</jar>
</target>

<target name="run" depends="jar">
<java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
</target>

<target name="clean-build" depends="clean,jar"/>

<target name="main" depends="clean,run"/>

</project>
[/java]

To invoke the buildfile, type ant at the command line. This runs the main target in the buildfile.Note that the project tag defines the default task as main.

Output:

[java]C:\>ant
Buildfile: build.xml

clean:

compile:
[mkdir] Created dir: C:\build\classes
[javac] Compiling 1 source file to C:\build\classes

jar:
[mkdir] Created dir: C:\build\jar
[jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar

run:</pre>
<code>Welcome To JavaBeat</code>

<code>main:</code>

<code>BUILD SUCCESSFUL</code>

[/java]

Task4: Build WelcomeToJavaBeat application to include external library(log4j) and hence create Apache Ant buildfile for this application</b></h3>Store external libraries in a new directory lib. Log4J can be downloaded from the Apache site. Create the lib directory and extract the log4j-1.2.17.jar into that lib-directory. Modify java source to use this library and also modify the buildfile so that this library could be accessed during compilation and run.evised Java Source:

[java]
package net.javaBeat;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class WelcomeToJavaBeat {

static Logger logger = Logger.getLogger(WelcomeToJavaBeat.class);
public static void main(String[] args) {
BasicConfigurator.configure();
logger.info("Welcome To JavaBeat");// the old System Out-statement
}
}

[/java]

Revised buildfile:

[java]
<project name="WelcomeToJavaBeat" basedir="." default="main">

<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}/jar"/>
<property name="lib.dir" value="lib"/>
<property name="main-class" value="net.javaBeat.WelcomeToJavaBeat"/>

<path id="classpath">
<fileset dir="${lib.dir}" includes="**/*.jar"/>
</path>

<target name="clean">
<delete dir="${build.dir}"/>
</target>

<target name="compile">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
</target>

<target name="jar" depends="compile">
<mkdir dir="${jar.dir}"/>
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
<manifest>
<attribute name="Main-Class" value="${main-class}"/>
</manifest>
</jar>
</target>

<target name="run" depends="jar">
<java fork="true" classname="${main-class}">
<classpath>
<path refid="classpath"/>
<path location="${jar.dir}/${ant.project.name}.jar"/>
</classpath>
</java>

</target>
<target name="clean-build" depends="clean,jar"/>
<target name="main" depends="clean,run"/>
</project>
[/java]

Following are the steps to modify the buildfile:

  • add property name lib.dir
  • add path element for classpath to include JARs in lib.dir
  • in the compile target, add classpathref to use the classpath which points to the external library JAR.
  • modify run task, such that it refers to the main-class,finds the project JAR and uses the classpath with the JARs in the library.
Run ant and the following output would be displayed:
C:\>ant
Buildfile: build.xml

clean:
   [delete] Deleting directory C:\build

compile:
    [mkdir] Created dir: C:\build\classes
[javac] Compiling 1 source file to C:\build\classes

jar:
    [mkdir] Created dir: C:\build\jar
      [jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar

run:
     [java][/java]




[main] INFO net.javaBeat.WelcomeToJavaBeat - Welcome To JavaBeat main: BUILD SUCCESSFUL

Summary

We saw stepwise to build a simple java application through command prompt.Then created buildfile to run this simple java application.Further we enhanced the application to include logging using external jar(log4j).We also modified the buildfile to include the external jars.On similar lines we can enhance this appliction to include Junit(testing tool).

If you have any questions, please write it in the comments section. If you are interested in receiving the future articles on Java, please subscribe here.

Filed Under: Apache Ant Tagged With: ANT

Execute batch file or shell script using Ant

January 25, 2013 by Manisha Patil Leave a Comment

This article discusses on how to execute a batch file or shell script using Ant.The article details about using exec command with an example code.We will write an Ant build script, which identifies the current operating system(OS) and based on the OS detected either a batch file or a shell script is executed.We assume that the reader of this article has basic knowledge about Apache Ant tool.

Example Code

Let’s assume we have two scripts, one (.bat file) which executes on windows operating system family, and other (.sh) that runs on all non-windows platforms like UNIX, Linux, etc. Now we need an ant task in build file, to call the appropriate scripts depending on the operating system.

Let’s write a target with named checkOS. This target depends on targets ifOSWindows and ifOSNotWindows.

[java]
<target name="checkOS" depends="ifOSWindows, ifOSNotWindows"/>
[/java]

We then define these targets as:

[java]
<target name="ifOSWindows" if="isOSWindows">
<antcall target="runscript.windows"/>
</target>

<target name="ifOSNotWindows" if="isOSUnix">
<antcall target="runscript.unix"/>
</target>
[/java]

We can see that, ifOSWindows and ifOSNotWindows are based on a condition, which if true calls the specific target.

If isOSWindows property,defined as –

[java]
<condition property="isOSWindows">
<os family="windows"/>
</condition>
[/java]

returns true, then ant target runscript.windows is executed.

Else, ifOSNotWindows is tested using isOSUnix property:

[java]
<condition property="isOSUnix">
<os family="unix" />
</condition>
[/java]

If this condition returns true, then runscript.unix will be called.

Following is how you can define an ant task to execute a batch script on windows:
To execute a script , exec command is used wrapped inside your target definition. <exec> executes a system command. When the os attribute is specified, then the command is only executed when Apache Ant is run on one of the specified operating systems :

[java]
<target name="runscript.windows">
<echo>This is a Windows machine.</echo>
<exec dir="." executable="cmd" >
<arg line="/c test.bat ‘m4 foo.m4 > foo’"/>
</exec>
</target>
[/java]

Following is to run a shell script on UNIX using Ant task:

[java]
<target name="runscript.unix">
<echo>This is an Unix machine.</echo>
<exec dir="." executable="/bin/sh">
<arg path="-c test.bat ‘m4 foo.m4 > foo’"/>
</exec>
</target>
[/java]

To try out this,

  1. Copy the build.xml and test.bat (attached below), to your C: directory.Now open the command prompt,cursor pointing to C:\>
  2. Execute the ant command and the output should be:

[java]
C:\>ant
Buildfile: build.xml

ifOSWindows:
[echo] is windows……..

runscript.windows:
[echo] This is a Windows machine.
[exec] **************************************
[exec] Hello world!…Printed from batch file. "m4 foo.m4 > foo"
[exec] **************************************

ifOSNotWindows:

checkOS:

BUILD SUCCESSFUL
Total time: 0 seconds
[/java]

build.xml

[java]
<?xml version="1.0"?>
<project name="checkOperatingSystem" default="checkOS">

<!–checking if for windows and non windows OS–>
<target depends="ifOSWindows, ifOSNotWindows" name="checkOS"/>

<condition property="isOSUnix">
<os family="unix" />
</condition>

<condition property="isOSWindows">
<os family="windows" />
</condition>

<!– if the OS is windows call the target run.script.windows –>
<target name="ifOSWindows" if="isOSWindows">
<echo>is windows……..</echo>
<antcall target="runscript.windows"/>
</target>

<!– if the OS is not windows call the target run.script.unix–>
<target name="ifOSNotWindows" if="isOSUnix">
<echo>is unix……..</echo>
<antcall target="runscript.unix"/>
</target>

<target name="runscript.windows">
<echo>This is a Windows machine.</echo>
<exec dir="." executable="cmd" >
<arg line="/c /test.bat ‘m4 foo.m4 > foo’"/>
</exec>

</target>

<target name="runscript.unix">
<echo>This is an Unix machine.</echo>
<exec dir="." executable="/bin/sh">
<arg line="-c /test.bat ‘m4 foo.m4 > foo’"/>
</exec>
</target>
</project>
[/java]

test.bat

[java]
@echo **************************************
@echo Hello world!…Printed from batch file. %1%
@echo **************************************
[/java]

To summarize,on native UNIX systems, you should be able to run shell scripts directly. On systems running a Unix-type shell (for example, Cygwin on Windows) execute the (command) shell

  1. sh for shell scripts. Pass the shell script (plus any arguments to the script) as a single command, using -c switch.
  2. cmd for batch files. Pass the batch files (plus any arguments to the script) as a single command, using /c switch.

Filed Under: Apache Ant Tagged With: ANT

  • « Previous Page
  • 1
  • …
  • 5
  • 6
  • 7

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