Friday, September 30, 2011

How to handle One apostrophe in SQL string

If you are using SQL strings in your database operations, chances are you have come across problem with strings in SQL statement. One apostrophe screws up the SQL string, causing the SQL statement to fail.

Assume you have a SQL string:
SELECT * FROM tUsers WHERE LastName='O'Brien';
When LastName contains a name like O'Brien, the final string becomes


The second ' ends the SQL statement, leaving the rest of the string dangling. The solution is easy: Replace each ' in O'Brien with two 's, something like O''Brien, so the final SQL looks like:

SELECT * FROM tUsers WHERE LastName='O''Brien';
The second ' "escapes" the third ', thus leaving the whole SQL statement complete.

Sunday, August 7, 2011

Difference between Shallow Copy and Deep Copy

Shallow Copy
This is a result of the default cloning functionality provided by the Object.clone() method if the class has non-primitive data type members as well. Shallow Copy concept is not applicable to the classes having only primitive data type members as in that case the default cloning will also result into a Deep Copy only.

In case of Shallow Copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That's why the name Shallow Copy. Read more about Cloning More Details
sample program :
package com.sallowcopy;
/**
*
* @author thanooj
*
*/
class Person implements Cloneable {
// Lower-level object
private Car car;
private String name;
private Integer no;

public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(Integer n, String s, String t) {
no = n;
name = s;
car = new Car(t);
}
public Object clone() {
// shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public void setNo(Integer no) {
this.no = no;
}
public Integer getNo() {
return no;
}
}

class Car {

private String name;

public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Car(String s) {
name = s;
}
}

public class ShallowCopyTest {

public static void main(String[] args) {
// Original Object
Person p = new Person(new Integer(1000), "sreeRama", "Garuda");
System.out.println("Original (orginal values): " + p.getNo() + " "
+ p.getName() + " - " + p.getCar().getName());
// Clone as a shallow copy
Person q = (Person) p.clone();
System.out.println("Clone (before change): " + q.getNo() + " "
+ q.getName() + " - " + q.getCar().getName());
// change the primitive member
q.setName("Indra");
q.setNo(new Integer(2000));
// change the lower-level object
q.getCar().setName("Iravath");
System.out.println("Clone (after change): " + q.getNo() + " "
+ q.getName() + " - " + q.getCar().getName());
System.out.println("Original (after clone is modified): " + p.getNo()
+ " " + p.getName() + " - " + p.getCar().getName());
}
}
//output :
Original (orginal values): 1000 sreeRama - Garuda
Clone (before change): 1000 sreeRama - Garuda
Clone (after change): 2000 Indra - Iravath
Original (after clone is modified): 1000 sreeRama - Iravath
-------------------------------------------
Deep Copy

We need to override the clone() method for the classes having non-primitive type members to achieve Deep Copy as Deep Copy requires the member objects to be cloned as well, which is not done by the default cloning mechanism. Why is it not done by the default cloning? Because clone() is a method of the Object class and at that level it's not known what a typical class can have as its members and hence only a field-by-field copy approach has been provided as the default cloning mechanism.

Implementing Deep Copy in Java

For Deep Copy, we need to ensure that the member classes also implement the Cloneable interface otherwise calling the clone() method on the objects of those classes will result into CloneNotSupportedException. So, to implement Deep Copy, we first need to ensure that all the member classes (at all the levels - like if the member class itself has a member of some class type then that class as well... and so on) are implementing the Cloneable interface. After that we override the clone() method in all those classes (even in the classes where we have only primitive type members otherwise we would not be able to call the protected clone()method of Object class on the instances of those classes inside some other class ... a typical restriction of the protected access. We'll cover this in a separate article) and finally calling clone() method on the object members in the overriden clone() method definition.
sample program :

package com.deepcopy;
/**
*
* @author thanooj
*
*/
class Person implements Cloneable {
// Lower-level object
private Car car;
private String name;

public Car getCar() {
return car;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Person(String s, String t) {
name = s;
car = new Car(t);
}
public Object clone() throws CloneNotSupportedException{
// Deep copy
Person p = (Person) super.clone();
p.car = (Car) p.car.clone();
return p;
}
}
class Car implements Cloneable{

private String name;

public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Car(String s) {
name = s;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class DeepCopyTest {

public static void main(String[] args) {
// Original Object - before Deep cloning
Person p = new Person("sreeRama", "Garuda");
System.out.println(p.getName()+" "+p.getCar().getName());
Person pClone = null;
try {
pClone = (Person) p.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println("Clone (before change): "+pClone.getName()+" "+pClone.getCar().getName());
pClone.setName("Indra");
pClone.getCar().setName("Iravath");
System.out.println("Clone (after change): "+pClone.getName()+" "+pClone.getCar().getName());
// Original Object - after Deep cloning
System.out.println(p.getName()+" "+p.getCar().getName());
}
}
// Output :
sreeRama Garuda
Clone (before change): sreeRama Garuda
Clone (after change): Indra Iravath
sreeRama Garuda

Sunday, June 26, 2011

MySQL import and export

Here are few MySQL Queries/commands that i regularly use for exporting and importing MySQL data. This is for my reference, but just thought this might be useful for newbies.
MySQL Table Data Export and Import

To export the just table data please use the following query
SELECT * INTO OUTFILE 'data.txt' FIELDS TERMINATED BY ',' FROM mytable;
To import the csv file into table execute the following SQL Query.
LOAD DATA INFILE 'data.txt' INTO TABLE mytable FIELDS TERMINATED BY ',';

Copy the contents of one database to another

First, create the new database
create database db2;
Then, from the command-line, do the following to copy the contents from db1 to db2.
$ mysqldump -u root --password=pass db1 | mysql -u root --password=pass db2

MySQL Dump

To export the MySQL database into a dump file, please execute the following command
$ mysqldump -u root --password=pass db1 > dbdump.sql

Create MySQL User

Creating MySQL user and granting access
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'myuser';
GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'myuser';

Tuesday, June 21, 2011

What is serialVersionUID?

Most people learn about serialVersionUID after they write their first serializable object (I know I did). You add ‘implements Serializable’ and in the next moment your IDE starts complaining… so what’s up?

Lets look at a simple example to see what meaning that variable has. In the example we will use the class SerializeMe shown below:

class SerializeMe implements Serializable {
private static final long serialVersionUID = 1L;

private int data;

public SerializeMe (int data) {
this.data = data;
}

public int getData() {
return data;
}
}

Field data represents some information stored in the class. Class implements the Serializable interface, so my IDE automatically offered me to declare the serialVersionUID field. Lets start with value 1 set there.

We will also need some class that will serialize and deserialize the SerializeMe class. Here it is:

public class UIDTester {
public static void main(String... strings) throws Exception {
File file = new File("out.ser");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);

SerializeMe serializeMe = new SerializeMe(1);
oos.writeObject(serializeMe);
oos.close();

FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);

SerializeMe dto = (SerializeMe) ois.readObject();
System.out.println("data : " + dto.getData());
ois.close();
}
}

This code will serialize an instance of class SerializeMe to a file and then deserialize it back. Now let’s run the main function! You should get output that says:
data : 1

It means that our object was properly serialized and deserialized. Note that the file “out.ser” was created on disk and it is still there even after the program finished. Let’s see if we can read that file once again, this time without creating it first. To do that, comment out lines from 4 to 9 in the UIDTester class:

public class UIDTester {
public static void main(String... strings) throws Exception {
File file = new File("out.ser");
//FileOutputStream fos = new FileOutputStream(file);
//ObjectOutputStream oos = new ObjectOutputStream(fos);

//SerializeMe serializeMe = new SerializeMe(1);
//oos.writeObject(serializeMe);
//oos.close();

FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);

SerializeMe dto = (SerializeMe) ois.readObject();
System.out.println("data : " + dto.getData());
ois.close();
}
}

This way, the main method starts right away with reading the file from the disk and deserializing data stored in it. As the file is exactly the same and our class didn’t changed either, we should get exactly the same output:

data : 1

Now, let’s see what happens, when we change the serialVersionUID value and try to deserialize once again our file. Change the line 2 in the class SerializeMe so that serialVersionUID contains now 2 instead of 1:

private static final long serialVersionUID = 2L;

Now let’s run again our program (just like one step before, with commented out lines writing the file). We should get an exception like this:

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
serialVersionUID = 1, local class serialVersionUID = 2

As you can see, this time the deserialization didn’t go well. ObjectInputStream complained about the serialVersionUID being changed. How does he know that it changed? If serialVersinUID is static, then it should not have been serialized in the first place, and there should be no information about the previous value 1 during the deserialization, right? Well, serialVersionUID is an exception to the rule that “static fields don’t get serialized”. ObjectOutputStream writes every time the value of serialVersionUID to the output stream. ObjectInputStream reads it back and if the value read from the stream does not agree with the serialVersionUID value in the current version of the class, then it throws the InvalidClassException. Moreover, if there is no serialVersionUID officially declared in the class to be serialized, compiler automatically adds it with a value generated based on the fields declared in the class.

So what is it for after all? Let’s suppose that there is some file storing a serialized object of some class A. The deserialization of that object does not necessarily have to occur exactly after serialization. It can occur after a few months or on a completely different JVM (i.e. sending an object through net using serialization). In both cases, there is a chance that the class declaration has changed between serialization and deserialization. It would be nice to have some kind of versioning system for every serializable class – and serialVersionUID does exactly that. It checks if the data read from the input stream is compatible with the current definition of the class.

If so, then why is it recommended to specify your own serialVersionUID ? It gives us simply more control. Default rules for generating serialVersionUID can be too strict in some cases. For example when the visibility of a field changes, the serialVersionUID changes too. Value generated automatically can differ between various Java implementations. There is a chance that some object serialized on one Java implementation will not deserialize on some other Java implementation, even if the class definition is exactly the same. Furthermore, sometimes you just want for some reason to forbid deserialization of old serialized objects, and in this case you just have to change the serialVersionUID.

Now that you know that specifying your own serialVersionUID is recommended, you might tend to write it once for every serializable class ( or have it generated by the IDE ) and forget about it. WRONG !!! If you write it once and don’t take care to update it when necessary, you loose all the merits of serialVersionUID. All your classes will get deserialized without exceptions even when using outdated data. What you should do is to change serialVersionUID (for example increase it by 1 or make your IDE generate automatically a new value) every time there is some change in the definition of data stored in the class. For example if you change data types, variable names or add new data – hence every time you want to have ‘backward incompatibility’ for deserialization.

Sunday, June 19, 2011

session tracking techniques in java

Here we do share session tracking techniques in java

What is a session?
seesion is a scope of accessing a client state in series of continuous request and response with in a browser window.

Why should a session be maintained?
When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.

When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.

Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.
Session tracking methods:

User authorization
Hidden fields
URL rewriting
Cookies
Session tracking API

The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization
Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields
<input name="”technology”" type="”hidden”" value="”servlet”" />
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.
3. URL Rewriting
Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456

and

encodeURL
String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary.

For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

Parameters:
url - the url to be encoded.
Returns:
the encoded URL if encoding is needed; the unchanged URL otherwise.

encodeRedirectURL
String encodeRedirectURL(String url)

Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separated from the encodeURL method.

All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

Parameters:
url - the url to be encoded.
Returns:
the encoded URL if encoding is needed; the unchanged URL otherwise.

When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

and

String contextPath = request.getContextPath();
String userURL = contextPath + "/default.jsp?name="+userName;
String encodedUrl = response.encodeURL(userURL);
String encodedRedirectURL = response.encodeRedirectURL(userURL);
------
4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie alogwith it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:

// creating a cookie
Cookie user = new Cookie("userName","Sreerama");
response.addCookie(user);
// retriving a cookie
Cookie [] userArray = request.getCookies();
for(Cookie user : userArray){
System.out.println(user.getName());
}


Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API
Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using session tracking api.

// create a session
HttpSession ses = request.getSession(true); // arg- true/false
ses.setAttribute("user",UserObj);
// retrieve a session
HttpSession ses = request.getSession();
User user = (User)ses.getAttribute("user");
it depends on the browser preferences. the servlet tries to set cookies but if they are disabled in browser it moves to session tracking stuff with urlencoding.
// cookies and url rewrite
request.isRequestedSessionIdFromCookie();
request.isRequestedSessionIdFromURL();

simple Session Tracker

Here we share, how to track a user login as session in a simple way.

Detailed usage of Comparable and Comparator

Here we do share about Detailed usage of Comparable and Comparator.

-first we do try to understand Detailed usage of Comparable.

// Employee.java

package com.comparable;

public class Employee implements Comparable, Serializable {

private int eNo;
private String eName;
private float eSal;

public Employee() {
super();
}

public Employee(int eNo, String eName, float eSal) {
super();
this.eNo = eNo;
this.eName = eName;
this.eSal = eSal;
}

@Override
public int hashCode() {
System.out.println("-hashCode()- : " + this.hashCode());
final int prime = 31;
int result = 1;
result = prime * result + ((eName == null) ? 0 : eName.hashCode());
result = prime * result + eNo;
result = prime * result + Float.floatToIntBits(eSal);
return result;
}

@Override
public boolean equals(Object obj) {
System.out.println("-equals(obj)-: " + obj.toString());
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (eName == null) {
if (other.eName != null)
return false;
} else if (!eName.equals(other.eName))
return false;
if (eNo != other.eNo)
return false;
if (Float.floatToIntBits(eSal) != Float.floatToIntBits(other.eSal))
return false;
return true;
}

public int geteNo() {
return eNo;
}

public String geteName() {
return eName;
}

public float geteSal() {
return eSal;
}

@Override
public int compareTo(Employee emp) {
int comp = 0;
if ((comp = this.geteName().compareTo(emp.geteName())) != 0) {
} else {
if ((comp = Float.floatToIntBits(this.geteSal())
- Float.floatToIntBits(emp.geteSal())) != 0) {
} else {
comp = this.geteNo() - emp.geteNo();
}
}
return comp;
}
}
//EmpComparable.java
package com.comparable;

/*
* To be able to use the Comparable interface, the class of the objects
* in the collection has to implement that interface.
* You might have for example a List of objects from a class
* that you don't control yourself - for example,
* a class that comes from some third-party library.
* You can't make that class implement Comparable easily
* (it would mean you'd have to change the source code of
* the third-party library, which is normally not a good idea).
* To be able to sort the List anyway, you can implement your own Comparator
* and pass that to for example
* Collections.sort(list, comparator);.
* Your Comparator object can be separate from the objects that are in the List.
*/
import java.util.ArrayList;
import java.util.Collections;


public class EmpComparable {

/**
* @param args
*/
public static void main(String[] args) {

ArrayList empList = EmpComparable.getEmployees();

EmpComparable.EmpListIterate(empList);

}

public static ArrayList getEmployees() {

ArrayList empList = new ArrayList();
empList.add(new Employee(1, "Sreerama", 50000.0f));
empList.add(new Employee(2, "Seetha", 45000.0f));
empList.add(new Employee(8, "Lakshmana", 40000.0f));
empList.add(new Employee(4, "Bharatha", 30000.0f));
empList.add(new Employee(5, "Sethrugna", 20000.0f));
empList.add(new Employee(7, "Hanuma", 10000.0f));
empList.add(new Employee(6, "Hanuma", 15000.0f));
empList.add(new Employee(3, "Lakshmana", 40000.0f));

/*
* perform the sorting on given object; NOTE - no return type.
* we cont perform reverse sorting by using comparable
*/
Collections.sort(empList);

return empList;
}

public static void EmpListIterate(ArrayList empList) {

System.out.println("EmpNo" + "\t\t" + "EmpName" + "\t\t\t" + "EmpSal");
System.out.println("-----" + "\t\t" + "-------" + "\t\t\t" + "------");
// no need of Iterator here, we just go for display employees.
for (Employee emp : empList) {
System.out.println(emp.geteNo() + "\t\t" + emp.geteName() + "\t\t"
+ emp.geteSal());
}


}

}
output:
-------

---------------------------------
-Second, we do try to understand Detailed usage of Comparator.

//Employee.java
package com.comparator;

public class Employee implements Serializable {

private int eNo;
private String eName;
private float eSal;


public Employee() {
super();
}

public Employee(int eNo, String eName, float eSal) {
super();
this.eNo = eNo;
this.eName = eName;
this.eSal = eSal;
}

@Override
public int hashCode() {
System.out.println("-hashCode()- : " + this.hashCode());
final int prime = 31;
int result = 1;
result = prime * result + ((eName == null) ? 0 : eName.hashCode());
result = prime * result + eNo;
result = prime * result + Float.floatToIntBits(eSal);
return result;
}

@Override
public boolean equals(Object obj) {
System.out.println("-equals(obj)-: " + obj.toString());
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (eName == null) {
if (other.eName != null)
return false;
} else if (!eName.equals(other.eName))
return false;
if (eNo != other.eNo)
return false;
if (Float.floatToIntBits(eSal) != Float.floatToIntBits(other.eSal))
return false;
return true;
}

public int geteNo() {
return eNo;
}

public String geteName() {
return eName;
}

public float geteSal() {
return eSal;
}
}
//EmpComparator.java
package com.comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.comparable.EmpComparable;
import com.comparable.Employee;

class EmpNameComparator implements Comparator {

@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.geteName().compareTo(emp2.geteName());
}
}
class EmpNoComparator implements Comparator {

@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.geteNo() &lt; emp2.geteNo() ? -1 : (emp1.geteNo() &lt; emp2
.geteNo()) ? 0 : 1;
}
}
class EmpSalComparator implements Comparator {

@Override
public int compare(Employee emp1, Employee emp2) {
return Float.floatToIntBits(emp1.geteSal()) &lt; Float.floatToIntBits(emp2
.geteSal()) ? -1
: (Float.floatToIntBits(emp1.geteSal()) &lt; Float
.floatToIntBits(emp2.geteSal())) ? 0 : 1;
}
}
public class EmpComparator {

public EmpComparator() {
// no code
}
public static Comparator CompareWith(String comp) {
System.out.println("-comp- " + comp);
Comparator compObj = null;
if (comp.equals("EmpName")) {
compObj = new EmpNameComparator();
} else if (comp.equals("EmpSal")) {
compObj = new EmpSalComparator();
} else {
compObj = new EmpNoComparator();
}
return compObj;
}
public static ArrayList showEmployees() {
ArrayList empList = new ArrayList();
empList.add(new Employee(1, "Sreerama", 50000.0f));
empList.add(new Employee(2, "Seetha", 45000.0f));
empList.add(new Employee(8, "Lakshmana", 40000.0f));
empList.add(new Employee(4, "Bharatha", 30000.0f));
empList.add(new Employee(5, "Sethrugna", 20000.0f));
empList.add(new Employee(7, "Hanuma", 10000.0f));
empList.add(new Employee(6, "Hanuma", 15000.0f));
empList.add(new Employee(3, "Lakshmana", 40000.0f));
// perform the sorting on given object; NOTE - no return type.
Collections.sort(empList, EmpComparator.CompareWith("EmpName"));
EmpComparable.EmpListIterate(empList);
Collections.sort(empList, EmpComparator.CompareWith("EmpSal"));
EmpComparable.EmpListIterate(empList);
Collections.sort(empList, EmpComparator.CompareWith("default"));
EmpComparable.EmpListIterate(empList);
//Reverse sort is also possible.
Collections.sort(empList, Collections.reverseOrder(EmpComparator.CompareWith("default")));
EmpComparable.EmpListIterate(empList);
return empList;
}
public static void EmpListIterate(ArrayList empList) {

System.out.println("EmpNo" + "\t\t" + "EmpName" + "\t\t\t" + "EmpSal");
System.out.println("-----" + "\t\t" + "-------" + "\t\t\t" + "------");
// no need of Iterator here, we just go for display employees.
for (Employee emp : empList) {
System.out.println(emp.geteNo() + "\t\t" + emp.geteName() + "\t\t"
+ emp.geteSal());
}
}
public static void main(String[] args) {
ArrayList empList = EmpComparator.showEmployees();

}
}

output:
------

// In reverse order by EmpNo as default sort.

Monday, April 18, 2011

Set session timeout in Weblogic

There are two ways user's HTTP session timeout can be set for your web application.
1. Web.xml
2. Weblogic.xml



More importantly the timeout value set in web.xml takes precedence over weblogic.xml. If you don't set any values in web.xml, weblogic.xml takes over. I think it is better to handle session timeout in web.xml itself since web.xml takes precedence over application server’s deployment descriptors.

Sunday, April 17, 2011

Parse CSV In Java

package com.csv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;

public class ParseCSVInJava {

/**
* @param args
*/
public static void main(String[] args) {

try
{
//csv file containing data
String strFile = "D:\\WS12042011\\Parsing_XMLDOM_CSV_Text_In_Java\\src\\com\\csv\\Employee.csv";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader(strFile));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//read comma separated file line by line
while( (strLine = br.readLine()) != null)
{
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens())
{
//display csv values
tokenNumber++;
System.out.println("Line:" + lineNumber +", Token:" + tokenNumber+ ", Value = "+ st.nextToken());
}
//reset token number
tokenNumber = 0;
}
}
catch(Exception e)
{
System.out.println("Exception while reading csv file: " + e);
}
}
}
----------
out put
----------
Line:1, Token:1, Value = one:1
Line:1, Token:2, Value = two:2
Line:1, Token:3, Value = three:3
Line:1, Token:4, Value = four:4
Line:1, Token:5, Value = five:5
Line:1, Token:6, Value = six:6
Line:2, Token:1, Value = parsing
Line:2, Token:2, Value = comma
Line:2, Token:3, Value = separated
Line:2, Token:4, Value = file
Line:2, Token:5, Value = in
Line:2, Token:6, Value = java

Friday, March 25, 2011

Will your resume get you the interview call?

1. Should your resume have a career goal/ objective statement? A resume that is worthy of representing you, should clearly state your career objective. A career objective is an indirect way of advertising what all you would bring to the company/ role. It must display a ‘giving’ attitude and not a ‘taking’ attitude.

2. What sequence should your story follow?
Be it work experience or education, always tell the story from the current/ most recent to the first. NEVER write it the other way round.

3. Does your resume need to mention your marital status?
The new age resume does not require you to mention your marital status. However, if the job advertisement clearly states this as a requirement, do fulfil it. Quick Take

* Include a sharp Career Goal

* Choose the pdf format with discretion

* Fonts: Use Times New Roman, Calibri or Verdana

* Run a spell check

* Tweak to suit position and company of a potential employer

* Your latest work stint must appear first

* save the doc/pdf with meaning full name like : thanooj_j2ee_2.7yrs_25032011.

* writing a cover letter
Dear _______, I am applying for the role of ___________________ at your esteemed organisation _____________________.

4. How should you treat references?

Unless you have been specifically asked to provide references, it is acceptable to state in your covering letter/ email that you will provide references on request. Usually, two references are sufficient. Try to provide references from the two most recent phases of your career.
It is a good idea to inform the referees that you are giving out their contact information. It will also help if they know what kind of jobs you are applying for.

5. Should you send the resume as an MS Word document or a PDF?
Some organisations ask you to upload your resume. Usually they ask for an MS Word document. If you are mailing across your resume, you could choose either format.
A word of caution – do not get carried away if you decide to make it a PDF. Keep it simple – leave out visual histrionics. And whatever software you choose – send the resume in the most commonly used version.
The biggest advantage of using a pdf format is that it preserves the formatting irrespective of the version of the Acrobat Reader version or user settings.

6. Should you incorporate links in the resume?
If you are an engineer who writes a technical blog, go ahead and incorporate the link in your resume. If you are a website developer, the links to the pages created by you would certainly help.

Tuesday, March 22, 2011

Struts 1.x – Multiple configuration files.



1. Single module
A single module support multiple Struts configuration files.



In the web.xml, you can separate multiple Struts configure file by a comma “,“.

Test it:
1.http://localhost:8080/StrutsExample/Page1.do
It will display the page1.jsp
2.http://localhost:8080/StrutsExample/common/Welcome.do
It will display the page2.jsp
Both Struts configuration are loaded property.
--------------------------------------------------------
2. Multiple modules
Multiple modules, each has own Struts configuration files.



Both “struts-config-admin.xml” and “struts-config-common.xml” files contains the same settings, Struts is able to differential it via the “config” parameter value in web.xml.

struts-config-admin.xml, struts-config-common.xml


web.xml



Test it
The “config/admin” will match to this URL pattern – http://localhost:8080/StrutsExample/admin/
The “config/common” will match to this URL pattern – http://localhost:8080/StrutsExample/common/

1.http://localhost:8080/StrutsExample/admin/Welcome.do
It will display the admin/welcome.jsp
2.http://localhost:8080/StrutsExample/common/Welcome.do
It will display the common/welcome.jsp
Each modules has own Struts configuration file.

Thursday, February 3, 2011

Tomcat manager console

we do discuss about tomcat manager console login :

we do for tomcat server installation, while installing it, i will ask us to give userName/password, though that we can access tomcat manager console.

where as, when we go for tomcat.zip, it won't ask for manager userName/pwd or so.
after unzipping tomcat.zip.
we need to set
JAVA_HOME=%{where our JAVA JDK s/w installed(reside)}%
CATALINA_HOME=%{where our Tomcat s/w unzip/installed(reside)}%
done.
now, when we try to access manager's console, then we need to edit %{CATALINA_HOME}%\conf\tomcat-users.xml

edit tomcat-users.xml :

if you already started tomcat server, shutdown server before edit



and save it.done.

now, run startup.bat
goto http://localhost:8080/
click on 'Tomcat Manager'
it will ask for userName/pwd, provide your specific details.

done.

Monday, January 17, 2011

Unit testing with JUnit and EasyMock

What is a unit test?For the case of this tutorial, we'll define a unit test as a test of a single isolated component in a repeatable way. Let's go thru that one section at a time to get a clearer idea of what goes into a unit test.
"a test". This means to verify something is correct. In order for us to have a valid unit test, we need to actually validate that after a start condition A, an end condition B exists. "...a single isolated component...". This is what separates a unit test from other types of tests. In order for it to be a unit test, it must test something in isolation, aka without dependencies. The reason for this is that we are testing the component itself and not it's interaction with other components (that is an integration test). Finally, although most definitions don't include this piece, "...in a repeatable way" is a very important piece of the definition. It's one thing to run a test that passes. It's quite different to have something you can run in a repeatable manor at any point to see if changes you made effected how the component behaves. For example, if you choose to do some refactoring to improve performance, can you rerun your unit test to verify that you didn't change the behavior of the component.
Setup
I will be using Eclipse 3.3 Europa to do this tutorial. To begin, create a new java project and call it JUnitTutorial. Right click on your new project and select New --> Folder. Name it lib and click Finish. Usually you don't want to package your test code with your regular code, so let's make an additional source directory, test. To do that, right click on your new project and select Properties. Select Java Build Path from the available options. In the Java Build Path window, click Add Folder. From the Add Folder dialog, select Create New Folder, name it test and click Finish. Next we need to add JUnit to our build path. Since it comes with Eclipse, all we need to do is to go to the Libraries tab, click the button Add Library, select JUnit and click Next. Select JUnit 4 and click Finish. Click ok to exit the Preferences window. We will also need to download and add the EasyMock jar files to our project. You can find the jars here. Once you download the zip file (we are using version 2.3 for this tutorial), extract the easymock.jar file and place it in the lib folder you created earlier. In Eclipse, right click on your project and select Properties. On the menu to the left, click Java Build Path and select the Libraries tab. Click the button Add Jar on the right. In the window that pops up, add the easymock.jar and click Ok. Click Ok to close the Properties window. You should now be ready to start your development.
The requirementsIn test driven design, we develop the unit test before the functionality. We write a test that verifies that the class should do X after our call. We prove that the test fails, we then create the component to make the test pass. In this case, we are going to create a service with a method that authenticates a user. Below is a class diagram of the scenario.


The interfacesWe will start our coding by defining two interfaces, LoginService and UserDAO We will implement LoginService, however since in this tutorial UserDAO will be mocked, we won't bother implementing it right now. For LoginService, we have a single method that takes a String userName and String password and returns a boolean (true if the user was found, false if it was not). The interface looks like this:

/**
* Provides authenticated related processing.
*/
public interface LoginService {

/**
* Handles a request to login. Passwords are stored as an MD5 Hash in
* this system. The login service creates a hash based on the paramters
* received and looks up the user. If a user with the same userName and
* password hash are found, true is returned, else false is returned.
*
* @parameter userName
* @parameter password
* @return boolean
*/
boolean login(String userName, String password);
}
The UserDAO interface will look very similar to the LoginService. It will have a single method that takes a userName and hash. The hash is an MD5 hashed version of the password, provided by the above service.

/**
* Provides database access for login related functions
*/
public interface UserDAO {

/**
* Loads a User object for the record that
* is returned with the same userName and password.
*
* @parameter userName
* @parameter password
* @return User
*/
User loadByUsernameAndPassword(String userName, String password);
}
The test caseBefore we begin development, we will develop our test. Tests are structured by grouping methods that perform a test together in a test case. A test case is a class that extends junit.framework.TestCase. So in this case, we will begin by developing the test case for LoginService. To start, in your test directory, create a new class named LoginServiceTest and make it extend junit.framework.TestCase.

The lifecycle of a test execution consists of three main methods:
public void setUp()setUp is executed before each of the test. It is used to perform any setup required before the execution of your test. Your implementation will override the default empty implementation in TestCase.
public void testSomething()testSomething is the actual test method. You may have many of these within a single test case. Each one will be executed by your test runner and all errors will be reported at the end.
public void tearDown()tearDown is executed after each test method. It is used to perform any cleanup required after your tests.

So to begin flushing out our test case, we'll start with the setUp method. In this method, we'll instantiate an instance of the service to be tested. We'll also create our first mock object, UserDAO. You can see the source of our test below.

import junit.framework.TestCase;
import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.easymock.EasyMock.eq;
/**
* Test case for LoginService.
*/
public class LoginServiceTest extends TestCase{

private LoginServiceImpl service;
private UserDAO mockDao;

/**
* setUp overrides the default, empty implementation provided by
* JUnit's TestCase. We will use it to instantiate our required
* objects so that we get a clean copy for each test.
*/
@Override
public void setUp() {
service = new LoginServiceImpl();
mockDao = createStrictMock(UserDAO.class);
service.setUserDAO(mockDao);
}
}
EasyMock works by implementing the proxy pattern. When you create a mock object, it creates a proxy object that takes the place of the real object. The proxy object gets it's definition from the interface you pass when creating the mock. We will define what methods are called and their returns from within our test method itself.

When creating a mock object, there are two types, a mock and a strict mock. In either case, our test will tell the mock object what method calls to expect and what to return when they occur. A basic mock will not care about the order of the execution of the methods. A strict mock, on the other hand, is order specific. Your test will fail if the methods are executed out of order on a strict mock. In this example, we will be using a strict mock.

The next step is to create our actual test method (for reference, we will not be implementing a tearDown method for this test case, it won't be needed in this example). In our test method, we want to test the following scenario:



Even with the very basic method we want to test above, there are still a number of different scenarios that require tests. We will start with the "rosy" scenario, passing in two values and getting a user object back. Below is the source of what will be our new test method.

...
/**
* This method will test the "rosy" scenario of passing a valid
* username and password and retrieveing the user. Once the user
* is returned to the service, the service will return true to
* the caller.
*/
public void testRosyScenario() {
User results = new User();
String userName = "testUserName";
String password = "testPassword";
String passwordHash =
"�Ӣ & I7���Ni=.";
expect(mockDao.loadByUsernameAndPassword(eq(userName), eq(passwordHash)))
.andReturn(results);

replay(mockDao);
assertTrue(service.login(userName, password));
verify(mockDao);
}
...
So let's go thru the code above. First, we create the expected result of our DAO call, results. In this case, our method will just check to see if an object was returned, so we don't need to populate our user object with anything, we just need an empty instance. Next we declare the values we will be passing into our service call. The password hash may catch you off guard. It's considered unsafe to store passwords as plain text so our service will generate an MD5 hash of the password and that value is the value that we will pass to our DAO.

The next line is a very important line in our test that alot happens, so let's walk thru it step by step:

expect(mockDao.loadByUsernameAndPassword()This is a call to the static method EasyMock.expect. It tells your mock object to expect the method loadByUsernameAndPassword to be called.
eq(userName), eq(passwordHash)
This code isn't always needed. When EasyMock compares the values passed to the method call, it does and == comparison. Because we are going to create the MD5 hash within our method, an == check will fail, so we have to use one of EasyMock's comparators instead. The eq comparator in this case will compare the contents of the string using it's .equals method. If we were not doing the MD5 hash, this line would be expect(mockDao.loadByUsernameAndPassword(userName, password).andReturn(results);
.andReturn(results);This tells our mock object what to return after this method is called.

The final three lines are the ones that do the testing work. replay(mockDao); tells EasyMock "We're done declaring our expectations. It's now time to run what we told you". assertTrue(service.login(userName, password)); does two things: executes the code to be tested and tests that the result is true. If it is false, the test will fail. Finally, verify(mockDao); tells EasyMock to validate that all of the expected method calls were executed and in the correct order.

So that's it for the test. Now all we have to do is write the code to make it pass. You can find that below.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class LoginServiceImpl implements LoginService {

private UserDAO userDao;

public void setUserDAO(UserDAO userDao) {
this.userDao = userDao;
}

@Override
public boolean login(String userName, String password) {
boolean valid = false;
try {
String passwordHash = null;
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes());
passwordHash = new String(md5.digest());

User results =
userDao.loadByUsernameAndPassword(userName, passwordHash);
if(results != null) {
valid = true;
}
} catch (NoSuchAlgorithmException ignore) {}

return valid;
}
}
ConclusionSo that is it. I hope this gives you a more in depth view into JUnit and EasyMock. Unit testing is something that once you get used to it, makes you code better, provides you with a safety net for future refactoring and protects you from being burned by API changes. I strongly encourage that you give it a try. Until next time.