Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, March 29, 2009

Java Issues and Solutions - 4

Scenario 1: One large object (the object is to display dynamic fields on the page with different fields....it is dynamic in nature without having one unique field for field Ex: Company.Accounts[*].AccountNumber) should be displayed on the page,after selecting one radio button the object should be modified using service call and the updated value should be dispayed on the page without refreshing the complete page.

Possible Solution:Using AJAX: On change of the radio button javascript should be called, from the java script make ajax call to process to call a servlet. The servlet makes a business service call updated the object.But using AJAX only littl information can be returned to the javascript, the complete object can not be returned.

Alternative; Use JSON to modify the object with service call and return the updated object

On change of radio button call javascript which makes an JSON call. It hits the servlet, the servlet makes a business call and updates the object. the object is returned back to the javascript using JSON notation.But the updated object can not be displayed in the page without reloading the page. Since the object is dynamic the values can not set using Javascript.

Possible way is after making AJAX call and updating the object, only the part of the page where the object should be displayed needs to reloaded without realoding the complete page.

Scenario 2:

Problem: unlocking the DB when the user closed the browser using the broswers closing button (that is not logging off) (locking and unlocking the DB in the sense a flag is set to Y or N in the DB so that other user can not access that application)
Scenario: The application consists of multiple pages....on load of the first page the DB will be locked as per the requirements, this should be unlocked when the user clicks logoff. but what is the situation when the user closes the browser without logoff. (there should not be any time out option as the user can keep the page open for a long time) Solution; there is a javascriot event "onunload()" which is executed on close of the page, but the problem this will be fired even on click of the other page link or button to navigate to other page. Then how to handle ?on click of each other page link or button an action (application) willl be executed. to catch the event of broswer close the action wil be checked in unonload() javascript funtion.

If the action is something related to application navigation then dont make any call to unlock the DB, if the action is null then that means the broswer is closed in different ways (like clicking brosswer close button. closing it using task manager,right click and close when minimized etc., ). so when the action is null in the onunload() javascript make a call (may be AJAX call or submitdynamic action etc..depending on the applciation type) to unlock the DB.

Saturday, February 14, 2009

Java Issues and Solutions - 3

Common Exceptions and Solutions:

java.lang.NullPointerException;
Problem:The JVM throws null pointer exception when object accessing is dereferenced or not assigned any value.
Ex:
String s;
s.toUpper();
Customer c = null;
c.getName();

Solution:
Make sure that the object is assigned a proper value or its not dereferenced.
Ex: String s = "Test";
s.toUpper();
StringBuffer s = "";
s.append("test");
Customer c = new Customer();
c.getName();

Best Practise: Add null check before accessing any object.
Ex:
Customer c = someObject.getCustomer();
if( c != null)
{
c.getName();
}

java.lang.ClassCastException;
Problem:
The JVM throws class cast exceptions when your are trying to type cast one object which is not a type or sub type of that object.
Ex: X x = (X) y ; here Y should be either instance of X or it should be subtype of X.
class Customer{ -- }
clas Vehicle{ -- }
Vehicle v = new Vehicle();
Customer c = (Customer)v;
Here v is not an instance of Customer and its not s subtype of Vehicle, if you are trying to do this casting the JVM cannot caste the Vehicle object to Customer then it throws class caste exception.

Solutions:
Make sure that your trying to cast the appropriate type that is the exact instance of that class or sub type of that.
Ex:
X y = new X();
X x = (X) y;
class Vehicle{--}
class Car extends Vehicle{--}
Car c = new Car();
Vehicle v =(Vehicle)c;

BestPractise: Use intanceof check before casting the object
Ex:
class Vehicle{--}
class Car extends Vehicle{--}
Car c = new Car();
if( c instanceof Vehicle)
{
Vehicle v =(Vehicle)c;
}

java.lang.ArithmeticException:
Problem:
Mostly this exception will be thrown while trying to divide one variable or value by zero.
Ex:
int x = 10;
int result = x/0; or
int y = 0;
int result = x/y;

Solution: Make sure the divider value is not zero
BestPractise: Use != 0 check or >0 check for the divider before using in the arithmetic operation depending on the scenario.
int x = 10; int y = 0;
if(y > 0)
{
int result = x/y;
}

java.lang.NumberFormatException:
Problem:
This exceptions is thrown when your are trying convert a non numeric string to numeric.
Ex:
String responseCodeString = "x123";
int responseCode = Integer.parseInt(responseCodeString);
Solution:
Make sure that the string contains only digits or keep the statement in try catch block String responseCodeString = "123";
try{
int responseCode = Integer.parseInt(responseCodeString);
}catch(Exception e)
{
}

BestPractise: Use try catch block for this type of statements

java.lang.ArrayIndexOutOfBoundsException:
Problem:
This exception will be thrown while trying to access an index in an array which is more than the length of the array.
Ex:
String[] books = new String[3]; //allocates 3 places with index of 0,1 and 2
String thirdBook = books[3]; //the index 3 is not available in the above created array, it throws exception
Solution:
Make sure that you are using proper index before accessing the array or use the .length property to get the array size and do the operation.
String[] books = new String[3];
String thirdBook = books[2];// the index 2 is available in the above created array which returns third element
BestPractise:
Use .length property of the array before accessing its elements. int index = 3;
int size = books.length;
if(size > index)
{
String bookName = books[index];
}
This is mainly used in for loops as below.
for(int i=0;i<books.length;i++)
{
String bookName = books[i];
}

java.lang.NoClassDefFoundError:
Problem:
This exception is thrown when the specified class is not available at run time, this may happen because the class is not present in the current directory and not in the class path.
Solution;
1.Make sure that class is available in the current directory or
2.Make sure that class path is set for the specified class if it is not in the current directory or
3.Make sure that jar file is added in the class path if the class is present in any jar file
BestPractise:
Place all the classes or jar files at one place(like lib folder) and set the path to the place.

java.lang.IllegalStateException:
Problem:
This exceptions thrown when you are performing illegal operations on the object like accessing a closed IO stream or starting a thread which is already started etc.,
Ex:
1. con.close();
con.flush(); //The connection is already closed there is no meaning to flush the data for the connection.
2. t1.start(); //where t1 is a thread
t1.start(); //The thread has been already started again calling start leads to illegal state exception
Solution:
Check for the scenarios like where trying to performing illegal operation

java.lang.NoSuchMethodException:
Problem:
When we are calling the method on the object is not available
Solution:
Check for the below scenarios.
1. Check whether the calling method is defined on that object
2. Check whether the access modifier is private if it is accessing from the other class
3. Check whether the parameters and return types are proper

Java Issues and Solutions - 2

How to set the path?
Solution:
You can set the path in two ways.

1.Set the path at command prompt.
set path = "%path%;.;JAVA_HOME\bin";
%path% tells that the old "path" variable values should be remained as it is and the new values should be appended to the old 'path'variable value.
"." represents the current directory
It is a temporary solution the path variable is available only for the current session,
that is till the command prompt is closed.
Ex: C:\Mydirectory\JavaPrgs>set path = %path%;.;C:\Java\Jdk1.5\bin"; where C:\Java is the installation folder for Jdk.15

2.Set the path in MyComputer Environment variable.
Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "PATH" and enter the variable value as %path%;.;C:\java_home\bin; and click OK.
This is the permanent solution, this works fine till the java is there in the specified directory or the path variable available in the EnvironmentVariables.

How to set the classpath?
Solution:
Setting the classpath is very similar to setting the path variable.
This is also can be done in two ways.

1.Set the classpath at command prompt.
set classpath = "%classpath%;.;JAVA_HOME\lib";
%path% tells that the old "classpath" variable values should be remained as it is and the new values should be appended to the old 'classpath'variable value.
"." represents the current directory
It is a temporary solution the classpath variable is available only for the current session,
that is till the command prompt is closed.
Ex: C:\Mydirectory\JavaPrgs>set classpath = %classpath%;.;C:\Java\Jdk1.5\lib"; where C:\Java is the installation folder for Jdk.15

2.Set the classpath in MyComputer Environment variable.
Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "CLASSPATH" and enter the variable value as %classpath%;.;C:\java_home\lib; and click OK.
This is the permanent solution, this works fine till the java is there in the specified directory or the classpath variable available in the EnvironmentVariables.

How to set the Tomcat configuration variables?
Solution:
To run the Tomcat server you have to configure two variables in the EnvironmentVariables

1. JAVA_HOME : this is the Java installation home directory.
To configure this variable; Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "JAVA_HOME" and enter the variable value as C:\Java\Jdk.15;
(say java is installed in the C:\Java\Jdk1.5 directory) and click OK.

2. CATALINA_HOME : this is the Tomcat installation home directory.
To configure this variable; Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "CATALINA_HOME" and enter the variable value as C:\Tomcat5.0;
(say java is installed in the C:\Tomcat5.0 directory) and click OK.
(If tomcat is installed in the C:\jakarta_tomcat\Tomcat5.0 folder then set the value to this)

How to set the classpath to jdbc thin driver(that is type-4 driver) for oracle?
Solution:
To use the jdbc thin driver for oracle the classpath has to be set to the classes_111.jar or classes_12.jar or ojdbc14.jar depending on the oracle version.
For oracle 10XE thin driver classes are available in the ojdbc14.jar, you can set classpath to this jar in the EnvironmentVariables.
Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables,
if the CLASSPATH variable is already present click on the Edit and add the jar file path at the end of the classpath variable value.
Ex: %classpath%;.;C:\Java\Jdk1.5\lib;C:\oracleexe\app\oracle\product\10.20.0\server\jdbc\lib\ojdbc14.jar;
Depending on the oracle version search for the above mentioned jars and set the classpath to that jar as it is in the above example.
If the above mentioned jar names are in the zip format say classes_111.zip then rename the extension from zip to jar either directly or by
extracting then set the classpath to classes_111.jar
If your developing the application through the Eclipse or any other IDE add the jar in the classpath libraries in the below manner.
Right click on the project, select properties, select JavaBuildPath, select Libraries tab,click on the AddExternalJars button,
browse and select the jar click OK.

How to set the class path to run the servlets?
Solution:
1. Either set the class path to servlet-api.jar or j2ee.jar
2.Or add the jar to the class path of the project

Java Issues and Solutions - 1

How to convert an array to list?
Solution:
This is an example to convert String of arrays to list of arrays.//Say array is initialized as below
String[] s = new String[3];
s[0] = "test1";
s[1] = "test2";
s[2] = "test3";
//Method to convert array to list
private List convetArrayToList(String[] s)
{
List testList = new ArrayList();

//Conversion from array to list
int size = s.length;
for(int i=0;i<size;i++)
{
testList.add(s[i]);
}
return testList;
}

How to convert a list to array?
Solution:

This is an example to convert array list to String of arrays.
//Say list is initialized as below
List testList = new ArrayList();testList.add("test1");
testList.add("test2");
testList.add("test3");
//Method to convert list to array
private String[] convetListToArray(List list)
{
String[] s = new String[list.size()];
Iterator listIterator = list.iterator();
int i = 0;
while(listIterator.hasNext())
{
Object temp = listIterator.hasNext();
if(temp instanceof String)
s[i++] = (String) temp;
}
return s;
}

How to convert a numeric string to integer or double etc.,?
Solution:
Use the parseXXX method of that data types wrapper class.
String intString = "123";
int value = Integer.parseInt(intString);
String doubleString = "123.45";
double value = Double.parseDouble(doubleString);

How to store the elements in sorted order?
Solution:
Use tree set to store the elements, it stores the elements in sorted order.
Set s = new TreeSet();
s.add("CCC");
s.add("AAA");
s.add("GGG");
s.add("BBB");
Iterator setIterator = s.iterator();
while(setIterator.hasNext())
{
Object temp = setIterator.next();
String value = (String)temp;
System.out.println(value);
}
This will return the elements in the below order.
AAA
BBB
CCC
GGG

How get all the elements of a map without knowing the keys? or How to iterate through a map elements ?
We can't directly iterate through the map, you can do it by getting all the keys of the map into a set, iterating that set and by passing the set element to map as key you can get the corresponding value from map.
Map m = new Map();
m.put("1", "First");
m.put("2", "Second");
m.put("3", "Third");
m.put("4", "Fourth");
//Get all the keys from map
Set s = m.keySet();
Iterator setIterator = s.iterator();
while(setIterator.hasNext())
{
String key = (String) setIterator.next();
//Pass each key to the map to get the map value
//to the corresponding key
String value = (String)m.get(key);
System.out.println("The key is: "+key+" :value is: "+value);
}
This will give the output:
The key is: 1 :value is: First
The key is: 2 :value is: Second
The key is: 3 :value is: Third
The key is: 4 :value is: Fourth