Wednesday, December 19, 2012

What is ACID , in simple words


A stands for Atomicity, Atom is considered to be smallest particle which can not be broken into further
pieces.database transaction has to be atomic means either all steps of transaction completes or none of
them.
C stands for Consistency, transaction must leave database in consistent state even if it succeed or
rollback.
I is for Isolation
Two database transactions happening at same time should not affect each other and has consistent
view of database. This is achieved by using isolation levels in database.
D stands for Durability
Data has to be persisted successfully in database once transaction completed successfully and it has to
be saved from power outage or other threats. This is achieved by saving data related to transaction in
more than one places along with database.

Monday, October 22, 2012

how to return from the method when a timeout has occured

usecase : when we have a method abc() , and caller of this method will wait for 10 min for the resposne from this method, once the time has expired , then caller won't wait for the method response and return from the method.

solution : this can implemented as follows


example :




import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimeOutTesting {

public static void main(String[] args){

ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Object> task = new Callable<Object>() {
  public Object call() {
     return gettheCOntext();
  }
};
Future<Object> future = executor.submit(task);
try {
  Object result = future.get(0, TimeUnit.MILLISECONDS);
 
  System.out.println("hi how are you");
  System.out.println(result.toString());
} catch (TimeoutException ex) {
  System.out.println("time out exception has occured");
}
catch(Exception e)
{System.out.println("Exception has occured");}
finally {
  future.cancel(false); // may or may not desire this
}

}

public static String gettheCOntext()
{
String ramesh="ramesh";
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ramesh;
}

}



Monday, October 15, 2012

Wednesday, September 12, 2012

eclipse short cuts for good coding

Ctrl + Shift + F – Formats the source code.

Ctrl + Shift + O – Organizes the imports and removes the unused ones.

Instead of you manually invoking these two functions, you can tell Eclipse to auto-format and auto-organize whenever you save a file. To do this, in Eclipse, go to Window -> Preferences -> Java -> Editor -> Save Actions and then enable Perform the selected actions on save and check Format source code + Organize imports.

Avoid multiple returns (exit points) in methods: 

private boolean isEligible(int age){
  if(age > 18){
    return true;
  }else{
    return false;
  }
}

can be replaced with the below code 


private boolean isEligible(int age){
  boolean result;
  if(age > 18){
    result = true;
  }else{
    result = false;
  }
  return result;
}


which one is better

Boolean b = new Boolean(true)  or Boolean.valueOf(true)  ?

Do not create new instances of Boolean, Integer or String: 

Avoid creating new instances of Boolean, Integer, String etc. For example, instead of using new Boolean(true), useBoolean.valueOf(true). The later statement has the same effect of the former one but it has improved performance.



Mark method parameters as final, wherever applicable: 

Always mark the method parameters as final wherever applicable. If you do so, when you accidentally modify the value of the parameter, you’ll get a compiler warning. Also, it makes the compiler to optimize the byte code in a better way. 


private boolean isEligible(final int age){ ... }


Name public static final fields in UPPERCASE: 

Always name the public static final fields (also known as Constants) in UPPERCASE. This lets you to easily differentiate constant fields from the local variables. 

NOT RECOMMENDED
public static final String testAccountNo = '12345678'; 

RECOMMENDED
public static final String TEST_ACCOUNT_NO = '12345678';,


Monday, September 10, 2012

python how to use if else , simple example


a  = input()
if a == 'ramesh':
    print ('hi '+a)
elif  a == 'babu':
    print ('hi '+a+' ela unnavu')
else :
    print ('hi ')


save it with ifelse.py and run using f5 

Tuesday, August 28, 2012

how to split the given statement using split() function in python


s = input("enter any sentence")
for w in s.split():
    print(w)

this script will split the entered sentence based on the space 

if we entered the sentence as  , python is using by rby , then result is 

python
is
using
by
rby

if we use the split like below 

s = input("enter any sentence")
for w in s.split(':'):
    print(w)


then 

it will work as follows

ramesh:rby:python


ramesh
rby
python

Monday, August 27, 2012

printing first n natural numbers starting from 0 in python


def ranarr(len):
    arr=[]
    for i in range(0,len):
        arr.append(i)
        print(i)
    return arr

print(ranarr(10))



result :

0
1
2
3
4
5
6
7
8
9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Sunday, August 26, 2012

finding the length of a string in python


s='ramesh'
print(len(s))



open ant notepad type above two lines save it with some name of ur choice with file extension as py the execute 

adding two number in python

below is the simple python script to add two numbers



x = input("enter value of x")
y= input("enter value of y")
z=int(x)+int(y)
print("x :"+str(x)+" + Y:"+str(y)+" = "+str(z))


save it as add.py and enjoy

Wednesday, August 8, 2012

how to retrieve the values in .properties into java using the spring and spring annotations

In this , u will see , how to get the values of .properties into java using spring annotations

in the spring application context xml file defined as below

      
    <util:properties id="pwdProperties"
        location="classpath:/PwdRules.properties" />


and define a properties file with the name PwdRules.properties, add any name value pair to this file

let consider we added like below

name=rby

now define a class , with the name . AppConfig.java , inside , write the below code


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;


@Configuration
//spring config that loads the properties file
@ImportResource("classpath:/login-connector.xml")
public class AppConfig {

/**
     * Using property 'EL' syntax to load values from the
     * jetProperties value
     */
    private @Value("#{pwdProperties[' name  ']}") String  name  ;
    
    /**
     * Create a jetBean within the Spring Application Context
     * @return a bean
     */
    public @Bean(name = "pwdBean")
    PwdBean pwdBean() {
    PwdBean bean = new PwdBean();
        bean.setName(name);
        return bean;
    }
 
}


define a bean class with the name

PwdBean.java and add one member field for that as, name and generate setter and getter for that 


and u can write the test case as below to test this

ApplicationContext ctx =
            new AnnotationConfigApplicationContext(AppConfig.class);
PwdBean bean = ctx.getBean(PwdBean.class);
System.out.print(bean.getPwdrule());

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.