Monday, April 14, 2014

Connection Pooling




What is Connection Pooling:-
Opening/Closing database connections is an expensive process and hence connection pools improve the performance of execution of commands on a database for which we maintain connection objects in the pool.
Every time a client request is received, the pool is searched for an available connection object and it's highly likely that it gets a free connection object.
                                     
Need of Connection Pooling:
The biggest performance problem when dealing with remote databases is the time taken to establish a connection.
            In the case of very short operations like selecting a single attribute from a single row, the connection time might be orders of magnitude longer, such as a fraction of a second for the operation, but over a second to connect.
            Connection Pooling gets rid of this by establishing connections before they are required and holding them until someone asks for one.

Other advantages to Connection Pooling are:
It can reuse connections if they are returned, reducing work on the database to keep creating connections.
            They can be made to expand and contract as more connections are needed, which protects database resources from being wasted.
            And it can also have an upper limit of connections, to protect too many connections from choking the database.

Connection Pooling Example in Apache Tomcat+JSP Servlet+Hibernate+Mysql

Steps:
Step 1:
Create Context.xml  file  as below mentioned in Meta-INF Folder of project
Where you have to mention  configuration with you database .
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/coral" debug="1" reloadable="true">
    <Resource name="jdbc/coraljndi"
              type="javax.sql.DataSource"
              factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/coralDB"
              username="root"
              password=""
              maxActive="15"
          maxIdle="3"
          maxWait="5000"
          removeAbandoned="true"
          removeAbandonedTimeout="20"
          logAbandoned="true"
          validationQuery="select 1"
          minEvictableIdleTimeMillis="3600000"
          timeBetweenEvictionRunsMillis="1800000"
          numTestsPerEvictionRun="10"
          testWhileIdle="true"
          testOnBorrow="true"
          testOnReturn="false"/>
</Context>

Fields that need to change:
url: According to database you are using.
Username:
Password:
Resource Name: It is jndi name which you have to mention in web.xml file.

Step2:
Mention your jndi in web.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
 
  <resource-ref>
    <description>This is a MySQL database connection</description>
    <res-ref-name>jdbc/coraljndi</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

Step 3:
Mention your datasource in hibernate.cfg.xml file:
<property name="hibernate.connection.datasource">java:comp/env/jdbc/coraljndi</property>


In this way you can access your datasource.                

Saturday, April 12, 2014

JAXB -- ITS VERY SIMPLE STEP BY STEP

JAXB - Converting XML to java object and vice versa.

Marshaling - java Object to XML
UnMarshalling - XML to Java Object

Steps :

1 ) 

package com.model;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Students123")
public class Student {
@XmlElement(name = "age" ,required=true)
int age;
@XmlElement(name = "name" )
String name;

ArrayList<String> skill;

ArrayList<Skill> arrayListSk;
public ArrayList<Skill> getArrayListSk() {
return arrayListSk;
}

public void setArrayListSk(ArrayList<Skill> arrayListSk) {
this.arrayListSk = arrayListSk;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

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

public ArrayList<String> getSkill() {
return skill;
}

public void setSkill(ArrayList<String> skill) {
this.skill = skill;
}


}

2) Skill.java
package com.model;

public class Skill {

String skillName;
int skillId;
public int getSkillId() {
return skillId;
}
public void setSkillId(int skillId) {
this.skillId = skillId;
}
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
}

3)
JAXB Marshaling


package com;

import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.model.Skill;
import com.model.Student;

public class JAVA2XML {
public static void main(String[] args) throws JAXBException {
Student student = new Student();
student.setAge(77);
student.setName("kiran");
ArrayList<String > alPhone=new ArrayList<String>();
alPhone.add("111");
alPhone.add("222");
student.setSkill(alPhone);
Skill skill=new Skill();
skill.setSkillId(11);
skill.setSkillName("java");
Skill skill1=new Skill();
skill1.setSkillId(11111);
skill1.setSkillName("java11");
ArrayList<Skill> arrayListss=new ArrayList<Skill>();
arrayListss.add(skill);
arrayListss.add(skill1);
student.setArrayListSk(arrayListss);
// converting java object into XML
JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();

jaxbMarshaller.marshal(student, writer);
System.out.println(writer.toString());
}
}

4) Try below code for unmarshaling by your own

               JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
       Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
       User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
        
//Verify the populated object
       System.out.println(user.getId());
       System.out.println(user.getFirstName());
       System.out.println(user.getLastName());



ANOTHER EXAMPLE


Consider the following JAXB class:
import javax.xml.bind.annotation.*;
 
@XmlRootElement
public class Book {
 
  @XmlElement
  private String author;
 
  @XmlElement
  private String title;
}
Unmarshalling:
To convert an XML string into an object of class Book:
public static Book unmarshal(final String xml) throws JAXBException {
  return (Book) JAXBContext.newInstance(Book.class)
                           .createUnmarshaller()
                           .unmarshal(new StringReader(xml));
}
Marshalling:
To convert a Book object into an XML string:
public static String marshal(Book book) throws JAXBException {
  final Marshaller m = JAXBContext.newInstance(Book.class)
                                  .createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  final StringWriter w = new StringWriter();
  m.marshal(book, w);
  return w.toString();
}