Using Kapatcha Library as a Google Captcha on Jsp Form Validation.

kapatcha

Have you seen the picture above? Yes, the picture is an image contains codes. Maybe we’ve ever seen this picture when we register an account to google, yahoo, or maybe we want to submit a comment to someones blog, or etc. This image is used as a validation techniques on a form on a web application. This validation techniques is used by a web application developer to protect their web application against spams attack.

Nowadays, this protection way become a trend on a web application development. It’s called as a Google Captcha. Practically, the code that appears on the image have to be inputed by the user onto a text box on a form, so the user can access the next page. If user did not input the correct code, so the user will be asked again to input the code with different image.

Now we will try to implement this techniques on our try-it-out today. For this try-it-out, we will only make a simple form validation, where user will be asked to write a code that appears on a image onto a text box and then user will click the submit button to go to the next page. And in this next page we will add syntax to check whether the code that given in previous page is correct or not.

We will use a library on this try-it-out, this library called kapatcha, you can download it here. After finish downloading this library, don’t forget to put this library on WEB-INF/lib folder on your web application later. The work flow of this library is very simple. Actually the image that inserted on a form is made by this kapatcha library, so we don’t have to create images containing codes manually, we can say this process as on the fly image creation.

The images that will be created automatically by this kapatcha library, is made by a servlet that exist in this kapatcha library, the servlet name is KaptchaServlet, located on package com.google.code.kaptcha.servlet. This KaptchaServlet will automatically create an image with jpg extention every time when this servlet is called. That’s mean we have to declare this servlet on deployment-descriptor file. And then on our form, we just called this image using html tag img. Please take a look on this codes below:

<body>
<form name="kapatcha_form" action="validate_kaptcha.jsp" method="post">
Enter code shown on the picture <br>
<img src="kapatcha.jpg" width="200" id="kaptchaImage" onclick="document.location.reload()"/>
<br>
<small>if you cannot see the image, just click the image to reload the image</small>
<br>
<input type="text" name="kaptcha"><br>
<input type="submit" value="Submit">
</form>
</body>

On this code above, we can see that image tag (img) containing an image ‘kapatcha.jpg’, which actually this image is not exist on our web application, but this image will be created automatically by KapacthaServlet at the time this kapatcha.jpg called by the form, and then how to call this KapatchaServlet? Let’s take a look the codes that filled up a tomcat deployment-descriptor file or web.xml below:

<servlet>
<servlet-name>kapatcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>kapatcha</servlet-name>
<url-pattern>/kapatcha.jpg</url-pattern>
</servlet-mapping>

on the codes above we can see that this KaptchaServlet mapped to an url, which this url is kapatcha.jpg, that’s mean when this kapatcha.jpg called by the form, then this KaptchaServlet will create an image and directly allocated as kapatcha.jpg, so our form will be inserted by an image that created by this KaptchaServlet calling. Our form will look like this:

googlecaptchaform

In the image tag which exist on our html form, we also saw a function of a java-script, this function is inserted as onclick=”document.location.reload();”, this function is need to reload the form when user cannot see the code that appear on image, when this image clicked, the form will reload and the KaptchaServlet will create another image, so the user might be able to read the code in this new image created by the servlet.

Now, let’s discuss how to handle the validation of the code, the validation will be handle by the next page which is validate_kaptcha.jsp that we declared on our html form above. So let’s take a look out of this below codes :

<%@ page import="com.google.code.kaptcha.Constants" %>
<%
    String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
    String kaptchaReceived = request.getParameter("kaptcha");
    String textResult = "";

    if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
        textResult = "You're entered invalid code";
    } else
        textResult = "Congratulation you're entered correct code";

%>
<html>
<head>
    <title>Validate Kapatcha</title>
</head>
<body>
<%=textResult%>
</body>
</html>

On this validate_kapatche.jsp file above, we can see there’s two string, both have initialized related with this captcha validation. The first string is kaptchaExpected, this string is catching a session that have been made by this KaptchaServlet when the captha image created, and the 2nd string is kaptchaReceieved which it’s value filled by the taking parameter value of the previous form.

Don’t forget we also inserted statement to import Constants class on the first line of the codes above. And then on the next statement, we can see a check process, this check process is very simple, the codes is only comparing the both string whether they are equals or not, and then filled the textResult string with the appropriate information, and we later use this textResult string as our web page body display string.

I think this Google Captcha implementation on our try-it-out is very simple and very easy to understand, so I hope on the next development you can use it to your own web application.

 

I Hope this will helpful

Menteng, December 22th 2008


josescalia

 

Advertisements

Making HTTP POST Client Application using Java

What is on our mind when we see this title?. On Internet technology, we found often an interaction between user and a website. One of this interaction such as when user asked to input data on a website for some matters. When that’s happen, we can understand on that web application there’s some data inputed on a website actually.

On web programming we knew few methods on posting process, the first is post methods. Post methods is a data post mechanism, that in it’s process the post parameters explicitly cannot be seen on browsers address bar, while get methods is a posting data mechanism that the posting parameters explicitly seen on browsers address bar.

Now we will try to make a java console application, which this application have an ability to post to an URL within HTTP POST method. For this project we will need a server element. This element is used to catch the post action that we will do using this project application. We will make this server element using PHP script, so the element is more simple and easier to make. Let’s take a look out this PHP script below, this script is made in order to catch all the thrown data post.

 <?php
//define all param
$name = $_POST["name"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$address = $_POST["address"];

//print our all posted param
echo "Name : ".$name."<br>";
echo "Phone : ".$phone."<br>";
echo "Email : ".$email."<br>";
echo "Address : ".$address."<br>";

//other method to go to next process goes here...!!!

?>

That script is very simple, first, declare all parameters that thrown to this file, and then print out all those passed parameters. If you wants any other process after catch all parameters process such as save data process to a database, please do so, the important things is 5 lines of the beginning of the script still exist. On that above script, we use $_POST to catch all passed parameters, because out later application will be using HTTP POST method, if we use HTTP GET method, so the we cannot use this lines we have to use $_GET to catch all the passed parameters.

We named this PHP script as test.php, and then we have to put this file on our apache htdocs folder, let’s put this file on <apache_folder>/htdocs/server_hit/ where apache_folder is your apache-php installation directory. Then we run down our apache server and test this file by opening a browser and type http://localhost/server_hit/test.php on a it’s address bar. If we see the browser just like this below image, so our server element for this project is done.

php_post

And now we will make a java console application, that this application will shoot that URL. Our application will include libraries from the apache.common.project collection which is common-httpclient library, please download this library here. This common-httpclient library had a dependency of other apache.common.project which is common-logging library, so please download this common-logging library here.

If we have provided all the libraries, let’s code. This link is a complete source file of this application. We will discuss this code. On the source file we could see there’s 3 methods which is:

  1. public static Hashtable defineParamToPost.

  2. public static sendUrlPost.

  3. public static void main.

Those three methods is a static methods, which the 3rd method is a main method of our application, while others methods in this application can be called directly on a main method without declaring our application as a new object, because those both methods is also static.

Now let’s discuss each method, take a look to first method as shown below:

....
....
public static Hashtable defineParamToPost(String sParamName,
                              String sParamPhone,
                              String sParamEmail,
                              String sParamAddress) {
       Hashtable hash = new Hashtable();
       hash.put("name", sParamName);
       hash.put("phone", sParamPhone);
       hash.put("email", sParamEmail);
       hash.put("address", sParamAddress);
   return hash;

}

.....
.....

This method have a return value as Hashtable object and this method have 4 string type parameters. This method is processing a conversion of 4 string type parameters into a hashtable object and then return the process as a hashtable obejct.

Now let’s discuss 2nd method, sendUrlPost method. Let’s take a look on a few beginning lines of this method below:

......
......
......
public static String sendUrlPost(String Url, Hashtable hash,
                          int connectionTimeout, int readTimeout) {

System.out.println("Url To Post: " + Url);
System.out.println("Timeout limit for Connection :" + connectionTimeout + " milisecond");
System.out.println("Timeout limit for Read Response :" + readTimeout + " milisecond ");
System.out.println("Params to be posted on Hashtable Object : " + hash);

String sResponse = "";

Enumeration paramList = hash.keys();
Vector requestParamKey = new Vector(1, 1);
Vector requestParamValue = new Vector(1, 1);

System.out.println("Converting Hashtable to Vector....");

while (paramList.hasMoreElements()) {
 String name = (String) paramList.nextElement();
 String value = (String) hash.get(name);
 requestParamKey.addElement(name);
 requestParamValue.addElement(value);
 if (!paramList.hasMoreElements()) {
     break;
 }
}
System.out.println("Convert Hashtable to Vector done...");
......
......
......
}

On those code above, we can see we print out all the passed parameters to this method, and then after we declare String sResponse, we initialized a few objects which is Enumeration object and Vector object. And then we do loop to map the hashtable onto each Vector object that we have initialized before which is requestParamKey and requestParamValue. And then for the next process let’s take a look on the below code:

public static String sendUrlPost(String Url, Hashtable hash,
                           int connectionTimeout, int readTimeout) {
......
......
......

//create new HttpClient Object
HttpClient client = new HttpClient();

//Set Timeout till connection established
client.setConnectionTimeout(connectionTimeout);

// Set Timeout waiting for data
client.setTimeout(readTimeout);

int responseCode = -1;

// Create a method instance.
PostMethod method = new PostMethod(Url);
method.setHttp11(false);

String req_name = null;
String req_value = null;
......
......
}

On the next lines we could see, few methods of this common-httpclient library is used here. First step we could see there’s a making proces of HttpClient object, and then some property if this object is set. Those properties are Connection Time Out and Timeout, that the timeout property is a maximal time needed to read the result of the connection.

And then new object was made here above is PostMethod object, for this object the property http11 is set to false, because we don’t use it to create http connection. And then there’s a declaration of two string, both string has a null given value as an initialization. And now let’s take a look of others next code:

public static String sendUrlPost(String Url, Hashtable hash,
                            int connectionTimeout, int readTimeout) {
......
......
......

try {
   //iterate Vector contains http_post params
   System.out.println("Iterating Vector to map to post params...");
   for (int i = 0; i < requestParamKey.size(); i++) {
       req_name = (String) requestParamKey.elementAt(i);
       req_value = (String) requestParamValue.elementAt(i);
       method.addParameter(req_name, req_value);
   }

   System.out.println("Iterating Vector Done...");

   //execute Post Method
   System.out.println("Executing Http Method...");
   responseCode = client.executeMethod(method);
} catch (MalformedURLException mue) {
   mue.printStackTrace();
} catch (IOException ioe) {
   ioe.printStackTrace();
} catch (Exception runex) {
   runex.printStackTrace();
}

//printout Server Status
System.out.println("HttpResponseCode : " + responseCode);

......
......
}

On those lines we could see the post method execution is invoke here, after we iterate Vector object and then put each element and it’s value onto HTTP POST method parameters. Those task should be proces on try-catch block to avoid unexpected error such as Malformed URL, or any other catch. When this method was executed, server will return the HTTP STATUS, we can catch this status and then print it out onto a console.

Now, let’s take a look the last lines of this methods:

public static String sendUrlPost(String Url, Hashtable hash,
                             int connectionTimeout, int readTimeout) {
......
......
......

if (responseCode != 200) {
    // Release the connection.
    method.releaseConnection();
    System.out.println("Invalid HttpResponse: " + responseCode);
    return sResponse;
}

// Read the response body.
System.out.println("Reading the Response Body...!!!");
byte[] responseBody = method.getResponseBody();

if (responseBody != null) {
    System.out.println("Converting Response Body from byte array to String...");
    sResponse = new String(responseBody);
    if (sResponse != null) {
        sResponse = sResponse.trim();
    }
}

// Release the connection.
System.out.println("Releasing Connection...");
method.releaseConnection();

return sResponse;
}

On these last lines of this method, we see that if there’s not HTTP response return as 200, that’s mean our posting process will not be successful, because on HTTP response code, a successful connection to a server will be marked by HTTP status code 200. And then next line on this method is statement to read the resonse body of the server. Response body is view of a web page when we request the page on a web site.

The reading of this response body that exist on this method is read process of bytes that appear from the web page. On this method, this bytes was hold on an array of byte variable. And then the next process are converting this array of byte into a string variable, this string is needed to give return value of this method. The last process of this method is releasing the http connection.

That’s it, the discussion of both essential methods on this source file, while the main method, I think it’s easier to understand, because the main method is only processing the calls of these both essential method.

If we have done for this project, now we can test this application, i’ve tested on my side using IntelliJidea and the screen shot is below, and it’s running well, how bout you…?

runninghttppostclient

For the next future development, we can use this application consept to create an application that suitable for posting data into a server. This application might be a scheduled post that might be need to run periodically. It can be used too post the data that might be taken from a database, so the post will loop as much as the row on the database. Rather then we do posting manually it will waste a time, we can use this application consept and impelement anything that might be suitable for our needs.

 

I hope this usefull.

Menteng, January 15th 2008

 

josescalia

 

Making XML Writer Application with Java Console

XML or eXtensible MarkUp Language basically is a mark up language that was created by the World Wide Web Consortium (W3C) to overcome HTML (Hyper Text Markup Language). With XML we can make the customizable tags. Practically, nowadays XML is used to any purpose on the computer data technology. The XML is used from the data changing format on a web service to using an xml as data format to store a data like database.
We are not going to discuss the detail of about history XML, the used of XML, how is the future about XML it self. Obviously, now we already knew how important the XML existence on the computer data technology. And it feels good, if we also could implement this XML existence as a special things in our knowledge. To find out more about XML and it’s behavior on the computer data technology, you can find out your own reference freely.
Now, we will try to make a Java console application that have an ability to write a data on a XML format. For this purpose we will try to map a list onto a XML format. Let’s take a look an example list below:
list
If the list above mapped to a XML format, maybe it will looks like below:

<BOOK_CATALOG>
<LIST>
   <CODE>D0001</CODE>
   <TITLE>Mastering Java</TITLE>
   <WRITER>Ian Klause</WRITER>
   <PUBLISHER>Ian Klause</PUBLISHER>
   <YEAR>Ian Klause</YEAR>
</LIST>
<LIST>
   <CODE>D0002</CODE>
   <TITLE>Mastering Tomcat</TITLE>
   <WRITER>Ian McFarland</WRITER>
   <PUBLISHER>Ian McFarland</PUBLISHER>
   <YEAR>Ian McFarland</YEAR>
</LIST>
<LIST>
   <CODE>D0003</CODE>
   <TITLE>Java GUI and Implementation</TITLE>
   <WRITER>Patrick Boyze</WRITER>
   <PUBLISHER>Patrick Boyze</PUBLISHER>
   <YEAR>Patrick Boyze</YEAR>
</LIST>
<LIST>
   <CODE>D0004</CODE>
   <TITLE>Analyse Jboss Flow</TITLE>
   <WRITER>Adelaine Gim</WRITER>
   <PUBLISHER>Adelaine Gim</PUBLISHER>
   <YEAR>Adelaine Gim</YEAR>
</LIST>
</BOOK_CATALOG>

Now we will make a Java console application to handle the making of the list onto a XML data format just like above.

Ok, let’s make this application, first we create am object which it’s properties are headers of the list, let’s make a Java standard object or POJO (Plain Old Java Object) with getter, setter, constructor, and toString method, the codes of this class object is here.

Hmmm, it’s very simple the object class that we already created, even for the constructor we make all this object properties become parameters of the constructor. And then on the last lines there’s a toString methods that will usable to print out all the value of those object properties.

And then let’s make a small class that we will use to serialize XML Document onto a String Buffer, this String Buffer we can use it to print out to a console. Let’s name this class as DomSerializer, this link provides the codes of this class.

Actually the main function of this DomSerializer class is the lines that exist on serializeNode methods, this method reads all the node of the XML document, and then the result will we put on a String Buffer. And then also on this class there’s a method called serialize, this method will called serializedNode method which return a string. You can explore each methods that exist on this class.

And the next step, we will create an application, which this application will have the scenario below:

1. Put on all the data into an array of object.

2. Create an object of a XML document.

3. Convert the XML Document that we have created onto a string using DomSerializer class.

 

To map the list onto an array of object, let’s take a look of this below codes:

 

public class XMLApplication {
.........
.........
public static void main(String[] args) {
  BookCatalog[] catalog = new BookCatalog[4];
  //entrying the data
  catalog[0] = new BookCatalog("D0001", "Mastering Java", "Ian Klause", "Wrox.com", Double.parseDouble("2005"));
  catalog[1] = new BookCatalog("D0002", "Mastering Tomcat", "Ian McFarland", "Wrox.com", Double.parseDouble("2002"));
  catalog[2] = new BookCatalog("D0003", "Java GUI and Implementation", "Patrick Boyze", "Andalusia.com", Double.parseDouble("2001"));
  catalog[3] = new BookCatalog("D0004", "Analyse Jboss Flow", "Adelaine Gim", "Tarkuti.com", Double.parseDouble("2003"));
 ..........
 ........
 .......
}
......

On those lines we can see that first we have created a new array of object with the index of the array is 4, just like the much of the data on the list. And then for each index we fill the value of the object using the object constructor of the BookCatalog that we’ve already created before.

The next step we will make 3 methods on this application, those methods are :

1. getDocumentBuilder, this is the method which have used a DocumentBuilderFactory class that exist on javax.xml.parsers packages. And then this method will return a Document Builder object that we can use to create a XML document on the others method. Let’s take a look of below codes:

public class XMLApplication {
 .........
 .........
 .........
private DocumentBuilder getDocumentBuilder() {
   DocumentBuilderFactory dbf=null;
   DocumentBuilder db=null;
   if ((db == null) || (dbf == null)) {
       // Step 1: create a DocumentBuilderFactory and configure it
       dbf = DocumentBuilderFactory.newInstance();
       // Optional: set various configuration options
       dbf.setValidating(false);
       // Step 2: create a DocumentBuilder that satisfies the constraints
       // specified by the DocumentBuilderFactory
       try {
           db = dbf.newDocumentBuilder();
       }
       catch (ParserConfigurationException pce) {
           System.err.println(pce);
       }
   }
   return db;
}
.........
.........
.........
}

as we can see on those lines, first in this method DocumentBuilderFactory class called and initialized with null value, and then on the if block, DocumentBuilderFactory class created and it’s configured, and then on the try catch block, DocumentBuilder object created and this object will be returned.

2. createXMLTemp, this method have a return value is XML Document, and with it’s parameter which is BookCatalog as an array of objeck. Here’s the codes of this methods:

public class XMLApplication {
  .........
  .........
  .........
private Document createXMLTemp(BookCatalog[] catalog) {
    Document doc = getDocumentBuilder().newDocument();
    Element top = doc.createElement("BOOK_CATALOG");
    doc.appendChild(top);
    Element root = doc.getDocumentElement();
    Element list = null;

    for (int i = 0; i < catalog.length; i++) {
        list = doc.createElement("LIST");

        Element elCode = doc.createElement("CODE");
        Text txtElCode = doc.createTextNode(catalog[i].getBookCode());
        elCode.appendChild(txtElCode);
        list.appendChild(elCode);

        Element elTitle = doc.createElement("TITLE");
        Text txtElTitle = doc.createTextNode(catalog[i].getBookTitle());
        elTitle.appendChild(txtElTitle);
        list.appendChild(elTitle);

        Element elWriter = doc.createElement("WRITER");
        Text txtElWriter = doc.createTextNode(catalog[i].getBookWriter());
        elWriter.appendChild(txtElWriter);
        list.appendChild(elWriter);

        Element elPublisher = doc.createElement("PUBLISHER");
        Text txtElPublisher = doc.createTextNode(catalog[i].getBookWriter());
        elPublisher.appendChild(txtElPublisher);
        list.appendChild(elPublisher);

        Element elYear = doc.createElement("YEAR");
        Text txtElYear = doc.createTextNode(catalog[i].getBookWriter());
        elYear.appendChild(txtElYear);
        list.appendChild(elYear);
        root.appendChild(list);
    }

    return doc;
}

.........

we could see on those lines, the getDocumentBuilder method called to create a new XML document object, and then an element added on the object, this element is the top element of the object and has been named as top, and then there’s a loop do, this loop will rotate the process as much as the BookCatalog object index length, which used as a parameter of this method, on this loop there’s an adding process of few element refers to a header of the list wich is CODE, TITLE, WRITER, PUBLISHER dan YEAR

3. serializeDOM, this is the 3rd method that we’ve made, this method is usable to convert XML document onto a string that we will print out this string into a console. Here’s the codes of our last method.

public class XMLApplication {
   .........
   .........
   .........
 private String serializeDOM(Document doc) throws IOException {
     DomSerializer serializer = new DomSerializer();
     return serializer.serialize(doc);
 }

.........
.........
.........
}

After we finished creating those methods, now let’s continue to the next scenarios that we have arranged, which is Create an object of a XML document and Convert the XML Document that we have created onto a string using DomSerializer class. Please take a look on below codes to finish up the both scenarios:

public class XMLApplication {
    .........
    .........
 public static void main(String[] args) {
     ............
     ............
     XMLApplication app = new XMLApplication();

      //create document Object
      Document doc = app.createXMLTemp(catalog);
      //Serialize document to String
      String output = "";
      try {
          output = app.serializeDOM(doc);
      } catch (IOException e) {
          e.printStackTrace();
      }
      System.out.print(output);
    ......
    ......
    ......
}
 ......
 ......
 ......
}

That is the last two scenarios that we directly implement on above codes, which on the codes we can see that we create an object of document here, and then we convert the document into a string, and the finally we print out the string result onto a console. Okay, this is the link which provides the source of this application file, this file has been optimized in order to make it good on the view and perhaps it’s easy to understand, (Main Application Source Code Link).

That’s it, our experiments this time, this XML Writer Application that we can use to print out a list onto XML format view on the console. Practically, I use this methods to create a servlet that will produce a XML data format. I have used it in a web application, that this web application is responsible for a web service that my company had. The list of data taken from a database and then the XML format view will be handled by a servlet and the servlet will be requested through http port.

Indeed, it’s my plan to write this XML Writer application that print out into a console, because I think if we discuss it on web application environment and the database included, this article will be so big and it’s hard to understand, because there will be some layers included, such as DAO layer, presentation layer, etc. While those layers have a focus that split between this XML Writer application and those layers it’s self.

Please explore this application to be a wider scale of usage more than we have created above. I hope this article can be a reference for this blog reader generally and especially my self, on how to write XML document format and it’s implementation using Java programming language..

 

I hope this will helpful.

Menteng, 9 December 2009

 

josescalia.

Ant – Java Development Automation

In java programming, we knew ANT(Another Neat Tool). Ant is a tool in java programming where compile, deploy, and packaging matter, become automatic. Ant known as an “easy-to-use XML based syntax”. Just like Java, Ant also can run in cross platform. In Ant we also familiar with a file called build.xml. This file is central file of all automate process of a Java Development.

Practically, ant used by java developer as a tool to compile, package, and deploy after the source code have been made. To use ant you can download it here.

This time we will discuss about using ant as a tool to automate process java development after source code have been made. Let’s see a simple example of a build.xml file that ant can executing.

<project name="Blog" default="compile" >
  <target name="prepare">
    <mkdir dir="G:\Pribadi\MyProgramming\Java\JavaProject\Blog\output"/>
</target>
<target name="compile"  depends="prepared">
      <javac srcdir="G:\Pribadi\MyProgramming\Java\JavaProject\Blog\src"
                  destdir="G:\Pribadi\MyProgramming\Java\JavaProject\Blog\output"/>
  </target>
</project>

This code is a simple example of a build.xml file. From those lines we can see that there’s two task that is ant can call which is : prepare and compile. On prepare task, we see that there’s a directory that need to create with the mkdir command, where this directory is have to be located on G:\Pribadi\MyProgramming\Java\JavaProject\Blog path and the name of the directory is output. While in compile task, we can see that this task is depends on the previous task which is prepare task, mean if prepare task is failed to execute, and then this compile task wouldn’t never be executed. In the compile task, we also can see that the main function of the task is compiling all source code that located on G:\Pribadi\MyProgramming\Java\JavaProject\Blog\src.

Ant is also known property. In the build.xml file, property noted with the property syntax. Property is used in this build.xml file, as a variable of a value that might be taking space that too long, such as a path. On the lines above, we can change the directory name into a property, then the build.xml file will be like this:

<project name="Blog" default="compile" basedir=".">
<!--Define Params-->
<property name="src" value="${basedir}/src"/>
<property name="output" value="${basedir}/output"/>

<target name="prepare">
    <mkdir dir="${output}"/>
</target>

<target name="compile" depends="prepare">
    <javac srcdir="${src}" destdir="${output}"/>
</target>

<target name="clean">
  <delete dir="${output}"/>
</target>
</project>

On those lines, we can see that we can simplify the directory by adding property lines on the header of the syntax, and then on the prepare task and the compile task, we call those properties and turn it into a variable which has a directory path as a value. On those lines we also add a new task that can be executed by ant, which is clean task. This task is used to delete the directory that declared.

In the distribute issue of our hand made application which we have made with Java Programming Language, it’s highly suggested, that we have to pack our application on a jar file format. Especially if our hand made application contains a lot of classes. With this jar file, the class files are easier to maintain, because it’s only on a single jar file. Actually jar file is a zip file of java, even the class is on a package, but the classes inside of this jar file can be executed. When we execute a jar file that contains a lot of classes, we have to make an information on that jar file. This Information will tell the executable command, which is the main class of the jar file. This information is put on a file called manifest.mf on META-INF folder. In this manifest file also wrote some information of the application dependency to some libraries that we might be use on our application.

Please see the syntax of this build.xml file,below:

<project name="Blog" default="compile" basedir=".">
 <!--Define Params-->
 <property name="src" value="${basedir}/src"/>
 <property name="output" value="${basedir}/output"/>
 <property name="lib" value="${basedir}/lib"/>
 <property name="dist" value="${basedir}/dist"/>

 <target name="prepare">
     <mkdir dir="${output}"/>
 </target>

 <target name="make_jar” depends="compile”>
        <jar jarfile="${dist}/test_blog.jar">
               <fileset dir="${build}">
     <include name="**"/>
     </fileset>
                <manifest>
          <attribute name="Class-Path" value="lib/log4j-1.2.8.jar lib/commons-httpclient-2.0-rc2.jar  lib/jodd.jar ."/>
                </manifest>
    </jar>
</target>

 <target name="compile" depends="prepare">
     <javac srcdir="${src}" destdir="${output}">
 <classpath>
     <pathelement location="${lib}/ log4j-1.2.8.jar "/>
                          <pathelement location="${lib}/commons-httpclient-2.0-rc2.jar"/>
     <pathelement location="${lib}/jodd.jar"/>
           </classpath>
    </javac>
</target>

  <target name="clean">
      <delete dir="${output}"/>
      <delete dir="${dist}"/>
  </target>
</project>

On the above code we can see there are a few things that we added. The first adding is seen on the property lines. We added new property here that represent lib directory. The next adding is wrote on compile task code. We can add the some lines in this context if our hand made source code is also used other libraries. Lines added on this compile task, is used to import class-path of libraries when the compiling of the source code is run on the compile task.

In above code, we also add a new task which is make_jar task, the function of this task is creating a java archive file called test_blog.jar. This jar file contains all the class files that produced by a compile task. When we want to add files on a jar file we can use the fileset tag on that make_jar task. We also able to restrict the file that we will add to jar file by changing the value of include name tag and then we fill the value only with the list of files that we need. Remarks: include name tag is allowed to create more that one lines but the tag have to be inside the fileset tag.

And then we also could see in the make_jar task, there’s a line added which is manifest tag, this is the tag that write an information on a jar file. All of these information will we written on a file called manifest.mf and put it on a single folder that located on the distributed jar file.

That’s all, little discuss about the syntax on a file called build.xml, that can be executed by the Antoher Neat Tool (Ant). There’s still a lot of tags that we can use, so please try it with your own creativity, you can read the API of the ant it self for some references.

I hope this usefull, thanks

 

Menteng, Nov 30, 2008

josescalia