Category Archives: Java

AJAX with Java

As a major requirement for AJAX application from server side language is to retrieve the request from client side and then parse it based on the format of the request. The request can be in form of a simple string, or XML, or JSON. And similarly the AJAX application expects a response back from server in one of these formats. Java can fulfill these requirements easily.

As for the first part, the server side language needs to accept the request from AJAX application in client side. Now Java has multiple ways to accept the request like JSPs, Servlets, Struts, JSFs etc. lets take a Servlet example

Public void doGet(HttpServletRequest req, HttpServletResponse res)
{
String ajaxData=req.getParameter(“Data”);
String returnString = executeAJAXRequest(ajaxData);
res.setContentType(“text/xml”);
res.getWriter.write(returnString);
}

Above one is a simple example. I left some of the details on purpose. Like what is executeAJAXRequest method doing. This will actually depend on the kind of request we receive.

The request might be a text based one where we don’t need to do any special parsing.

String executeAJAXRequest(String name)
{
String helloString= “Hello “+name;
return helloString;
}

That’s just a simple example; we could be doing some database operations in the method based on the name we got. But the idea is that the data is being used as it is. If it was a number say employee number we would convert to long and use.

Now if the data is in XML format. We already know that Java has strong XML support. It can parse and create XML documents easily using either DOM or SAX parsers. The following example shows how to parse data (uses apache’s xerces library)

ajaxRequest=”<employees><employee><name>John</name></employee></employees>”;

ArrayList executeAJAXRequest(String ajaxRequest)
{
ArrayList<String> nameValueArray=new ArrayList<String>(10);
try
{
DOMParser parser = new DOMParser();

parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(ajaxRequest)));
DocumentImpl document = (DocumentImpl)parser.getDocument();

//get the root of the XML document
Node root = document.getFirstChild();
NodeList childNodes=root.getChildNodes();

for(int i=0;i<childNodes.getLength();i++)
{
nameValueArray.add(i, childNodes.item(i).getFirstChild().getFirstChild().getNodeValue());
}
}
catch (SAXException e)
{
e.printStackTrace();
//handle exception
}
catch(IOException e)
{
e.printStackTrace();
//handle exception
}

return nameValueArray;
}

The third way to pass data from client to server and vice versa is by using JSON. There are many libraries available in Java to parse and create JSON strings. Here is an example of code parsing a JSON String from client side using json-simple library (http://code.google.com/p/json-simple )

JSON string received from client is something like “{\”Employee\”: [{\”name\”: \”Eric\”, \”EmployeeNum\”: \”1232\”, \”Designation\”: \”SE\”}]}”

void executeAJAXRequest(String ajaxRequest)
{
JSONParser jsonParser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){

public List creatArrayContainer() {
//Add Details if required
return null;
}

public Map createObjectContainer() {
//Add Details if required
return null;
}
};

try{
Map jsonMap1 = (Map)jsonParser.parse(ajaxRequest, containerFactory);

Iterator iter1 = jsonMap1.entrySet().iterator();
while(iter1.hasNext()){
Map.Entry entry1 = (Map.Entry)iter1.next();
String valueString=entry1.getValue().toString();
String dataString=valueString.substring(1,valueString.length()-1);

Map jsonMap2 = (Map)jsonParser.parse(dataString, containerFactory);

Iterator iter2 = jsonMap2.entrySet().iterator();
System.out.println(“Here are the Employee Details”);
while(iter2.hasNext()){
Map.Entry entry2 = (Map.Entry)iter2.next();
System.out.println(entry2.getKey() + “=>” + entry2.getValue());
}
}

}
catch(ParseException pe){
System.out.println(pe);
}
}

Interesting Java Facts -2

Here is a interesting Java question. What should be values of x and y in below to make the while loop infinite / non terminating

while (x <= y&& x >= y && x != y) {
System.out.println(“hello”);
}

Hint: Answer lies in autoboxing.

Ok, the answer is

Integer x = new Integer(0);
Integer y = new Integer(0);

Now try to think why?

Wrapper Classes and Autoboxing in Java

We know in Java everything is an object, except, primitive types. Primitive types are char, int, boolean etc. As all other things in Java are objects, it is desirable to use our primitve types as Objects. An example situation is when we want to add int to an ArrayList which only accepts objects. The answer to this problem is wrapper classes like Integer class. We can wrap our primitive types into these class objects.

Integer iVal=new Integer(123);

So that is a wrapper class. Lets understand autoboxing now.

How to increment the value of iVal by 10?

Normal Scenario

Integer iVal=new Integer(123);
int temp=iVal.intValue();
temp+=10;
ival=new Integer(temp);

Java knows this is bit of a pain so it provides you help in form of autoboxing.

Autoboxing works

Integer iVal=new Integer(123);
iVal++;

How to use switch statement for String before Java 1.7

How to use switch statement for String before Java 1.7

We know that Java has provided us the functionality of using switch statements directly using Strings. If you are using an older version for some reasons, you can achieve the similar functionality using enums.

Here is an example

public class test2 {

private enum MyEnum{
red, green, blue;
}

public static void main (String s[])
{
MyEnum e=MyEnum.valueOf(“blue”);

switch(e)
{
case red:System.out.println(“red string”);break;
case green:System.out.println(“green string”);break;
case blue:System.out.println(“blue string”);break;
default: System.out.println(“default string”);
}

}
}

What is Type Erasure?

Since Java 5, Java has come up with the concept of Generics. Idea of generics came from the fact that developers at times faced issue with assignment of data types to Lists and other structure. In case a wrong type was assigned or was tried to fetched, error could be caught at run time only

Example

ArrayList arr=new ArrayList();
arr.add("kamal");
Integer i=arr.getIndex(0); //run time error

So Java gave us an option

ArrayList arr=new ArrayList();
arr.add("1");
Integer i=arr.getIndex(0); //compile time error

But we should note that Generics is a compile time concept. When Java convert the code to bytecode for JVM, it removes all generics related info. So finally

ArrayList arr=new ArrayList();

will be converted to

ArrayList arr=new ArrayList();

This concept is known as Type Erasure. This was necessary for Java in order to give backward compatibility, otherwise the code written earlier would not have been supported by newer JVMs.

Using Reflection with Android

Faced an interesting problem today. In my android app I needed to show some random strings on the UI (textview).  So obvious solution was to add the strings in string.xml (for supproting i18n), and then fetch the text based on the random number generated.

textView.setText(R.id.text_1);

or if random number is 2

textView.setText(R.id.text_2);

and so on

I realized that only change happening is the last one digit, so this is a good candidate for using reflections.

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(field.get(null)));

But this actually gave an Exception for ClassCast, so I realized that field.get(null) is actually returning the resource Id (as shown in R.java class) instead of string value.

The fix found was to use getResources().getString(resource_id) to fetch the string from the resource id

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(getResources().getString((Integer)field.get(null)));

Interesting Java Facts

I am working with Java for more than 7 years now and still it surprises me with some very basic stuff

Can you guess what is the output of this statement in Java

System.out.println(1+2+” = “+1+2);

3=12

Why? Apparently Java starts treating everything as a String once it has encountered a string in System out statement

Exception Handling- Basic Principles

Do not catch unchecked exceptions
Exceptions in java can be divided into checked and unchecked exceptions. Java compiler would force you to catch the checked exceptions but not the unchecked exceptions. Unchecked exceptions includes error and Runtime exception. These are the conditions in which program will not be able to handle the flow even if these are caught, so better let the JVM throw error and print stack rather than trying to handle these.

Error- A condition which occurs outside the program and causes failure, example, hardware failure.
Runtime Exceptions- An exception condition which occurred because of bad programming practice or unexpected input from user. For example, null value assigned to a variable being used or division by zero. Ideally these errors should be handled by code checks and not exception handling.

This means we should avoid catching superclass Exception as that will cover RuntimeExcpetions

Throw more relevant exceptions
Exception handling is done at multiple levels in code. For example you have, action->Process->Data layer. Now you might catch an exception in Database layer, but you might want to handle the exception actually in Action layer. So rather than throwing back filenotfound or sqlexception, you can create a DAOException and throw it instead. which will travel through Process layer and then to Action. This will help Action to handle fewer exceptions which are relevant at that layer.

Caveat- You might want to make sure you are passing all the relevant information back to the upper layers.

Using multiple try-catches
Instead of using one big block of try catch, create multiple blocks for better handling of exceptions. Make sure to take care of flow, once an exception is handled, the code will move to next try block.

Handle Exceptions late in code flow
Throw exceptions back to higher layers rather than absorbing them at lower layers. E.g. If an exception is caught at DAO layer, you might still want to throw it back to action layer for better handling.


Extend Exception and not Throwable

Here is the hierarchy of Exception class structure. Ideally we should try to extend a class as low as possible in hierarchy

Object->Throwable
Throwable->Exception and Error
Exception-> RuntimeExceptions and [other exceptions like filenotfound]
RuntimeException-> ArtithmeticException, NullPointerException

References:
http://wikijava.org/wiki/10_best_practices_with_Exceptions
http://docs.oracle.com/javase/tutorial/essential/exceptions/

Using Javadoc for documentation

What is Javadoc? Most of the times people confuse it with the actual HTML documentation for the Java code. This is somewhat true but not entirely. Javadoc, itself is not the documentation, it is a tool from SUN Microsystem that helps you generate the documents.

How does it work? Javadoc allows developers to add documentation for a code in the java file itself in some specially formatted comments. The tool will read these comments and create a HTML document file.

Why do we use Javadoc? Why can’t we just create documents on our own? Well That is possible. Javadoc is there to make your life simpler as a developer. It helps you keep your code and documentation information in the same file. Just imagine if you are keeping the documentation separately, everytime you make a change in code, you ill need to modify the documentation also. What if someone misses it? If it is in the same file it is easier to maintain and hard to miss.  Most importantly, you are not writing the whole documentation, but just adding some quick comments which will be interpreted by the Javadoc tool. Lot more easier and faster than actually writing the documentation.

How to implement it? Simple, just add some specially formatted comments in your code

Class Level comments

@author : Author of the class
@version : automatically provide accurate version and date updates.
@since :  Describes when this functionality has first existed.

Method Level

@param : method or constructor argument names and description
@return :  What does your method returns
@throws : Does this method throw an exception
@deprecated : 	Describes an outdated method.

General Commets

@see : Adds 'See also' entry
@link : Adds an inline link with a label for users of your API documentation

The final code will look something like

import java.util.ArrayList;

/**
 * This is a Java Class to find anagrams. Any class level description goes here
 *
 * @author kamal
 * @version 1.0
 * @since 21-Sep-2011
 */
public class test{

/**
 * This is the main method method
 *
 * use {@link #findAnagrams(String)}
 * @param str
 * 		Any param description goes here
 */
public static void main(String str[])
{
	try
	{
		 String finalString="TestString";
		 test t =new test();
		 t.findAnagrams(finalString);
	}
	catch(Exception e) {
	   e.printStackTrace();
	}
}

/**
 * This is another method and we will add the description here
 *
 * @param input
 * 		Any param description goes here
 * @return
 * @throws NullPointerException
 */
private ArrayList findAnagrams(String input) throws NullPointerException
{
	ArrayList retList=new ArrayList();
	if(input.equals("")) throw new NullPointerException();
	printAnagrams(retList, "",input);
	return retList;
}

/**
 * Yet another method description goes here
 *
 * @param retList
 * @param prefix
 * @param word
 */
public void printAnagrams( ArrayList retList, String prefix, String word) {

if(word.length() <= 1) {
	retList.add(prefix + word);
} else {
for(int i = 0; i < word.length(); i++) {
String cur = word.substring(i, i + 1);
String before = word.substring(0, i); // letters before cur
String after = word.substring(i + 1); // letters after cur
printAnagrams(retList,prefix + cur, before + after);
}
}
}
}

and your javadoc comments will look like

image link

testdoc