Tuesday, June 12, 2012

method signature for the validate method in the ActoinForm Extended child class

public ActionErrors validate(ActionMapping map , HttpServletRequest) {

ActoinErrors errors = new ActionErrors();
----
---
---
return errors
}

execute method signature in the Struts1.x , Action class child class

1 . execute method is public
so

 public execute(){
}

2. it should return ActionForward instance 
so

public ActionForward execute(){
}

3. it must have ActionMapping , ActionForm, HttpServletRequest  and HttpServletResponse arguments
so

public ActionForward execute(ActionMapping map, ActionForm form , HttpServletRequest req, HttpServletResponse) throw Exception{
-----
-----
------

return map.findForward("SUCESS");

}

Monday, June 11, 2012

how to make a each object for each thread using the ThreadLocal


package com.yagapp.phaseone;

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

public class DateFormatTest {

// anonymous inner class. Each thread will have its own copy
private final static ThreadLocal<SimpleDateFormat> shortDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("dd/MM/yyyy");
}
};

public Date convert(String strDate) throws ParseException {

// get the SimpleDateFormat instance for this thread and parse the date
// string
Date d = shortDateFormat.get().parse(strDate);
return d;
}

}

Sunday, June 10, 2012

why the code after final not executes in this case


package com.yagapp.phaseone;


public class Testing2 {


/**
* @param args
*/
public static void main(String[] args) {
int y=0;
try{
int x =2/y;
}
catch(RuntimeException e)
{
System.out.println(1);
int z=2/y;

}
catch(Exception e){
System.out.println(2);
int z=2/y;
}
finally{
System.out.println(3);
}
System.out.println(4);
}


}


in this our output will give the result of 1 and 3 only
you won't see the result 4 
why ?
here is the reason

see in the code in the red color will throw the exception , but for this exception  code their is no handler provided for this exception  in this class , so on reaching the finally code and executing the code inside the finally code JVM calls the , ThreadGroup class methode  

private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    } ,
 so u won't see the result 4 


Friday, June 8, 2012

how many types of cache modes are available for the hibernate cache

we have five types hibernate cacheModes

1 . GET in this mode only session can able to read from the cache, it won't  write the items to the cache,

2. IGNORE
      The session will never interact with the cache, except to invalidate cache items when updates occur
3. NORMAL
          The session may read items from the cache, and add items to the cache
4. PUT
     The session will never read items from the cache, but will add items to the cache as it reads them from the database.

5 REFRESH 
          The session will never read items from the cache, but will add items to the cache as it reads them from the database.

Convert List into Array


package com.yagapp.phaseone;


import java.util.ArrayList;
import java.util.List;


public class ListTOArray {


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

List<String> list = new ArrayList<String>();
 
list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");
 
String [] countries = list.toArray(new String[list.size()]);

System.out.println(countries);

}


}

Simple example for , Iterate method in the Hibernate Query Interface


package com.criteria.example;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;




@Entity
public class Room {

private int id;
private String name;

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}


package com.criteria.example;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestClient {

/**
* @param args
*/
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Room.class);
config.configure(); // reads the *.cfg.xml file and understands the what is db and etc..
//new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();
/*session.beginTransaction();
Room r = new Room();
//ramesh.setEmpId(8634);
r.setName("RameS");
session.save(r);
session.getTransaction().commit();
*/
session.beginTransaction();
Query q = session.createQuery("from Room");
Iterator<Room> itr = (Iterator<Room>)q.iterate();
for(;itr.hasNext();){
System.out.println(itr.next().getName());
}
session.getTransaction().commit();
}

}


this will return the Iterator object 

Monday, June 4, 2012

how to invoke private methods of a class, from outside of that class


package com.yagapp.phaseone;


public class Target {


private void Prin()
{
System.out.println("this is private");
}

private static void prn(){
System.out.println("this is static private");
}
}

***************************************************
package com.yagapp.phaseone;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


import java.lang.reflect.Modifier;


public class PrivateAccess {

/**
* @param args
*/
public static void main(String[] args) {
Class c = Target.class;
Method[] methodes = c.getDeclaredMethods();
for(Method m : methodes)
{
String methodename = m.getName();
m.setAccessible(true);
if(Modifier.isPrivate(m.getModifiers()))
{
if(Modifier.isStatic(m.getModifiers()))
{
try {
m.invoke(c, new Object[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
m.invoke(new Target(), new Object[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

}

}

What is failrOver in clustered environment

consider you deploy ur cluster aware application on the clustered environment
and server1 in this clustered environment got a request in the mid of this request processing , server 1 fails or crashed in this case , request which was in mid routed to another server ,say server 2 , along with its state , this is called failOver, 


here in this state transfer uses the serialization concept , so u can understand , how important it is 

how to set transaction age in the EJB

in the server specific configuration xml file

like

weblogic-ejb-jar.xml

check this structure



<transaction-descriptor>
      <trans-timeout-seconds>0</trans-timeout-seconds>
    </transaction-descriptor>




Sunday, June 3, 2012

Hibernate Object phases

Merge

In session, Hibernate guarantees no two Persistent objects represent the same row.  Again, this guarantee no 
longer holds with Detatched objects. In fact, this problem can create very unwanted consequences. Explore 
the code below.


Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BallPlayer p1 = (BallPlayer)session.get(BallPlayer.class, 1L);
transaction.commit();
session.close();
//p1 is now detached.
session = sessionFactory.openSession();
transaction = session.beginTransaction();
BallPlayer p2 = (BallPlayer)session.get(BallPlayer.class, 1L);
//Oops!  p2 represents the same persistent row as p1.
//When an attempt to reattach p1 occurs, an exception is thrown
session.update(p1);
transaction.commit();
session.close();


This code throws an exception when an attempt to reattach the Detached object at p1 is made.

Exception in thread "main" org.hibernate.NonUniqueObjectException: a  
different object with the same identifier value was already associated
with the session: [com.intertech.domain.BallPlayer#1]
        at
org.hibernate.engine.StatefulPersistenceContext.checkUniqueness
(StatefulPersistenceContext.java:613)
...


This is because Hibernate is trying to reinforce the guarantee that only a single instance of a Persistent object 
exist in memory.

The merge operation, helps to deal with this situation.


Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BallPlayer p1 = (BallPlayer)session.get(BallPlayer.class, 1L);
transaction.commit();
session.close();
//p1 is now detached.
session = sessionFactory.openSession();
transaction = session.beginTransaction();
BallPlayer p2 = (BallPlayer)session.get(BallPlayer.class, 1L);
BallPlayer p3 = (BallPlayer) session.merge(p1);
if (p2 == p3) {
  System.out.println("They're equal");
}
transaction.commit();
session.close();

The merge() method is a little complex and works differently depending on what is in/out of the persistence 
context. Hibernate will first check whether a Persistent instance of that type already exists in the persistent 
context. It uses the object identifiers to check on this existence. If another instance exists, it copies the state 
of the Detached object (p1 above) into the existing Persistence object (p2 above). If no other instance exists, 
Hibernate just reattaches the Detached object.

In the example above, p2==p3 and one Persistent object exists.  In the example below, two Persistent objects 
now exist and p2!=p3


Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BallPlayer p1 = (BallPlayer)session.get(BallPlayer.class, 3L);
transaction.commit();
session.close();
//p1 is now detached.
session = sessionFactory.openSession();
transaction = session.beginTransaction();
BallPlayer p2 = (BallPlayer)session.get(BallPlayer.class, 1L);
BallPlayer p3 = (BallPlayer) session.merge(p1);
if (p2 == p3) {
  System.out.println("They're equal");
}
System.out.println(p2);
System.out.println(p3);
transaction.commit();
session.close();



Simple Example for Named Query in Hibernate

package com.yagapps.example9;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;


/*Remember here the Query from Boy must have the same as Entity class ,Boy*/

@NamedQueries( {@NamedQuery(name="findBoy" ,query="from Boy")}  )
@Entity
public class Boy {                                                               
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

This class is Entity class

and now below the TestClient


package com.yagapps.example9;



import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestClient {

/**
* @param args
*/
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Boy.class);
config.configure();
new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session  session = factory.openSession();
session.beginTransaction();
Boy b = new Boy();
b.setId("A201");
b.setName("ramesh");
session.save(b);
session.getTransaction().commit();
session.beginTransaction();
Query query = session.getNamedQuery("findBoy");
List<Boy>  l = query.list();
for(Boy b1 : l)
System.out.println(b1.getId());
session.getTransaction().commit();
}

}

Ask below questions to decide whether Rest or SOAP based webswervice


  • Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)
  • Do we need to support multiple data formats?
  • Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
  • Is the call synchronous or  asynchronous?
  • Is the call stateful or stateless? (REST is suited for statless CRUD operations)
  • What level of security is required? (SOAP WS has better support for security)
  • What level of transaction support is required? (SOAP WS has better support for transaction management)
  • Do we have limited band width? (SOAP is more verbose)
  • What’s best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)

Saturday, June 2, 2012

excellent using of static final variables

spot the difference between below codes, which one is good and why

code # 1





public class StaticExample {


/**
* @param args
*/

public static final String name;

static{
String nam = "sai";

name =nam;
}




public static void main(String[] args) {
System.out.println(name);


}




}


Code # 2


public class StaticExample {

/**
* @param args
*/
public static final String name;
static{
name ="sai";
}
public static void main(String[] args) {
System.out.println(name);

}

}

What is Diamond operator in java 7 , and what is the use of this , explanation with the simple example

Every good programmer likes to write a concise but effective and optimized code. Type Inference is a way introduced in JDK 7 which will surely give you benefits of less typing. Its been a long time that you have using the java code in following manner.

But have you ever thought of code duplication while initializing the specific implementation of Collections? Why there is a need to write the parameters two times during an intialization?




1List<string> names = new ArrayList<string>();
2Map<string, Object> objectMap = new HashMap<string, Object>(); 
Now most of you would be thinking of initializing as a raw types as you had been doing in previous JDK version.
Something like this. 
1List<string> names = new ArrayList();
2Map<string, object=""> objectMap = new HashMap();

So whats new in JDK 7? What benefits you will have from the new feature? 
So first we need to understand the difference between raw type and generic type intialization. 

A statements like this ensures that the implementation will contain the same parameter as specified during initialization. 
1List<string> names = new ArrayList<string>();

In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type: 
1Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning

Diamond Operator
  
Okay Now I will introduce the new feature of JDK 7. 
So we have something called Diamond operator in JDK 7 which reduces your extra typing while initialization. 

Syntax: 
1List<string> names = new ArrayList<>();

So it not only reduces your code but also ensures the type checking. 
Here is a more clear example explaining the benefits of type inference. 

Advanced Example: 
01class Demo {
02void printStudentNames(List<string> names) {
03for(String name:names) {
04System.out.println("String name:"+name);
05}
06}
07 
08public static void main(String[] args) {
09Demo demo = new Demo();
10demo.printStudentNames(new ArrayList<>());   // It saved typing here in a method call too.
11List<string> names = new ArrayList<>();
12printStudentNames(names);
13List<string> copyOfNames = new ArrayList<>(names);  // It saved typing here in a copy contructor invocation too.
14}
15}

Now what are its limitations? 
It won't work in the case you use wildcards. 

Something like this 
1Class Tree<t> {
2 
3public void demoFunction(List<t> objList) {
4List<t> copyOfNames = new ArrayList<t>(objList);   //This is not gonna work.
5}
6}

In the above case the arguments passed in the copy constructor should be Collection<? extends T> 
So it wont accept the above inference type.