Tuesday, January 20, 2015

Ivy HelloWorld example


What is Ivy?

Ivy is additional set of Ant task created by Apache. It's packaged as JAR file and needs to be put in $ANT_HOME/lib, just like other third-party tasks. (To create your own task, you need to create a Java class that extends org.apache.tools.ant.Task)

Ivy contains a set of tasks (resolve, cachepath, retrieve, install, publish) which works like Apache Maven phases. For example, the resolve task downloads all dependencies from Maven's public repository and stores them in ivy cache (~/.ivy2/cache directory).

Why Ivy?

One of the reasons is you are familiar with Ant and you don't want to spend more time to learn Maven.




HelloWorld Example


We are going to show how to use Ivy to compile Java HelloWorld program.

1. Downloading Ivy
Suppose you already installed Ant and then you can download Ivy from http://ant.apache.org/ivy/download.cgi

2. Installing Ivy
cp apache-ivy-2.2.0/ivy-2.2.0.jar $ANT_HOME/lib
3. Creating HelloWorld.java

Suppose we are currently in $WORKSPACE directory then create the file in the directory $WORKSPACE/src/com/vathanakmao/ivytest/ as following:
package com.vathanakmao.ivytest;

import org.apache.commons.lang.StringUtils;

public class HelloWorld {

         public static void main(String[] args) {

                 String string = StringUtils.upperCase("Hello World!");

                 System.out.println(string);

         }

}

4. Creating build.xml file
<project name="test ivy" default="resolve"
                          xmlns:ivy="antlib:org.apache.ivy.ant">

        <target name="resolve" description="resolve dependencies with ivy">
                <ivy:resolve />
                <ivy:cachepath pathid="default.classpath"/>
        </target>

        <target name="compile" depends="resolve" description="Compile">
                <mkdir dir="build/classes" />
                <javac srcdir="src" destdir="build/classes">
                        <classpath refid="default.classpath" />
                </javac>
        </target>
</project>
The resolve task () will fetch the artifacts from Maven's public repository http://repo1.maven.org/maven2 and put them in cache (~/.ivy2/cache).

The cachepath task () creates an Ant path with the given ID default.classpath, pointing to ivy cache directory consisting of the resolved artifacts. Then, the javac task will look for the artifacts in the cache because we declare it as the classpath with refid.

5. Creating ivy.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<ivy-module version="2.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">

    <info organisation="com/vathanakmao/ivytest" module="helloworld" status="integration"></info>

    <dependencies>
         <dependency org="commons-lang" name="commons-lang" rev="2.6" />
    </dependencies>
</ivy-module>

6. Compiling
ant compile



No comments:

Post a Comment