Saturday, September 7, 2013

Generic Dao Pattern Code

 // jdbc.properties - connection

hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/test
hibernate.connection.username = root
hibernate.connection.password = ********
hibernate.show_sql = true
hibernate.connection.pool_size = 1
hibernate.hbm2ddl.auto = create

 // app-context.xml - (Application context - spring configuration)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation=" 
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 <context:property-placeholder location="classpath:jdbc.properties" />
 <context:component-scan base-package="com.global" />

 <context:annotation-config />

 <!-- HIBERNATE CONFIGURATION -->      
 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan" value="com.global.models"/>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.connection.driver_class">${hibernate.connection.driver_class}</prop>
    <prop key="hibernate.connection.url">${hibernate.connection.url}</prop>
    <prop key="hibernate.connection.username">${hibernate.connection.username}</prop>
    <prop key="hibernate.connection.password">${hibernate.connection.password}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>   
   </props>
  </property>
 </bean>

 <tx:annotation-driven transaction-manager="txManager" />
  
 <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

</beans>

// Log4j.properties
log4j.rootLogger=DEBUG,A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c %x - %m%n

// Dao
//AbstractDAO.java
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public abstract class AbstractDAO <T, ID extends Serializable> implements GenericDAO <T,ID> {
   
    protected HibernateTemplate hibernateTemplate;
    private  Class<T> entityClass;
   
    public AbstractDAO(Class<T> c){entityClass =c;}
   
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        hibernateTemplate = new HibernateTemplate(sessionFactory);
    }
   
    @Transactional(propagation = Propagation.SUPPORTS)
    public void save(T entity) {
        hibernateTemplate.saveOrUpdate(entity);
    }
   
    @Transactional(propagation = Propagation.SUPPORTS)
    public void delete (T entity){
        hibernateTemplate.delete(entity);
    }
   
    @Transactional(propagation = Propagation.SUPPORTS)
    public T findByPrimaryKey (ID id){
        return hibernateTemplate.load(entityClass, id);
    }
   
    @SuppressWarnings("unchecked")
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly=true)
    public List<T> load(final Order order, final Criterion... criterion) {
        return (List<T>) hibernateTemplate.execute(new HibernateCallback<Object> () {
            public Object doInHibernate(Session session) {
               
                Criteria criteria = session.createCriteria(entityClass);
               
                if (criterion != null){
           
                    for (Criterion crit : criterion){
                        criteria.add(crit);
                    }
                }
               
                if (order != null){
               
                    criteria.addOrder(order);
                }
               
                return criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
            }
        });
    }
   
    @SuppressWarnings("unchecked")
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly=true)
    public List<T> loadAll() {
        return (List<T>) hibernateTemplate.execute(new HibernateCallback<Object> () {
            public Object doInHibernate(Session session) {
               
                Criteria criteria = session.createCriteria(entityClass);
               
                return criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
            }
        });
    }
   
    @SuppressWarnings("unchecked")
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly=true)   
    public List<T> findByNamedQueryAndNamedParam(String queryName,List paramList, Boolean isEntityClass){
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        if(isEntityClass == true){       
           
            Query query =  session.createSQLQuery(makeSPCall(queryName,paramList)).addEntity(entityClass);;
            List<T> list = query.list();
            return list;   
           
        }else{
           
            Query query = session.createSQLQuery(makeSPCall(queryName,paramList));
            query.executeUpdate();
            query = session.createSQLQuery("select "+extractOutParam(paramList));
            query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
            List data = query.list();
           
            /*Query query = session.createSQLQuery("{ call simpleproc(@a) }");
            query.executeUpdate();
            query = session.createSQLQuery("select @a");
            query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
            List data = query.list();*/

            /* for(Object object : data)
             {
                Map row = (Map)object;
                System.out.print("---------: " + row.get("@a")+"\n");
             }*/
            
             return data;
            //return hibernateTemplate.findByNamedQueryAndNamedParam(queryName, paramNames, values);
        }
           
    }
   
    public void setEntityClass(Class<T> entityClass){
        this.entityClass = entityClass;
    }
   

    private String makeSPCall(String spName,List paramList){
       
        StringBuffer sb = new StringBuffer();
        sb.append("{ call ");
        sb.append(spName);   
        sb.append("( ");
        if(paramList != null){
            for(int i=0;i<paramList.size();i++){
                sb.append(paramList.get(i).toString());
                if(i != paramList.size()-1 ){
                    sb.append(",");
                }
            }
        }
        sb.append(" ) }");
        return sb.toString();
    }

    // out parameters
    private String extractOutParam(List paramList){
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<paramList.size();i++){
            if(paramList.get(i).toString().charAt(0) == '@'){
                sb.append(paramList.get(i).toString());
                sb.append(",");
            }   
        }
        return sb.deleteCharAt(sb.lastIndexOf(",")).toString();
    }
   
   
}

//GenericDao.java
import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;

public interface GenericDAO <T, ID extends Serializable> {

    void save (T entity);
    void delete (T entity);
    T findByPrimaryKey (ID id);
    public List<T> load(final Order order, final Criterion... criterion);
    public List<T> loadAll();
    public void setEntityClass(Class<T> entityClass);
    public List<T> findByNamedQueryAndNamedParam(String queryName, List paramList, Boolean isEntityClass);
}

//DepartmentDAO.java
import com.global.models.Department;

public interface DepartmentDAO extends GenericDAO<Department, Long> {
}

// StaffDAO.java
import com.global.models.Staff;

public interface StaffDAO extends GenericDAO<Staff, Long> {
}

//UserDAO.java
import java.util.List;

import com.global.models.User;

public interface UserDAO extends GenericDAO<User, Long> {

    List<User> findByName(String name);
}

// DAO Implementation
// DepartmentDAOImpl.java
import org.springframework.stereotype.Repository;

import com.global.dao.AbstractDAO;
import com.global.dao.DepartmentDAO;
import com.global.models.Department;

@Repository("departmentDAO")
public class DepartmentDAOImpl extends AbstractDAO <Department, Long> implements DepartmentDAO {
   
    public DepartmentDAOImpl() {
        super(Department.class);
    }
}
//StaffDAOImpl.java
import org.springframework.stereotype.Repository;

import com.global.dao.AbstractDAO;
import com.global.dao.StaffDAO;
import com.global.models.Staff;

@Repository("staffDAO")
public class StaffDAOImpl extends AbstractDAO <Staff, Long> implements StaffDAO {
   
    public StaffDAOImpl() {
        super(Staff.class);
    }
}
//UserDAOImpl.java
import java.util.List;

import org.springframework.stereotype.Repository;

import com.global.dao.AbstractDAO;
import com.global.dao.UserDAO;
import com.global.models.User;

@Repository("userDAO")
public class UserDAOImpl extends AbstractDAO <User, Long> implements UserDAO {
   
    public UserDAOImpl() {
        super(User.class);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> findByName(String name) {
        return hibernateTemplate.find("from User where username = ?", name);
    }
}
//Models
//Department.java
import java.io.Serializable;
import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="Department")
public class Department implements Serializable {

    private static final long serialVersionUID = 536199897485735748L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
   
    private String name;
   
    @OneToMany(mappedBy="department", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Collection<Staff> staff;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    public Collection<Staff> getStaff() {
        return staff;
    }

    public void setStaff(Collection<Staff> staff) {
        this.staff = staff;
    }
}
// Staff.java
import java.io.Serializable;

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

@Entity
@Table(name="Staff")
public class Staff implements Serializable {
   
    private static final long serialVersionUID = 6090120733590906021L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
   
    private String firstname;
    private String surname;
   
    @ManyToOne
    private Department department;
   
    public long getId() {
        return id;
    }
   
    public void setId(long id) {
        this.id = id;
    }
   
    public String getFirstname() {
        return firstname;
    }
   
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
   
    public String getSurname() {
        return surname;
    }
   
    public void setSurname(String surname) {
        this.surname = surname;
    }
   
    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Staff [id=" + id + ", firstname=" + firstname + ", surname="
                + surname + ", department=" + department.getId() + "]";
    }
}

//User.java
import java.io.Serializable;

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

import org.hibernate.annotations.NamedNativeQuery;

//@NamedNativeQuery(name = "callUserStoreProcedure", query = "call t()", resultClass = User.class)
@Entity
@Table(name = "user")
public class User implements Serializable,Comparable {
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long user_id;
   
    @Column(name = "username")
    private String username;
   
    @Column(name = "password")
    private String password;
   
   
    public User(){}
   
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
   
    public Long getUser_id() {
        return user_id;
    }
    public void setUser_id(Long user_id) {
        this.user_id = user_id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
   
    @Override
    public int compareTo(Object o) {
        if(!(o instanceof User))
            throw new ClassCastException();
       
        User u = (User) o;
        return password.compareTo(u.getPassword());
    }

    @Override
    public String toString() {
        return "User [user_id=" + user_id + ", username=" + username
                + ", password=" + password + "]";
    }
}

// Services
//GenericService.java
import java.util.List;

import org.hibernate.annotations.NamedNativeQueries;
import org.hibernate.annotations.NamedNativeQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Qualifier;

import com.global.dao.DepartmentDAO;
import com.global.dao.StaffDAO;
import com.global.dao.UserDAO;
import com.global.models.Department;
import com.global.models.Staff;
import com.global.models.User;

@Component("service")
public class GenericService {

    @Autowired
    @Qualifier (value="departmentDAO")
    private DepartmentDAO departmentDao;
   
    @Autowired
    @Qualifier (value="staffDAO")
    private StaffDAO staffDao;
   
    @Autowired
    @Qualifier (value="userDAO")
    private UserDAO userDao;
   
    /**
     * Adds data to DB
     */

    @Transactional
    public void testAddData(){
       
        /*Department dept = new Department();
        dept.setName("IT");
        departmentDao.save(dept);
       
        Staff one = new Staff();
        one.setDepartment(dept);
        one.setFirstname("Ben");
        one.setSurname("Macklin");
        staffDao.save(one);
       
        Staff two = new Staff();
        two.setDepartment(dept);
        two.setFirstname("David");
        two.setSurname("Stonson");
       
        staffDao.save(two);*/
       
        User user = new User("sandeep", "9oo9le");
        userDao.save(user);
    }
   
    /**
     * Loads a member of staff and checks their department
     */

    @Transactional
    public void loadStaff(){
        List<Staff> staffs = staffDao.loadAll();
        Staff loaded = staffDao.findByPrimaryKey(staffs.get(0).getId());
        System.out.println("Accounts "+loaded.getDepartment().getName());
    }
   
    /**
     * Loads a department and checks it has two staff.
     */
   
    @Transactional
    public void loadDepartment(){
        List<Department> depList = departmentDao.loadAll();
       
        Department dep = departmentDao.findByPrimaryKey(depList.get(0).getId());
       
        for (Staff staff: dep.getStaff()){
            System.out.println(staff.getFirstname());
            System.out.println(staff.getSurname());
        }
       
        //assertEquals(2, dep.getStaff().size());
    }
   
    /**
     * Deletes all data after tests have run
     */
   
    @Transactional
    public void reset(){
       
        // Deletes all staff as departments cascadeType set to All.
        List<Department> dep = departmentDao.loadAll();
       
        for (Department department : dep){
        //    departmentDao.delete(department);
            System.out.println(department);
        }
    }
   
    @Transactional
    public List<User> findByName(String name){
        return userDao.findByName(name);
    }
   
    @Transactional   
    public List<User> findByNamedQueryAndNamedParam(String queryName, List paramList, Boolean isEntityClass){
        return userDao.findByNamedQueryAndNamedParam(queryName,paramList,isEntityClass);
    }   
   
    @Transactional   
    public List<Staff> findByNamedQuery(String queryName, List paramList, Boolean isEntityClass){
        return staffDao.findByNamedQueryAndNamedParam(queryName,paramList,isEntityClass);
    }
   
    @Transactional
    public List<User> load(final Order order, final Criterion... criterion){
        return userDao.load(order, criterion);
    }
   
}

// TestGen.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.global.models.Staff;
import com.global.models.User;
import com.global.services.GenericService;


public class TestGen {
   
    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
         ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");
         GenericService service = (GenericService)ctx.getBean("service");
        // Add data in DB
        // service.testAddData();

        // not a generic function
        List<User> usrList = service.findByName("sandeep");   
        System.out.println(usrList);
       
        // get list based on criteria
        Criterion criterion = Restrictions.ne("password", "9oo9le");       
        usrList = service.load(Order.desc("user_id"), criterion);
        for (User user : usrList) {
            System.out.println(" Criteria:--------- "+user.toString());
        }
       
        // Call stored procedure for bean
         usrList = (List<User>)service.findByNamedQueryAndNamedParam("t", null, true);
        for (User user : usrList) {
            System.out.println(user.toString());
        }       
       
        @SuppressWarnings("rawtypes")
        List paramList1 = new ArrayList();
        paramList1.add(2);
       
        // Call stored procedure for bean
         List<Staff> usrList1 = (List<Staff>)service.findByNamedQuery("sp2", paramList1, true);
        for (Staff user : usrList1) {
            System.out.println(user.toString());
        }   
       
        @SuppressWarnings("rawtypes")
        List paramList = new ArrayList();
        paramList.add("@a");
        paramList.add("@b");
        paramList.add(2);
       
        // Call Stroed procedure for Out Parameters
        List data = service.findByNamedQueryAndNamedParam("sp1",paramList,false);
               
        for(Object object : data)
        {
           Map row = (Map)object;
           System.out.print("---------: " + row.get("@a")+"\n");
           System.out.print("---------: " + row.get("@b")+"\n");
        }
       
        /*List<User> usrLst = (List<User>)service.findByNamedQueryAndNamedParam("t()", null, null);
        for (User user : usrLst) {
            System.out.println(user.toString());
        }*/
       
        /*@SuppressWarnings("rawtypes")
        List paramList = new ArrayList();
        paramList.add("@a");
        paramList.add("@b");
        paramList.add(2);
       
        TestGen t = new TestGen();
        System.out.println(t.makeSPCall("simpleproc",paramList));
        System.out.println(t.extractOutParam(paramList));*/
       
    }   
}




// jar files
antlr-2.7.6.jar
aopalliance.jar
cglib-nodep-2.2.3.jar
commons-collections-3.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.7-bin.jar
org.springframework.aop-3.0.6.RELEASE.jar
org.springframework.asm-3.0.6.RELEASE.jar
org.springframework.beans-3.0.6.RELEASE.jar
org.springframework.context-3.0.6.RELEASE.jar
org.springframework.core-3.0.6.RELEASE.jar
org.springframework.expression-3.0.6.RELEASE.jar
org.springframework.jdbc-3.0.6.RELEASE.jar
org.springframework.orm-3.0.6.RELEASE.jar
org.springframework.transaction-3.0.6.RELEASE.jar
org.springframework.web-3.0.6.RELEASE.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.1.jar

Monday, July 8, 2013

Call Sqlcmd using Java

Generate csv from java using sqlcmd command
import java.io.IOException;

public class TestSQLCMD {

 /**
  * Generate CSV Using SQLCMD command
  * @param _SQL
  * @param downloadPath
  * @return
  * @throws IOException
  */
 public static int exportCSVviaCommand(String _SQL, String downloadPath) 
                throws IOException  {
  
  String[] commandArray = {"sqlcmd", 
             "-S", "localhost,1433", //Server and Port
             "-d",  "my_server", // DB Name
             "-U", "sa",  // DB User
             "-P", "password",  // DB Password
             "-Q",  _SQL, // Query
             "-k2", // Removes all control characters from the output
             "-W", //  Remove tabs between columns
             "-f", "65001", // for UTF-8 format
             "-h", "-1", //Remove headers  
             "-s,", // Separator is comma ','
             "-o", downloadPath}; // "" --> output to file
    
  Process process = Runtime.getRuntime().exec(commandArray);
  
  /**
   * causes the current thread to wait, if necessary, until the process
   * represented by this Process object has terminated. This method
   * returns immediately if the subprocess has already terminated. If the
   * subprocess has not yet terminated, the calling thread will be blocked
   * until the subprocess exits. Returns: the exit value of the process.
   * By convention, 0 indicates normal termination.
   */
  int i = -1;
  try {
   i = process.waitFor();
   System.out.println(i);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  return i;
 }

 public static void main(String[] args) {
  String sql= " select * from Employee where DeptNo=1  and ID > 10 ";
  try {
   StringBuilder downloadPath = new StringBuilder();
   downloadPath.append("D:\\downloads\\employee.csv");
   exportCSVviaCommand(sql, downloadPath.toString());
  } catch (IOException e) {
   e.printStackTrace();
  }catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println("Done...........");
 }

}

Friday, June 21, 2013

HttpURLConnection SendGet and SendPost

// HTTP GET request
private static String sendGet(String URL) throws Exception {
 
 String url = URL;
 
 URL obj = new URL(url);
 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
 // optional default is GET
 con.setRequestMethod("GET");
 
 //add request header
 //con.setRequestProperty("User-Agent", "Mozilla/5.0");
 
 int responseCode = con.getResponseCode();
 System.out.println("\nSending 'GET' request to URL : " + url);
 System.out.println("Response Code : " + responseCode);
 
 BufferedReader in = new BufferedReader(
         new InputStreamReader(con.getInputStream()));
 String inputLine;
 StringBuffer response = new StringBuffer();
 
 while ((inputLine = in.readLine()) != null) {
  response.append(inputLine);
 }
 in.close();
 
 //print result
 System.out.println("GET: "+response.toString());
 return response.toString();
 
}

// HTTP POST request
private static String sendPost(String URL,String content) throws Exception {
 
 String url = URL;
 URL obj = new URL(url);
 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
 //add reuqest header
 con.setRequestMethod("POST");
 //con.setRequestProperty("User-Agent", USER_AGENT);
 con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
 String urlParameters = content;
 
 // Send post request
 con.setDoOutput(true);
 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
 wr.writeBytes(urlParameters);
 wr.flush();
 wr.close();
 
 int responseCode = con.getResponseCode();
 System.out.println("\nSending 'POST' request to URL : " + url);
 System.out.println("Post parameters : " + urlParameters);
 System.out.println("Response Code : " + responseCode);
 
 BufferedReader in = new BufferedReader(
         new InputStreamReader(con.getInputStream()));
 String inputLine;
 StringBuffer response = new StringBuffer();
 
 while ((inputLine = in.readLine()) != null) {
  response.append(inputLine);
 }
 in.close();
 
 //print result
 System.out.println("POST: "+response.toString());
 return response.toString();
 
 }
 
// HTTP POST request
private static void sendPost(String URL,String content, String fileDownloadPathWithExtension) 
   throws Exception {

 String url = URL;
 URL obj = new URL(url);
 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
 //add reuqest header
 con.setRequestMethod("POST");
 //con.setRequestProperty("User-Agent", USER_AGENT);
 con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
 String urlParameters = content;
 
 // Send post request
 con.setDoOutput(true);
 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
 wr.writeBytes(urlParameters);
 wr.flush();
 wr.close();
 
 int responseCode = con.getResponseCode();
 System.out.println("\nSending 'POST' request to URL : " + url);
 System.out.println("Post parameters : " + urlParameters);
 System.out.println("Response Code : " + responseCode);
 
 InputStream is = con.getInputStream();
  
 try{
      File file = new File(fileDownloadPathWithExtension);
      if(file.delete()){
       System.out.println(file.getName() + " is deleted!");
      }else{
       System.out.println("Delete operation is failed.");
      }
     }catch(Exception e){
      e.printStackTrace();
     }
  
 // Write to  File
 FileOutputStream writer = new FileOutputStream(fileDownloadPathWithExtension);
  
 byte[] buffer = new byte[153600];
 @SuppressWarnings("unused")
 int totalBytesRead = 0;
 int bytesRead = 0;
  
 while ((bytesRead = is.read(buffer)) > 0) {
  writer.write(buffer, 0, bytesRead);
  buffer = new byte[153600];
  totalBytesRead += bytesRead;
 }
 writer.close();
 is.close();

 con.disconnect();
    
}
To Call
String postURL = "Server URL"; /* REST API */
String param ="Parameters"; /* REST Parameters */
 
try {
 sendPost(postURL, param, "c:/TEST/test.xml");
 //sendGet(postURL);
 //sendPost(postURL,param);
} catch (Exception e) {
 e.printStackTrace();
}

Wednesday, June 5, 2013

String Validation using Regular Expression

Validate String Number

public class ValidateStrNum {

 public static boolean validateNumber(String number) { 
  return number.matches("^\\d*$"); 
 }
 
 public static boolean validateDouble(String number) { 
  return number.matches("\\d+\\.\\d+"); 
 }
 
 public static boolean validateHex(String number) { 
  return number.matches("^(0x|0X)[0-9A-Fa-f]+"); 
 }
   
 public static void main(String[] args) {
  String str = "1234567890";
       
  if(validateNumber(str)){
   try{
    if(str.length() <= 10){
     Integer i = Integer.parseInt(str);
     System.out.println("Int: "+i);
    }else{
     Long l = Long.parseLong(str);
     System.out.println("Long: "+l);
    }
   }catch(Exception e){
    e.printStackTrace();
   }
   // System.out.println(str);
   
  }else{
   System.out.println("numeric error");
  }
  
  if(validateDouble(str)){
   
    System.out.println(str);
   
  }else{
   System.out.println("double error");
  }
  
  if(validateHex(str)){
   
    System.out.println(str);
   
  }else{
   System.out.println("Hex error");
  }

 }
 
}

Saturday, May 4, 2013

SessionFactory

what is the purpose and activity of SessionFactory in hibernate?
The SessionFactory is created from a Configuration object, and as its name implies it is a factory for Session objects.

The SessionFactory is an expensive object to create. It, like the Configuration object, is usually created during application start up. However, unlike the Configuration object, It should be created once and kept for later use.

The SessionFactory object is used by all the threads of an application. It is a thread safe object. One SessionFactory object is created per database. Multiple SessionFactory objects (each requiring a separate Configuration) are created when connecting to multiple databases. The SessionFactory can also provide caching of persistent objects.

The main use of session factory object is to get the session object for the application

Friday, March 15, 2013

What is the importance of hashCode() and equals() methods? How they are used in Java?

The java.lang.Object has two methods defined in it. They are - public boolean equals(Object obj) public int hashCode(). These two methods are used heavily when objects are stored in collections.
There is a contract between these two methods which should be kept in mind while overriding any of these methods. The Java API documentation describes it in detail. The hashCode() method returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable or java.util.HashMap. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. The equals(Object obj) method indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. A practical Example of hashcode() & equals(): This can be applied to classes that need to be stored in Set collections. Sets use equals() to enforce non-duplicates, and HashSet uses hashCode() as a first-cut test for equality. Technically hashCode() isn't necessary then since equals() will always be used in the end, but providing a meaningful hashCode() will improve performance for very large sets or objects that take a long time to compare using equals().

What is fail-fast property?

At high level - Fail-fast is a property of a system or software with respect to its response to failures.
A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production. In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

Monday, March 11, 2013

Top 50 SQL Question & Answers

1. What is DBMS?
A Database Management System (DBMS) is a program that controls creation, maintenance and use of a database. DBMS can be termed as File Manager that manages data in a database rather than saving it in file systems.

2. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS store the data into the collection of tables, which is related by common fields between the columns of the table. It also provides relational operators to manipulate the data stored into the tables. Example: SQL Server.

3. What is SQL?
SQL stands for Structured Query Language , and it is used to communicate with the Database. This is a standard language used to perform tasks such as retrieval, updation, insertion and deletion of data from a database. Standard SQL Commands are Select.

4. What is a Database?
Database is nothing but an organized form of data for easy access, storing, retrieval and managing of data. This is also known as structured form of data which can be accessed in many ways. Example: School Management Database, Bank Management Database.

5. What are tables and Fields?
A table is a set of data that are organized in a model with Columns and Rows. Columns can be categorized as vertical, and Rows are horizontal. A table has specified number of column called fields but can have any number of rows which is called record.

Example:.
Table: Employee.
Field: Emp ID, Emp Name, Date of Birth.
Data: 201456, David, 11/15/1960.

6. What is a primary key?
A primary key is a combination of fields which uniquely specify a row. This is a special kind of unique key, and it has implicit NOT NULL constraint. It means, Primary key values cannot be NULL.

7. What is a unique key?
A Unique key constraint uniquely identified each record in the database. This provides uniqueness for the column or set of columns.
A Primary key constraint has automatic unique constraint defined on it. But not, in the case of Unique Key. There can be many unique constraint defined per table, but only one Primary key constraint defined per table.

8. What is a foreign key?
A foreign key is one table which can be related to the primary key of another table. Relationship needs to be created between two tables by referencing foreign key with the primary key of another table.

9. What is a join?
This is a keyword used to query data from more tables based on the relationship between the fields of the tables. Keys play a major role when JOINs are used.

10. What are the types of join and explain each?
There are various types of join which can be used to retrieve data and it depends on the relationship between tables.

Inner join.
Inner join return rows when there is at least one match of rows between the tables.

Right Join.
Right join return rows which are common between the tables and all rows of Right hand side table. Simply, it returns all the rows from the right hand side table even though there are no matches in the left hand side table.

Left Join.
Left join return rows which are common between the tables and all rows of Left hand side table. Simply, it returns all the rows from Left hand side table even though there are no matches in the Right hand side table.

Full Join.
Full join return rows when there are matching rows in any one of the tables. This means, it returns all the rows from the left hand side table and all the rows from the right hand side table.

11. What is normalization?
Normalization is the process of minimizing redundancy and dependency by organizing fields and table of a database. The main aim of Normalization is to add, delete or modify field that can be made in a single table.

12. What is Denormalization?
DeNormalization is a technique used to access the data from higher to lower normal forms of database. It is also process of introducing redundancy into a table by incorporating data from the related tables.

13. What are all the different normalizations?
The normal forms can be divided into 5 forms, and they are explained below -.

First Normal Form (1NF):.
This should remove all the duplicate columns from the table. Creation of tables for the related data and identification of unique columns.

Second Normal Form (2NF):.
Meeting all requirements of the first normal form. Placing the subsets of data in separate tables and Creation of relationships between the tables using primary keys.

Third Normal Form (3NF):.
This should meet all requirements of 2NF. Removing the columns which are not dependent on primary key constraints.

Fourth Normal Form (3NF):.
Meeting all the requirements of third normal form and it should not have multi- valued dependencies.

14. What is a View?
A view is a virtual table which consists of a subset of data contained in a table. Views are not virtually present, and it takes less space to store. View can have data of one or more tables combined, and it is depending on the relationship.

15. What is an Index?
An index is performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and it will be faster to retrieve data.

16. What are all the different types of indexes?
There are three types of indexes -.
Unique Index.
This indexing does not allow the field to have duplicate values if the column is unique indexed. Unique index can be applied automatically when primary key is defined.
Clustered Index.
This type of index reorders the physical order of the table and search based on the key values. Each table can have only one clustered index.
NonClustered Index.
NonClustered Index does not alter the physical order of the table and maintains logical order of data. Each table can have 999 nonclustered indexes.

17. What is a Cursor?
A database Cursor is a control which enables traversal over the rows or records in the table. This can be viewed as a pointer to one row in a set of rows. Cursor is very much useful for traversing such as retrieval, addition and removal of database records.

18. What is a relationship and what are they?
Database Relationship is defined as the connection between the tables in a database. There are various data basing relationships, and they are as follows:.
One to One Relationship.
One to Many Relationship.
Many to One Relationship.
Self-Referencing Relationship.

19. What is a query?
A DB query is a code written in order to get the information back from the database. Query can be designed in such a way that it matched with our expectation of the result set. Simply, a question to the Database.

20. What is subquery?
A subquery is a query within another query. The outer query is called as main query, and inner query is called subquery. SubQuery is always executed first, and the result of subquery is passed on to the main query.

21. What are the types of subquery?
There are two types of subquery – Correlated and Non-Correlated.
A correlated subquery cannot be considered as independent query, but it can refer the column in a table listed in the FROM the list of the main query.
A Non-Correlated sub query can be considered as independent query and the output of subquery are substituted in the main query.

22. What is a stored procedure?
Stored Procedure is a function consists of many SQL statement to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required.

23. What is a trigger?
A DB trigger is a code or programs that automatically execute with response to some event on a table or view in a database. Mainly, trigger helps to maintain the integrity of the database.
Example: When a new student is added to the student database, new records should be created in the related tables like Exam, Score and Attendance tables.

24. What is the difference between DELETE and TRUNCATE commands?
DELETE command is used to remove rows from the table, and WHERE clause can be used for conditional set of parameters. Commit and Rollback can be performed after delete statement.
TRUNCATE removes all rows from the table. Truncate operation cannot be rolled back.

25. What are local and global variables and their differences?
Local variables are the variables which can be used or exist inside the function. They are not known to the other functions and those variables cannot be referred or used. Variables can be created whenever that function is called.
Global variables are the variables which can be used or exist throughout the program. Same variable declared in global cannot be used in functions. Global variables cannot be created whenever that function is called.

26. What is a constraint?
Constraint can be used to specify the limit on the data type of table. Constraint can be specified while creating or altering the table statement. Sample of constraint are.
NOT NULL.
CHECK.
DEFAULT.
UNIQUE.
PRIMARY KEY.
FOREIGN KEY.

27. What is data Integrity?
Data Integrity defines the accuracy and consistency of data stored in a database. It can also define integrity constraints to enforce business rules on the data when it is entered into the application or database.

28. What is Auto Increment?
Auto increment keyword allows the user to create a unique number to be generated when a new record is inserted into the table. AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.
Mostly this keyword can be used whenever PRIMARY KEY is used.

29. What is the difference between Cluster and Non-Cluster Index?
Clustered index is used for easy retrieval of data from the database by altering the way that the records are stored. Database sorts out rows by the column which is set to be clustered index.
A nonclustered index does not alter the way it was stored but creates a complete separate object within the table. It point back to the original table rows after searching.

30. What is Datawarehouse?
Datawarehouse is a central repository of data from multiple sources of information. Those data are consolidated, transformed and made available for the mining and online processing. Warehouse data have a subset of data called Data Marts.

31. What is Self-Join?
Self-join is set to be query used to compare to itself. This is used to compare values in a column with other values in the same column in the same table. ALIAS ES can be used for the same table comparison.

32. What is Cross-Join?
Cross join defines as Cartesian product where number of rows in the first table multiplied by number of rows in the second table. If suppose, WHERE clause is used in cross join then the query will work like an INNER JOIN.

33. What is user defined functions?
User defined functions are the functions written to use that logic whenever required. It is not necessary to write the same logic several times. Instead, function can be called or executed whenever needed.

34. What are all types of user defined functions?
Three types of user defined functions are.
Scalar Functions.
Inline Table valued functions.
Multi statement valued functions.
Scalar returns unit, variant defined the return clause. Other two types return table as a return.

35. What is collation?
Collation is defined as set of rules that determine how character data can be sorted and compared. This can be used to compare A and, other language characters and also depends on the width of the characters.
ASCII value can be used to compare these character data.

36. What are all different types of collation sensitivity?
Following are different types of collation sensitivity -.
Case Sensitivity – A and a and B and b.
Accent Sensitivity.
Kana Sensitivity – Japanese Kana characters.
Width Sensitivity – Single byte character and double byte character.

37. Advantages and Disadvantages of Stored Procedure?
Stored procedure can be used as a modular programming – means create once, store and call for several times whenever required. This supports faster execution instead of executing multiple queries. This reduces network traffic and provides better security to the data.
Disadvantage is that it can be executed only in the Database and utilizes more memory in the database server.

38. What is Online Transaction Processing (OLTP)?
Online Transaction Processing or OLTP manages transaction based applications which can be used for data entry and easy retrieval processing of data. This processing makes like easier on simplicity and efficiency. It is faster, more accurate results and expenses with respect to OTLP.
Example – Bank Transactions on a daily basis.

39. What is CLAUSE?
SQL clause is defined to limit the result set by providing condition to the query. This usually filters some rows from the whole set of records.
Example: – Query that has WHERE condition
Query that has HAVING condition.

40. What is recursive stored procedure?
A stored procedure which calls by itself until it reaches some boundary condition. This recursive function or procedure helps programmers to use the same set of code any number of times.

41. What is Union, minus and Interact commands?
UNION operator is used to combine the results of two tables, and it eliminates duplicate rows from the tables. MINUS operator is used to return rows from the first query but not from the second query. Matching records of first and second query and other rows from the first query will be displayed as a result set.
INTERSECT operator is used to return rows returned by both the queries.

42. What is an ALIAS command?
ALIAS name can be given to a table or column. This alias name can be referred in WHERE clause to identify the table or column.
Example-.
Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex. StudentID
Here, st refers to alias name for student table and Ex refers to alias name for exam table.

43. What is the difference between TRUNCATE and DROP statements?
TRUNCATE removes all the rows from the table, and it cannot be rolled back. DROP command removes a table from the database and operation cannot be rolled back.

44. What are aggregate and scalar functions?
Aggregate functions are used to evaluate mathematical calculation and return single values. This can be calculated from the columns in a table. Scalar functions return a single value based on the input value.
Example -.
Aggregate – max(), count – Calculated with respect to numeric.
Scalar – UCASE(), NOW() – Calculated with respect to strings.

45. How can you create an empty table from an existing table?
Example will be -.
Select * into studentcopy from student where 1=2.
Here, we are copying student table to another table with the same structure with no rows copied.

46. How to fetch common records from two tables?
Common records result set can be achieved by -.
Select studentID from student.
INTERSECT
Select StudentID from Exam.

47. How to fetch alternate records from a table?
Records can be fetched for both Odd and Even row numbers -.
To display even numbers-.
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0.
To display odd numbers-.
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1.

48. How to select unique records from a table?
Select unique records from a table by using DISTINCT keyword.
Select DISTINCT StudentID, StudentName from Student.

49. What is the command used to fetch first 5 characters of the string?
There are many ways to fetch first 5 characters of the string -.
Select SUBSTRING(StudentName,1,5) as studentname from student.
Select RIGHT(Studentname,5) as studentname from student.

50. Which operator is used in query for pattern matching?
LIKE operator is used for pattern matching, and it can be used as -.
% – Matches zero or more characters.
_(Underscore) – Matching exactly one character.
Example -.
Select * from Student where studentname like ‘a%’
Select * from Student where studentname like ‘ami_’

Thursday, January 31, 2013

Memory Leaks

In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code.

A memory leak,occurs when a computer program consumes memory but is unable to release it back to the operating system.The JVM reserves the heap as virtual memory on startup and doesn't gives that memory back until it exits. This virtual memory turns into main memory as it is used. This is why the virtual size and the resident size for a JVM can be very different and the resident memory can grow without the virtual memory changing.

The GC can always find every object on the heap, even those which are not reachable to the application. As such there is no object which is not reachable to running code.however, many people refer to any unwanted increase in memory usage as a memory leak,though this is not strictly accurate from a technical perspective.

In Java, the amount of memory required cannot be determined without a full GC. It is normal to see the "used" memory of a Java application sawtooth. Returning to the same amount of memory used after each GC indicates the memory required has not increased.

A memory leak can diminish the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down unacceptably due to thrashing.

Tuesday, January 22, 2013

Reads and Write binary data

This example reads and write binary data, moving it from disk to memory, and then back again.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**  
 Converting binary data into different forms. 
 Reads binary data into memory, and writes it back out.
 Buffering is used when reading and writing files, to minimize the number 
 of interactions with the disk.
*/
public final class BytesStreamsAndFiles {

  /** Change these settings before running this class. */
  private static final String INPUT_FILE_NAME = "home\s\Download\green_house.jpg";
  private static final String OUTPUT_FILE_NAME = "home\s\Download\green_house_n.jpg";

  /** Run the example. */
  public static void main(String... aArgs) {
    BytesStreamsAndFiles test = new BytesStreamsAndFiles();
    //read in the bytes
    byte[] fileContents = test.read(INPUT_FILE_NAME);
    //test.readAlternateImpl(INPUT_FILE_NAME);
    //write it back out to a different file name
    test.write(fileContents, OUTPUT_FILE_NAME);
  }
  
  /** Read the given binary file, and return its contents as a byte array.*/ 
  byte[] read(String aInputFileName){
    log("Reading in binary file named : " + aInputFileName);
    File file = new File(aInputFileName);
    log("File size: " + file.length());
    byte[] result = new byte[(int)file.length()];
    try {
      InputStream input = null;
      try {
        int totalBytesRead = 0;
        input = new BufferedInputStream(new FileInputStream(file));
        while(totalBytesRead < result.length){
          int bytesRemaining = result.length - totalBytesRead;
          //input.read() returns -1, 0, or more :
          int bytesRead = input.read(result, totalBytesRead, bytesRemaining); 
          if (bytesRead > 0){
            totalBytesRead = totalBytesRead + bytesRead;
          }
        }
        /*
         the above style is a bit tricky: it places bytes into the 'result' array; 
         'result' is an output parameter;
         the while loop usually has a single iteration only.
        */
        log("Num bytes read: " + totalBytesRead);
      }
      finally {
        log("Closing input stream.");
        input.close();
      }
    }
    catch (FileNotFoundException ex) {
      log("File not found.");
    }
    catch (IOException ex) {
      log(ex);
    }
    return result;
  }
  
  /**
   Write a byte array to the given file. 
   Writing binary data is significantly simpler than reading it. 
  */
  void write(byte[] aInput, String aOutputFileName){
    log("Writing binary file...");
    try {
      OutputStream output = null;
      try {
        output = new BufferedOutputStream(new FileOutputStream(aOutputFileName));
        output.write(aInput);
      }
      finally {
        output.close();
      }
    }
    catch(FileNotFoundException ex){
      log("File not found.");
    }
    catch(IOException ex){
      log(ex);
    }
  }
  
  /** Read the given binary file, and return its contents as a byte array.*/ 
  byte[] readAlternateImpl(String aInputFileName){
    log("Reading in binary file named : " + aInputFileName);
    File file = new File(aInputFileName);
    log("File size: " + file.length());
    byte[] result = null;
    try {
      InputStream input =  new BufferedInputStream(new FileInputStream(file));
      result = readAndClose(input);
    }
    catch (FileNotFoundException ex){
      log(ex);
    }
    return result;
  }
  
  /**
   Read an input stream, and return it as a byte array.  
   Sometimes the source of bytes is an input stream instead of a file. 
   This implementation closes aInput after it's read.
  */
  byte[] readAndClose(InputStream aInput){
    //carries the data from input to output :    
    byte[] bucket = new byte[32*1024]; 
    ByteArrayOutputStream result = null; 
    try  {
      try {
        //Use buffering? No. Buffering avoids costly access to disk or network;
        //buffering to an in-memory stream makes no sense.
        result = new ByteArrayOutputStream(bucket.length);
        int bytesRead = 0;
        while(bytesRead != -1){
          //aInput.read() returns -1, 0, or more :
          bytesRead = aInput.read(bucket);
          if(bytesRead > 0){
            result.write(bucket, 0, bytesRead);
          }
        }
      }
      finally {
        aInput.close();
        //result.close(); this is a no-operation for ByteArrayOutputStream
      }
    }
    catch (IOException ex){
      log(ex);
    }
    return result.toByteArray();
  }
  
  private static void log(Object aThing){
    System.out.println(String.valueOf(aThing));
  }
} 

Saturday, January 19, 2013

NavigableMap

What is NavigableMap in Java 6 ?
NavigableMap in Java 6 is an extension of SortedMap like TreeMap which provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey.it also provide ways to create a Sub Map from existing Map e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between specified toKey and fromKey.These methods also provides a boolean to include specified key or not.

import java.util.NavigableMap;
import java.util.TreeMap;

/**
 *
 * What is NavigableMap in Java. 
 * How to use NavigableMap in Java.
 * NavigableMap provides important features - navigation methods
 * like lowerKey(), floorKey, ceilingKey() and higherKey().
 * There Entry counterpart and methods to create subMap e.g. headMap(), tailMap()
 * and subMap().
 *
 */
public class NavigableMapEx {

    public static void main(String args[]) {
     
        //NavigableMap extends SortedMap to provide useful navigation methods
        NavigableMap navigableMap = new TreeMap();
             
        navigableMap.put("BritneySpears", "I go through life like a karate kid");
        navigableMap.put("AnnePackard", "Nothing happens without risk");
        navigableMap.put("WillSmith", "Life is lived on the edge");
        navigableMap.put("Cinderella", "Live like there is no midnight");
        
        System.out.println("SorteMap:"+ navigableMap);
     
        //lowerKey returns key which is less than specified key
        System.out.println("lowerKey:"+ navigableMap.lowerKey("Cinderella"));
     
        //floorKey returns key which is less than or equal to specified key
        System.out.println("floorKey:"+ navigableMap.floorKey("AnnePackard"));
     
        //ceilingKey returns key which is greater than or equal to specified key
        System.out.println("ceilingKey:"+ navigableMap.ceilingKey("BritneySpears"));
     
        //higherKey returns key which is greater specified key
        System.out.println("higherKey:"+ navigableMap.higherKey("BritneySpears"));
     
     
        //It also provides useful method to create subMap from existing Map 
        //e.g. tailMap, headMap and subMap
     
        //headMap - returns NavigableMap whose key is less than specified
        //param: Key, boolean : inclusive
        NavigableMap headMap = navigableMap.headMap("Cinderella", false);
        System.out.println("headMap created form navigableMap : " + headMap);
             
        //tailMap - returns NavigableMap whose key is greater than specified
        NavigableMap tailMap = navigableMap.tailMap("BritneySpears", false);
        System.out.println("tailMap created form navigableMap : " + tailMap);
     
        //subMap - return NavigableMap from toKey to fromKey
        NavigableMap subMap = 
          navigableMap.subMap("AnnePackard", false,"WillSmith", false);
        System.out.println("subMap created form navigableMap : " + subMap);
    }
}

Friday, January 18, 2013

Nested Static Class

What is nested static class in Java
Nested static class in Java is a static member of any top level class. Though you can make any class static in Java, but you can only make nested classes i.e. class inside another class as static, you can not make any top level class static. Those classes are called nested static classes. Since to create instance of any nested class you require instance of outer class but that is not required in case of static nested class in Java. You can have an instance of nested static class without any instance of outer class. Here is an example of static nested class in Java
public class StaticClass{

    public static void main(String args[]){
        StaticClass.NestedStaticClass ns = new StaticClass.NestedStaticClass();
        System.out.println(ns.getDescription());
    }
  
    static class NestedStaticClass{
        public String NestedStaticDescription =" Nested Static Class in Java";
      
        public String getDescription(){
            return NestedStaticDescription;
        }
    }
} 

Output: Example of Nested Static Class in Java

When to use nested static class in Java
Normally we make a class static in Java when we want a single resource to be shared between all instances and normally we do this for utility classes which are required by all components and which itself doesn't have any state. Sometime interviewer ask when to use Singleton vs Static Class in Java for those purpose,answer is that if its completely stateless and it work on provided data then you can go for static class otherwise Singleton pattern is a better choice.

When to make a method static in Java
We can make a method static in Java in following scenario:
1) Method doesn't depends on object's state, in other words doesn't depend on any member variable and everything they need is passes as parameter to them.
2) Method belongs to class naturally can be made static in Java.
3) Utility methods are good candidate of making static in Java because then they can directly be accessed using class name without even creating any instance. Classic example is java.lang.Math
4) In various designs pattern which need a global access e.g. Singleton pattern, Factory Pattern.

Disadvantage of static method in Java
There are certain disadvantages also if you make any method static in Java for example you can not override any static method in Java so it makes testing harder you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.

Example of static class and method in Java
Static method in Java is very popular to implement Factory design pattern. Since Generics also provides type inference during method invocation, use of static factory method to create object is popular Java idiom. JDK itself is a good example of several static factory methods like String.valueOf(). Core Java library is also a great place to learn how to use static keyword in java with methods, variables and classes. Another popular example of static method is main method in Java.

1. java.util.Collections has some static utility method which operates on provided collection.
2. java.lang.Math class has static method for maths operations.
3. BorderFactory has static method to control creation of object.
4. Singleton Classes like java.lang.Runtime.

Caution : Static methods should not manage or alter any state. and now a funny question what would happen if you execute following code
public class ElectronicSystem {

    private static String category = "electronic system";
    public static void main(String[] args) {
        ElectronicSystem system = null;
        System.out.println(system.category);
    }

will it throw NullPointerException in Java or print "electronic system"

XML

Q: What is XML ?
A : XML stands for Extensible Markup language which means you can extend XML based upon your needs. You can define custom tags like , etc in XML easily as opposed to other mark-up language like HTML where you need to work with predefined tags e.g.

and you can not use user defined tag. Though structure of XML can be standardize by making use of DTD and XML Schema. XML is mostly used to transfer data from one system to another e.g. between client and server in enterprise applications.

Q: Difference between DTD and XML Schema?
A : There are couple of differences between DTD and XML Schema e.g. DTD is not written using XML while XML schema are xml documents in itself, which means existing XML tools like XML parsers can be used to work with XML schema. Also XML schema is designed after DTD and it offer more types to map different types of data in XML documents. On the other hand DTD stands for Document Type definition and was a legacy way to define structure of XML documents.

Q: What is XPath ?
A : XPath is an XML technology which is used to retrieve element from XML documents. Since XML documents are structured, XPath expression can be used to locate and retrieve elements, attributes or value from XML files. XPath is similar to SQL in terms of retrieving data from XML but it has it's own syntax and rules. See here to know more about How to use XPath to retrieve data from XML documents.

Q: What is XSLT?
A : XSLT is another popular XML technology to transform one XML file to other XML, HTML or any other format. XSLT is like a language which specifies its own syntax, functions and operator to transform XML documents. Usually transformation is done by XSLT Engine which reads instruction written using XSLT syntax in XML style sheets or XSL files. XSLT also makes extensive use of recursion to perform transformation. One of the popular example of using XSLT is for displaying data present in XML files as HTML pages. XSLT is also very handy to transforming one XML file into another XML document.

Q: What is element and attribute in XML?
A : This can be best explained by an example. let's see a simple XML snippet

<Orders>
  <Order id="123">
     <Symbol> 6758.T</Symbol>
     <Price> 2300</Price>
  <Order>
<Orders>


In this sample XML id is an attribute of element. Here , and are also other elements but they don't have any attribute.

Q: What is meaning of well formed XML ?
A : Another interesting XML interview question which most appeared in telephonic interviews. A well formed XML means an XML document which is syntactically correct e.g. it has a root element, all open tags are closed properly, attributes are in quotes etc. If an XML is not well formed, it may not be processed and parsed correctly by various XML parsers.

Q: What is XML namespace? Why it's important?
A : XML namespace are similar to package in Java and used to provide a way to avoid conflict between two xml tags of same name but different sources. XML namespace is defined using xmlns attribute at top of the XML document and has following syntax xmlns:prefix="URI". later that prefix is used along with actual tag in XML documents. Here is an example of using XML namespace :

<root xmlns:inst="http://instruments.com/inst">
  <inst:phone>
      <inst:number>837363223</inst:number>
   </inst:phone>
</root>


Q: Difference between DOM and SAX parser ?
A : This is another very popular XML interview question, not just in XML world but also on Java world. Main difference between DOM and SAX parser is the way they parse XML documents. DOM creates an in memory tree representation of XML documents during parsing while SAX is a event driven parser. See Difference between DOM and SAX parser for more detailed answer of this question.

Q: What is a CDATA section in XML?
A : I like this XML Interview questions for its simplicity and importance, yet many programmer doesn't know much about it. CDATA stands for character data and has special instruction for XML parsers. Since XML parser parse all text in XML document e.g. This is name of person here even though value of tag will be parsed because it may contain XML tags e.g. First Name. CDATA section is not parsed by XML parser. CDATA section starts with "".

Q: What is XML data Binding in Java?
A : XML binding in Java refers to creating Java classes and object from XML documents and then modifying XML documents using Java programming language. JAXB , Java API for XML binding provides convenient way to bind XML documents with Java objects. Other alternatives for XML binding is using open source library e.g. XML Beans. One of the biggest advantage of XML binding in Java is to leverage Java programming capability to create and modify XML documents.

Difference between DOM and SAX XML Parser
1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.
2) DOM parser is faster than SAX because it access whole XML document in memory.
3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.
4) DOM parser works on Document Object Model while SAX is an event based xml parser.
Ref: javarevisited

Why non-static variable cannot be referenced from a static context?

compiler error: non-static
public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
        count++; //compiler error: non-static variable count cannot be 
                 //referenced from a static context
    } 
}
Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance(). So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
In summary since code in static context can be run even without creating any instance of class, it does not make sense asking value for an specific instance which is not yet created.

How to access non static variable inside static method or block
You can still access any non static variable inside any static method or block by creating an instance of class in Java and using that instance to reference instance variable. This is the only legitimate way to access non static variable on static context. here is a code example of accessing non static variable inside static context:
public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
     StaticTest test = new StaticTest(); //accessing static variable by creating 
                                        //an instance of class
     test.count++;
    }  
}

Ref: javarevisited

Thursday, January 17, 2013

NoClassDefFoundError vs ClassNotFoundException

Similarities
1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.

Difference
1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option. On the other hand NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using classloaders in Java and have two classloaders then if a classloader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass, Class.forName while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.
Ref: javarevisited

What is load-on-startup

load-on-startup is a tag element which appear inside tag in web.xml.

load-on-startup tells the web container about loading of a particular servlet. if you don't specify load-on-startup then container will load a particular servlet when it feels necessary most likely when first request for that servlet will come, this may lead to longer response time for that query if Servlet is making database connections or performing ldap authentication which contribute network latency or any other time consuming job, to avoid this, web container provides you a mean to specify certain servlet to be loaded during deployment time of application by using load-on-startup parameter.

If you specify load-on-startup parameter inside a servlet than based upon its value Container will load it.you can specify any value to this element but in case of load-on-startup>0 , servlet with less number will be loaded first. For example in below web.xml AuthenticationServlet will be loaded before AuthorizationServlet because load-on-startup value for AuthenticationServlet is less (2) while for AuthorizationServlet is 4.

Eg:
<servlet>
<servlet-name>AuthenticationServlet</servlet-name>
<display-name>AuthenticationServlet</display-name>
<servlet-class>com.trading.AuthenticationServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet>
<servlet-name>AuthorizationServlet</servlet-name>
<display-name>AuthorizationServlet</display-name>
<servlet-class>com.trading.AuthorizationServlet</servlet-class>
<load-on-startup>4</load-on-startup>
</servlet>

Important points on load-on-startup element
1. If value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
2. if is 0 or negative integer than Servlet will be loaded when Container feels to load them.
3. guarantees loading, initialization and call to init() method of servlet by web container.
4. If there is no element for any servlet than they will be loaded when web container decides to load them.

When to use in web.xml is suitable for those servlet which performs time consuming jobs e.g. Creating Database Connection pool, downloading files or data from network or prepare environment ready for servicing client in terms of initializing cache , clearing pipelines and loading important data in memory. If any of your servlet performs these jobs then declare them using element and specify order as per your business logic or what suites your application. Remember lower the value of , servlet will be loaded first.
Ref: javarevisited

Wednesday, January 16, 2013

POJO

Plain Old Java Object
POJO, or Plain Old Java Object, is a normal Java object class (that is, not a JavaBean, EntityBean etc.) and does not serve any other special role nor does it implement any special interfaces of any of the Java frameworks. This term was coined by Martin Fowler, Rebbecca Parsons and Josh MacKenzie who believed that by creating the acronym POJO, such objects would have a "fancy name", thereby convincing people that they were worthy of use.

Plain Old Java Object The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.

class A {}
class B extends/implements C {}

Note: B is non POJO when C is kind of distributed framework class or ifc. e.g. javax.servlet.http.HttpServlet, javax.ejb.EntityBean or J2EE extn and not serializable/comparable. Since serializable/comparable are valid for POJO.

Here A is simple object which is independent. B is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is tightly coupled with distributed framework. Hence B object is not POJO from its definition.

Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.

So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.

JavaBean is a example of POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks. It means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file.

Example 1: JAXB is the service to represent java object as XML; These java objects are simple and come up with default constructor getters and setters.

Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.

Example 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.

In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model. Thus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:

Advantages: Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
Ref:stackoverflow