Pages

Tuesday, July 24, 2012

hashCode() method in java

public int hashCode() : Returns a hash code value for the object.

- As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.
- If two object are equal a/c to the equals() method, then calling hashCode() on those object must produce the same hash value.
- It's not mandatory that if hash values of two object are equal, then the two objects should be equal.

It's generally said,

Adapter design pattern in Java with example


This is a structural design pattern. A Wrapper class, i.e., Adatper class is used to convert requests from it to Adaptee class.

The Adapter pattern converts the interface of a class into another interface the client expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Two forms of Adapter pattern:
1) class adapter (uses inheritace)
2) object adapter (uses composition)

object adapter 
---------------------
object adapter design pattern



 
A simple example

Thursday, July 19, 2012

Comparator and Comparable example in Java

java.lang.Comparable
--------------------------
int compareTo(Object o) : This method compares 'this' object with 'o' object

if the int value is
positive - 'this' object is greater than 'o' object
zero - 'this' object is equals with 'o' object
negative - 'this' object is less than 'o' object

java.util.Comparator
-----------------------------
int compare(Object o1,Object o2) : This method compares o1 and o2 objects.

if the int values is
positive - o1 is greater than o2
zero - o1 equals o2
negative - o1 is less than o2

A simple example

Tuesday, July 17, 2012

Sandbox model in Java

The Original Sandbox Model 
The original security model provided by the Java platform is known as the sandbox model, which existed in order to provide a very restricted environment in which to run untrusted code obtained from the open network. The essence of the sandbox model is that local code is trusted to have full access to vital system resources (such as the file system) while downloaded remote code (an applet) is not trusted and can access only the limited resources provided inside the sandbox.

Eclipse shortcut keys

Ctrl + D - Delete Row

Alt + Up/Down Arrow - Move the row up/down

Alt + Left/Right Arrow - Switch b/w files you last edited

Ctrl + Shift + O - All the required imports will be done,Unused imports will vanish

Ctrl + 1 - while implementing an interface we'll get error,because inherited methods not  yet implemented.This key acts as quick fix.

Ctrl + Shift + T - Open Type.Search the classes

Wednesday, July 11, 2012

clone() method in Java

We'll generally create clone, when we want to create local copy of the object and don't want to modify the original object.
Use the clone() method cautiously, or else you can also create a copy constructor alternative to the clone().
This is a protected method in java.lang.Object class.
protected Object clone() CloneNotSupportedException : It creates and returns a copy of this object.

By default shallow copy is applied. If we want extra logic to be impemented then we need to opt for deep copy.
Shallow copy : Just call the super.clone()
Deep copy : We need to implement ourselves.

A simple example

Tuesday, July 10, 2012

toString() method in Java

This method returns the string representation of the object.
If we try to print the object directly without overriding the toString() method for that calss, then we'll get the output  in the format.

ClassName@HexDecRepresentationOfObject or
getClass().getName() + '@' + Integer.toHexString(hashCode())

By default ArrayList overrides the toString method, so if we print the object of ArrayList it'll nicely print the added objects.

A simple example

Sunday, July 1, 2012

ServletContextListener in Java Servlets


ServletContextListener
--------------------------------
We can't very well stuff 'object' into an XML DD. We can do this by Listeners if, we want objects those required by any resource of app.
If we want to run some code before the rest of the app service a client, then we have context init parameters that we can get and use.

Methods in ServletContextListener
-------------------------------------------------
contextInitialized(ServletContextEvent)
contextDestroyed(ServletContextEvent)

A simple example

Saturday, June 30, 2012

ServletConfig and ServletContext in Java Servlets

ServletConfig
***************
ServletConfig encapsulates servlet configuration,that is used by the servlet container,used to pass information to servlet during initialix(z)ation.
ServletConfig is one per servlet.

Methods in <<ServletConfig>> interface:
i)          String getInitParameter(String)
ii)          Enumeration getInitParameterNames()
iii)         ServletContext getServletContext()
iv)         String getServletName() 

ServletContext
*****************
ServletContext is one per web application.

Methods in <<ServletContext>> interface:
i)          Object getAttribute(String)
ii)          String getInitParameter(String)
iii)         String getServletContextName()
iv)         void setAttribute(String,Object)
v)         void removeAttribute(String)
vi)         RequestDispatcher getRequestDispatcher(String path)
and many more...

A simple example

Wednesday, June 20, 2012

JSP tutorial (Java Server Pages)


JavaServer Pages (JSP) technology provides a simplified, fast way to create dynamic web content. JSP technology enables rapid development of web-based applications that are server- and platform-independent.

Steps in processong of Jsp
i)Jsp is translated to servlet(.java file)
ii)Compiled to .class file
iii)Loaded and initailized as servlet object


Jsp Elements
------------
i)Scriptlet(<%  %>)
    Eg:<% out.println("Hello Jsp");%>

Monday, June 18, 2012

Custom tag development

Tag handler : A Tag handler as opposed to a tag file, is simply Java class that does the work of the tag.

These are come in two ways.
i)Classic (pre. versions of JSP)
ii)Simple (JSP 2.0)

Making a Simple Tag handler : 
i)Write a class that extends SimpleTagSupport
ii)Override the doTag() method
iii)Create a TLD for the tag
iv)Deploy the tag handler and TLD
v)Write a JSP that uses the tag

A Simple tag example:

Tuesday, June 5, 2012

Spring Hibernate sample application

Spring Hibernate Integration Login Example using MySQL database and Tomcat Web Server.
A short description of how Spring MVC works (source : http://www.javacodegeeks.com)
When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The “DispatcherServlet” first receives the request
  • The “DispatcherServlet” consults the “HandlerMapping” and invokes the "Controller" associated with the request
  • The "Controller" process the request by calling the appropriate service methods and returns a “ModeAndView” object to the “DispatcherServlet”. The “ModeAndView” object contains the model data and the view name
  • The “DispatcherServlet” sends the view name to a “ViewResolver” to find the actual “View” to invoke
  • The “DispatcherServlet” passes the model object to the “View” to render the result
  • The “View” with the help of the model data renders the result and return it back to the user 
Eg : Employee Login:

Monday, June 4, 2012

Java Spring sample application

Spring tutorial example

The Spring Framework consists of features organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),Instrumentation, and Test.

-The Core Container consists of the Core, Beans, Context, and Expression Language modules.
-The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.
-The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.
-Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming.
-The Test module supports the testing of Spring components with JUnit or TestNG.

A simple example in spring (3.x)
************************

Sunday, June 3, 2012

MySQL data Encryption and Decryption using AES_ENCRYPT and AES_DECRYPT

Encryption and Decryption using AES_ENCRYPT and AES_DECRYPT

First create a table called test_encdec :

mysql> create table test_encdec(

 -> name varchar(30),

 -> password varbinary(150)

 -> );

Query OK, 0 rows affected (0.14 sec)

mysql> desc test_encdec;

+----------+----------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+----------+----------------+------+-----+---------+-------+

| name | varchar(30) | YES | | NULL | |

| password | varbinary(150) | YES | | NULL | |

+----------+----------------+------+-----+---------+-------+

2 rows in set (0.00 sec)
 mysql> insert into  test_encdec values('S L N V Praveen',aes_encrypt('praveen','
myname'));
Query OK, 1 row affected (0.01 sec)

mysql> select * from  test_encdec;
+-----------------+------------------+
| name            | password         |
+-----------------+------------------+
| S L N V Praveen | 8#sTyn ]7?รป¬+W¬2 |
+-----------------+------------------+
1 row in set (0.02 sec)

mysql> select name,aes_decrypt(password,'myname') from  test_encdec;
+-----------------+--------------------------------+
| name            | aes_decrypt(password,'myname')     |
+-----------------+--------------------------------+
| S L N V Praveen | praveen                                   |
+-----------------+--------------------------------+
1 row in set (0.00 sec)

mysql> select aes_decrypt(password,'myname') from  test_encdec;
+--------------------------------+
| aes_decrypt(password,'myname') |
+--------------------------------+
| praveen                        |
+--------------------------------+
1 row in set (0.00 sec)

Monday, March 5, 2012

Finding first/last day of the previous month using Calendar class in Java

Calendar is an abstract base class and implements Serializable and Cloneable interfaces.

Calendar provides 'getInstance' class method, returns Calendar object whose time fields have been initialized with the current date and time.
Calendar presentTime = Calendar.getInstance();

To find the last day/first day of the month
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class FindHistDate{ public static void getLastMonthLastDate() { 

 SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); 
 Calendar calendar = Calendar.getInstance();
 calendar.add(Calendar.MONTH, -1); 
 int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
 calendar.set(Calendar.DAY_OF_MONTH, max);
 Date pme = calendar.getTime();
 System.out.println(sdf.format(pme));

 int min = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
 calendar.set(Calendar.DAY_OF_MONTH, min);
 Date pms = calendar.getTime();
 System.out.println(pms);
}
 public static void main(String[] args) {
 FindHistDate.getLastMonthLastDate();
 }
}
o/p:
29-Feb-2012
Wed Feb 01 11:24:27 IST 2012

Monday, February 27, 2012

Convert Date to String and String to Date in Java

It's most obvious scenario where you need to convert Date to String and vice versa.

Example : Date to String
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateToString { 
 public static void main(String[] args) {  
  Date d = new Date();
  DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
  String str_dt = df.format(d);
  System.out.println("Date : "+str_dt);
 }
}
o/p :
Date : 27-Feb-2012

Example : String to Date

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate {
 public static void main(String[] args) throws ParseException {
  String d = "27-Jan-2012";
  SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
  Date date = sdf.parse(d);
  System.out.println("Date : "+date);  
 }
}

o/p :
Date : Fri Jan 27 00:00:00 IST 2012