Sunday, August 19, 2007

How to upload a file to server

We can use html form's file control to upload a file to server end.
This is not a simple process as form data is not a simple data but the
form data must be set to enctype="multipart/form-data" and method must
be set to POST.
One simple form may be like follows

<form name="form1" action="/uploader.htm" method="post" enctype="multipart/form-data">
<input class="fileUploadInput" type="file" name="file">
<input type="submit" value="Upload">
</form>

At Server end we can use one of several possible wrappers available for
file upload. One I will use here for demonstration is very popular library
provided by jakarta commons file upload library. It's jar commons-fileupload.jar
can be downloaded from site http://commons.apache.org/fileupload/.

I will write a code to process the request's data to extract file content from
uploaded form data. Since the data is of multipart in nature, I will use a wrapper
for file data given by commons file upload library.

Suppose you are given an instance of HttpServletRequest named as request in your servlet context.
You can use it to parse the file data as follows

String UPLOAD_DIR = "/uploadDir";
DiskFileUpload diskFileUpload = new DiskFileUpload();
diskFileUpload.setSizeMax(1000000);

List fileItems = (List) diskFileUpload.parseRequest(request);

for (FileItem fileItem : fileItems) {
if (fileItem != null) {
if (!fileItem.isFormField()) {
File file = new File(UPLOAD_DIR + File.separator + fileItem.getName());
fileItem.write(file);
}
} else {
System.out.println("File Item is null. Kindly Check it.");
}
}


This code when executed will save a file to /uploadDir location.

First of all we created a DiskFileUpload instance and then it's size was set to 1 MB.
Then request instance was parsed to create a list of FileItems. Each FileItem represents
a single form field. It may be a File Field or it may be a simple form field such as
a input type or it may be a button etc. So to parse the file type we need to put a check if
this is not a form field (or it is a file type field), this is done using the inner if
clause. If this is of type file then a new File instance is created using the name of
fileName.getName(); and then the file is written to the UPLOAD_DIR.

Sphere: Related Content

Friday, June 15, 2007

How to count html links in a web page

We can use parse the hmtl pages of a site and then further write a recursive program to count the no of html links present in that web page.
Here is the code snippet that will give you an idea.

Suppose your web page content is given as a String object in java

This program parses the above html page and will return you two html links present in the web page as follows.

2
http://localhost/mypage1.html
http://localhost/mypage2.html

2 is the total count of html links present in web page and links are given at each
line.

Following is the program that gives us total html links and their count




Modifications can be done to this code so as to incorporate hashmap instead of arraylist. This may be helpful if we want to count only unique links present in the page.

When we use hashmap, we can use this program to recursively crawl the website's each
page as each link will be unique in hashmap and we can fetch pages corresponding to those links using standard java techniques and hence recursively applying the program for newly obtained page content.

Sphere: Related Content

Monday, June 11, 2007

Formatting a number to a fixed number of decimal places

We can use a DecimalFormat object to format a given number to a fixed number of places.
Here is the example that does the trick

import java.text.DecimalFormat;
import java.text.ParseException;

public class TestClass {
public static void main(String[] args) throws ParseException {
double doubleAmount_ = 10000;

DecimalFormat currency = new DecimalFormat("$0.00 dollars");

// Without using DecimalFormat class and hence without using fixed no. of decimal places.
Float result = (float) doubleAmount_ / 66;
System.out.println("$" + result + " dollars");
// Now using DecimalFormat class and hence fixing no.of decimal places to two.
String formattedResult = currency.format(result);
System.out.println(formattedResult);

// parsing a float value from a String using a DecimalFormat class.
String strAmount = "$10000.00 dollars";
Float floatValue = currency.parse(strAmount).floatValue();
System.out.println(floatValue);
}
}

Here are the results:

$151.51515 dollars
$151.52 dollars
10000.0

In the constructor of DecimalFormat we pass the format string, according to which the input value will be formatted.
I have demonstrated two ways in which divison is performed. First one is normal divison and hence leads to unformatted
output 151.51515, but in second the division is formatted upto two decimal places using format method of DecimalFormat
class.

Further we can use DecimalFormat class to parse a number from a formatted string like done above. In this case we use
parse method of DecimalFormat class. this gives us the output of 10000.0 when given an input string "$10000.00 dollars".

We can typically encapsulate the DecimalFormat object within a class, so that each time we do not need to pass the DecimalFormat
class instance. Typically we use toString method to format the results.

Using this model, here's the example

public class TestClass {

public static void main(String[] args) {
double totalAmount = 10000.0;
DecimalFormatTest amount = new DecimalFormatTest(totalAmount / 66);
System.out.println(amount);
}
}


class DecimalFormatTest {
double amount_;

public DecimalFormatTest(double amount) {
amount_ = amount;
}

public String toString() {
DecimalFormat currency = new DecimalFormat("$0.00 dollars");
return currency.format(amount_);
}
}


It produces the following output
$151.52 dollars

Sphere: Related Content

Sunday, May 27, 2007

Java Rules: equals and hashcode in Java

Java Rules: equals and hashcode in Java

Sphere: Related Content

Monday, May 21, 2007

equals and hashcode in Java

equals() and hashCode().
These two are the methods most often overridden after toString() method. All of these methods are defined in java.lang.Object class. These method play an important role when using Collection API of Java. They provide a way to check the equality of records or mappings being put into collection.If you override equals() method, you must override hashCode() to make sure that the objects which are equal return the same hash code.Keep in mind that two equal objects must return the same integer.
In short the requirements of eqauls and hashcode implementation are.
1. equals(null) must return false.
2. If Object1.equals(Object2) returns true, then Object2.equals(Object1) must also return true.
3. If equals() returns true for two objects, both objects must return the same integer from the hashCode() method.
4. If two objects are same they must reproduce same hashcode value for all different invocation of hashcode method unless their state is changed programatically.

Sphere: Related Content