Windows Delayed Write Failed On Maxtor One Touch 4 Mini

maxtoronetouch4miniOn December 26th 2008, I bought a external hard-drive, Maxtor One Touch 4 Mini with 160 GB capacity and it cost about 750.000 IDR. At the first time I use this external hard-drive I was very disappointed, I cannot use this external hard-drive at all. When I plugged in USB device to my laptop, my Windows XP cannot recognize this new hardware. At first time, I suspected this Windows XP cannot recognize this hardware, then I switch my operating system into Linux Open Suse, the other operating system that I‘ve been choose for my own computer, but the fact, I got one more disappointed feel, this Open Suse also cannot recognize this new hardware.

Well I think there’s nothing wrong with my laptop or the operating system. It must be this external hard-drive got some error when it comes out from its vendor. Anything broken maybe or I don’t know, obviously this is about this external hard-drive and its not about my chosen operating system, so I decide to returning back to the shop where this external hard-drive have been bought by me. At the shop, this hard-drive checked by the technician of the shop. And the result of this checking is make feel better, indeed this external hard-drive had something broken that can make it can be used. Then the shop replaces this external hard-drive with the other new external hard-drive that was still same type and same capacity with the broken one.

Before I took home this new external hard-drive, the technician makes sure that this new hardware is on good condition by trying first by him self. Indeed this one is on good condition and ready to use, so I agreed to take it home with me as a replacement of the broken one.

At home, I started to use this hard-drive to save the data which is very important to me. Because, indeed, I bought this external hard-drive in order to backing up all the important data. Backing up the data became a part of my computer activity.

Actually, I want to split this external hard-drive into two partitions, but I can only do that 2 days after, because I didn’t have a software on my laptop that have an ability to split the partition of this external hard-drive. Well as a customer I thought, I want to know the quality of the stuff that I bought rite? So I planned to do some test on this external hard-drive. My first simple test is copying the large size of files from my laptop into this external hard-drive. So I try to test it by copying a file that have 500 MB of its size with one single copy and one single paste, the result is not bad, this new external hard-drive capable to receive the data directly from a single copy-paste for 500 MB size of files. Actually this test is goes to USB cable, to find out whether this USB cable is capable or not to transferring the 500 MB file size.

And then I try to copy-paste a data file that have 1GB of size, and the result is still good, but when I try to copy-paste a data file that have 2GB file size, this hardware is apparently showing its weakness. When the data copying into this external hard-drive, and the progress just reached 45% of copied file, there’s an alert balloon showing up at the bottom-corner of my desktop windows, “Windows Delayed Write Failedand bla..bla..bla… now I can found out that this external hard-drive was cannot resist for transferring data file that large then 2 GB file size. And then I try to delete the failed copied file, but I feel so disappointed, this failed copied file cannot be deleted, when I try to delete, there’s a windows dialog showed up, telling that this failed copied file cannot be deleted. So I try to delete the file using Dos Console, and it still cannot delete. I try to switch to Linux open suse, and its still same, its still cannot be delete, so I left this failed copied file. I will remove it by formatting this external hard-drive and split its partition into 2 partitions. So this external hard-drive will have clean storage.

Two days later, I split this external hard-drive into 2 partitions with same size, each of this partition have 80 GB capacity. And then I try to do above test again, this test was failed the windows still have this windows delayed write failed.

And then I format again, and do the splitting once again, and do the test once again, but now I’ll test this external hard-drive using Linux operating system. Its little weird, the result that goes with Linux, found there’s none of this external hard-drive had some error, the copy of 2GB of file size was run properly, there’s no corrupted file found.

Hmm, I started to think, maybe there’s a problem with my Windows XP when the 1GB file size or above being copy to the external hard-drive. I tried to find out by browse Microsoft web site on FAQ and Bugs page. And I also search another web site or articles in the internet. By these browsing, I can make some statement that there are problems on the Windows system cache when we copy the data with a large size onto external hard-drive. Even the answer of Microsoft website about this problem focused on the failed of the external hard-drive connector, such as USB cable, etc, I still keep the statement that this is all about Windows XP system cache problem.

Then I try to find out once more by browse the internet, the possibility of any one else having same problem like me and how he or she solve the problem. After two days, finally I found a related article, and in these article also written how to solve these problem. Unfortunately, I forgot the link, but the important thing is, this link is not the Microsoft website or this external hard-drive vendor web site, but some one else which have same problem with me.

Ok, the focus of this problem fixing process is, by enlarging Windows system cache. I used software to change to change this windows system cache. I know this software also from the article that I’ve read before. This software name is Cacheman made by Outer Technologies. This software is not free, and I used version 5.0. I used this version because we can still use this software even we don’t do any registration. :P

After the installation of this software is successful on my Windows XP, refer to the article I made some changes on my Windows XP system cache, and then I restart my Windows XP and make some test again just like before.

The test by copying 2GB file size to the external hard-drive running well, there’s no more Windows Delayed Write Failed, I’m happy. Then I try to copy file that larger then 2GB of file size and its still have no problem at all. After do test by copying 5GB file size onto this external hard-drive and its success, I stop the test, and I think the test is finish.

I’ve planned to test for a week, before I can make a decision that this test is really-really passed. And when this article written I still cannot found a same problem with before. Then I decide that Windows Delayed Write Failed that happen on my external hard-drive is solved, I can use this external hard-drive normally.

Below are the steps, when I’m using Cacheman5.0 to change my Windows XP system cache in order to solve the Windows Delayed Write Failed problem that happen on my brand new Maxtor One Touch 4 Mini 160 GB.

On show wizard menu, I choose all, and for the entire window that showed up, here are the details:

1.Disk Cache: choose Balance
2.Icon Cache: choose Set large maximum Icon Cache size
3.Unload DLLs from Memory: choose Enable
4.Disable Paging Executive: choose Enable
5.IO Page Lock Limit: choose Large IO page lock limit value
6.Disable NTFS last access update: choose Enable
7.Disable creation of short filenames: choose Enable
8.Reserve more space for the Master File Table: not enable (don’t check)
9.Defragment hard disk when idle: choose Enable
10. Hung App Timeout: choose Optimize
11. Wait to Kill App / Service Timeout: choose Optimize
12. Menu Show Delay: choose Optimize
13. Filename Completion: not enable (don’t check)

That’s it, Windows system cache setting using Cacheman on my Windows XP, to prevent Windows Delayed Write Failed problem.

Menteng, January 4th, 2009

I Hope this will helpful

Josescalia

Advertisements

Find Out Prime Number with Java Application

One day, there’s some one came to me and intent to start learning Java programming, she asked a lot about Java and it’s technology. One of her question based on her story-told is how can we make a Java application which is able to generate an array of prime number?, the problem is, I have forgotten what is the definition of prime number it self, so we had a problem to make the application that will appropriate with her idea. ha..ha..ha..(what an excuse…!!!).

Yesterday, I remembered that, and I go Googling, to find out what is prime number definition. From the Indonesian version of wikipedia site, I found prime number definition, but I tried to make my own comprehension of this prime number, Prime Number is a real number beginning with 2, this prime number is a number that is not exactly divisible by any number less then it self, except 1. That’s my comprehension of prime number, so let’s take a number and try to check with my comprehension, lets take 15 as a sample. Is 15 is prime number?, we will arrange our inspection like this :

  1. Is 15 is more or equals to 2 (15 >= 2 ) ?, because first condition of prime number is real number that start from 2.
  2. Is 15 exactly divisible by a numbers started from 2 until 14 ?, because other condition of prime number is a number that is not exactly divisible by any number less then it self, except 1.

OK, let’s run this inspection one by one, for the first step of the inspection, 15 is fulfill the condition of a prime number, meaning that 15 >= 2 is true or correct. And then let’s continue with the 2nd step of the inspection. Is 15 is exactly divisible by 2, and the result is 15 got reminder when it devise b,y 2, because 15/2 =7 and the reminder is 1. The checking is continue by devise again with next number which is 3, at this division, it’s clear that 15 is not a prime number, because 15 devise by 3 is got no reminder. And we can assume that 15 is not a prime number because 15 is exactly divisible by 3.

Now, let’s take a new number to check, the new number is 17, and we will check whether this 17 is a prime number or not using same inspection above. For the first check, it’s clear that 17 is highest than 2, and for 2nd inspection, let’s take a look the picture below:

17 / 2 = 8 remind 1
17 / 3 = 5 remind 2
17 / 4 = 4 remind 1
17 / 5 = 3 remind 1
17 / 6 = 2 remind 5
17 / 7 = 2 remind 3
17 / 8 = 2 remind 1
17 / 9 = 1 remind 8
17 / 10 = 1 remind 7
17 / 11 = 1 remind 6
17 / 12 = 1 remind 5
17 / 13 = 1 remind 4
17 / 14 = 1 remind 3
17 / 15 = 1 remind 2
17 / 16 = 1 remind 1

On the above picture we can see that 17 always got reminder when we devise it by any number that less then 17, except 1. And now we can assume that 17 is a prime number.

How about, if with those steps we try to make a Java application that have an ability to check a number whether is a prime number or not. OK, let’s try to make an application that have an ability to check a number whether it’s prime number or not, here comes the codes:

package org.mojo.blog.app.integer; //ignore this, if this program is not on package

public class isPrimeApplication {

    public static void main(String[] args) {
        int valueToCheck = 17; // value to check
        boolean isPrime = false;
        if (valueToCheck >= 2) {
            isPrime = true; // first check and assume it's prime number
            // try divide valueToCheck
            // with all number less than it self
            // and begining from 2
           for (int i = 2; i < valueToCheck; i++) {
            if (valueToCheck % i == 0) {
                    //if divides exactly so stop the loop and it must be not prime
                    isPrime = false;
                    break; // no need to check again
                }
            }
        }
        System.out.println("is " + valueToCheck + " Prime ? ");
        System.out.println("the answer is " + isPrime);
    }
}

In above codes, we can see that we have 2 variables, valueToCheck and isPrime, and the process flow will look like exactly same with the inspection above, where :

  1. if (valueToCheck > = 2) is first inspection, the number which entering this block will temporary assumed as prime number.
  2. for (int i=2; i < valueToCheck; i++), we will do loop, start from 2 until the value of checked number minus 1 (valueToCheck – 1) . And then we will do checking, if from this loop operation there’s a number can exactly divisible, then stop the loop, cos that number is not a prime number clearly.

Hmm, what if we continue the development of this application become an application that have an ability to find out prime numbers of given range, such as, find out prime numbers between 0-50. It looks like, we can make it by adding just one looping-logic before the existed loop. Let’s take a look of this codes :

package org.mojo.blog.app.integer; //ignore this, if this program is not on package

public class PrimeAdvance {

    public static void main(String[] args) {
//      int valueToCheck = 17; // value to check
        int nRange = 50;
        boolean isPrime = false;

        for (int i = 2; i <= nRange; i++) {
            if (i >= 2) {
                isPrime = true; // first check and assume it's prime number
                // try divide valueToCheck
                // with all number less than it self
                // and begining from 2
                for (int j = 2; j < i; j++) {
                    if (i % j == 0) {
                        //if divides exactly so stop the loop and it must be not prime
                        isPrime = false;
                        break; // no need to check again
                    }
                }
            }
            if(isPrime){
                System.out.println(i);}
        }
        //System.out.println("is " + valueToCheck + " Prime ? ");
        //System.out.println("the answer is " + isPrime);
    }
}

On the above code, we can see that we just add one looping-logic before the existed looping. And then we add lines to check if i is prime number, then print out i to console. And we put this lines inside the block of looping the range data that will check.

That’s it, a little story about the my wondering of prime number, triggered by friend’s story. You can use it freely if it’s helpful for your case, and it’s freely too for you to develop mode if you have any brand new idea.

To more understand the prime number it self, here’s a link of Java program source code, that I have added some console print out, in order to watch the process of finding out a prime number from a given range

 

I hope this helpfully

Menteng, 01 January 2009

josescalia

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

 

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 

Making Send Mail Web Application with Java

In a websites we often see an interactive feature that can make possible to user to send email to others. This feature is called web-mail. Web mail is a web application which has capability to read and send email through internet browser. There’s a lot of web-mail application that might be we use often. Like yahoo-mail, or Gmail, etc.

In the use of web-mail application, some of developer also use it as a communication tools between user and the internal side of those web-site owner, such as send email to an admin of the web site jut like this link.

Now, we will try to make a send mail web application, for this purpose we will limit the project only to send mail, not read the mail from other mail server. Maybe in the next chance we will discuss about how to read the mail that exist from a mail server.

Ok, now we just go straight…:D

To make this send mail web application with java, we will need some library. Those library is mail.jar and activation.jar. so you can download those library through this link

  1. mail.jar

  2. activation.jar

The process flow of this web application is:

From a standard html form which consist of some input type and a text area, we will posting using HTTP POST method to a servlet that containing methods send mail. And then the status of sending mail will be displayed on a html page.

sendmailflow

 

On the standard html form we need a few input type and a text area. The picture show below hopefully can present.

sendmailform1

And for the servlet scenario, lets arrange with the steps below :

  1. Initialize the smtp host in init servlet methods

  2. Initialize all params that send by standard html form.

  3. On a try-catch block do the following steps:

    • Create java mail session

    • Constructs the message

    • Set the form address and recipient address

    • Set the message

    • Transport the mail

    • Print out the send mail status on html page.

  1. We ca use the catch blok to set the status for causes fo failure send mail process

  2. Print out the send mail status on html page.

To those servlet scenario below is the list of the servlet code.

package org.mojo.mail.web.servlet;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
* Created by IntelliJ IDEA.
* User: Muhammad Yusuf
* Date: 23 Nov 08
* Time: 13:27:09
* To change this template use File | Settings | File Templates.
*/
public class SendMailServlet extends HttpServlet {

private String smtpHost;

//initialize this servlet to get SMTP Host Name to use in sending message
public void init(ServletConfig config) throws ServletException {
   super.init(config);
   smtpHost = config.getInitParameter("smtpHost");
}

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String from = req.getParameter("from");
    String to = req.getParameter("to");
    String cc = req.getParameter("cc");
    String bcc = req.getParameter("bcc");
    String subject = req.getParameter("subject");
    String text = req.getParameter("text");

    String status;
try {
    //create java mail session
    Properties prop = System.getProperties();
    prop.put("mail.smtp.host", smtpHost);
    Session session = Session.getInstance(prop, null);

    //construct the message
    MimeMessage message = new MimeMessage(session);

    //set the from adress
    Address fromAddress = new InternetAddress(from);
    message.setFrom(fromAddress);

    //parse and set the recipient
    Address[] toAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.TO, toAddress);
    Address[] ccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.CC, ccAddress);
    Address[] bccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.BCC, bccAddress);

    //set The Subject and Text
    message.setSubject(subject);
    message.setText(text);

    //begin send Message
    Transport.send(message);
    status = "Your Message has sent";

 } catch (AddressException aex) {
      status = "There was an error when parsing the address";
 } catch (SendFailedException sfe) {
      status = "There was an error when sending the Message";
 } catch (MessagingException me) {
     status = "There was unexpected error";
 }

   //print out status in display
   res.setContentType("text/html");
   PrintWriter writer = res.getWriter();
   writer.println("<html><head><title>Status</title></head>");
   writer.println("<body><p>" + status + "</body></html>");
   writer.close();
 }
}

Let’s discuss those codes.

package org.mojo.mail.web.servlet;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

Just like usual these lines is created to define where the package of this servlet made and importing all the class that might be we need later.

public class SendMailServlet extends HttpServlet {
………..
…….
}

Above code is show us, that we create a servlet class and we name it SendMailServlet, Just because this class is a servlet so we have to add extends HttpServlet there. And then we have to make deployment descriptor(web.xml) file that we will place it at <ApplicationServer>/webapps/<ApplicationName>/WEB-INF/

The deployment descriptor file is shown below:

mail-webxml

On this file we can see that the servlet class that we’ve made, we define here and we name it as sendMessage, and then we will mapping this name to url called /sendMessage. That’s why on the standar html form the action will lead this post to this url. And see that in this file we also initialize a parameter, we named it as smtpHost and the value of this parameter is smtp.speed.net.id, you can change this value depends on which smtp server we use to send the message through this web application

Now let’s see another line of the servlet.

private String smtpHost;

//initialize this servlet to get SMTP Host Name to use in sending message
public void init(ServletConfig config) throws ServletException {
   super.init(config);
   smtpHost = config.getInitParameter("smtpHost");
}

In above code we declare a variable named smtpHost, and this variable is string. Then in the next line we see that this variable now has a value that taken from the web.xml file. This method is using ServletConfig object.

Now let’s see the doPost method below:

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
   String from = req.getParameter("from");
   String to = req.getParameter("to");
   String cc = req.getParameter("cc");
   String bcc = req.getParameter("bcc");
   String subject = req.getParameter("subject");
   String text = req.getParameter("text");

   String status;
…………
………..
}

Those lines are lines which we take all the value that posted by standard html form and then put it into variables. In this lines we also define a variable that we will use to display the status of the send mail, this variable named status and this is string type.

For the third point of above servlet scenario, we will do it in try-catch block just like the following code.

…………..
try {
    //create java mail session
    Properties prop = System.getProperties();
    prop.put("mail.smtp.host", smtpHost);
    Session session = Session.getInstance(prop, null);

    //construct the message
    MimeMessage message = new MimeMessage(session);

    //set the from adress
    Address fromAddress = new InternetAddress(from);
    message.setFrom(fromAddress);

    //parse and set the recipient
    Address[] toAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.TO, toAddress);
    Address[] ccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.CC, ccAddress);
    Address[] bccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.BCC, bccAddress);

    //set The Subject and Text
    message.setSubject(subject);
    message.setText(text);

    //begin send Message
    Transport.send(message);
    status = "Your Message has sent";

} catch (AddressException aex) {
…………..
………….

On that code lines, we can see one by one of the servlet scenario on the third point handled, from the making a java mail session till give the value for variable status.

Now let’s see the catch block or a fourth point of servlet scenario.

………….
 } catch (AddressException aex) {
     status = "There was an error when parsing the address";
 } catch (SendFailedException sfe) {
     status = "There was an error when sending the Message";
 } catch (MessagingException me) {
     status = "There was unexpected error";
 }
………….
………….

On that code, we optimize the variable status, we fill this variable with the value that suitable with the error message that can be happen on our servlet. From wrong email address error, till the unexpected error.

Now we meet the last lines of the code.

……..
//print out status in display
        res.setContentType("text/html");
        PrintWriter writer = res.getWriter();
        writer.println("<html><head><title>Status</title></head>");
        writer.println("<body><p>" + status + "</body></html>");
        writer.close();
    }
…….

On this last lines, we make a response as a html type that inform the status of send mail transport. Its easy rite ? now it’s your turn to create and free to modified this all codes for your need.

 

I hope this will be usefull

 

Menteng, November 23rd, 2008

Josescalia