Adding C3PO Connection Pooling in Spring JDBC.

Connection pooling is an operation in which system pre-initializes the connection for use as creating connections at the time of use is an expensive operation. In this post we will learn how we can punch C3P0 connection pooling in Spring JDBC

All following dependency to pom.xml file

<dependency>
  <groupId>c3p0</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.1.2</version>
</dependency>

Now we need to prepare a JDBC context file for spring. We need to define a Data source for a DB with all its credentials. define data-source bean as bellow.

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.db_url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
    <property name="minPoolSize" value="${jdbc.minPoolSize}" />
    <property name="maxStatements" value="${jdbc.maxStatements}" />
    <property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>

I have been using properties file for define database connection details.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.db_url=jdbc:mysql://localhost:3306/{db_name}
jdbc.username=root
jdbc.password=root
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true

That’s all you need to do in order to configure connection pooling.

Reading properties files in Spring with PropertyPlaceholderConfigurer bean

Spring allows us to externalize String literals in its context configuration files into external properties files in order to separate application-specific settings from framework-specific configuration. For example, database connection details can be placed in a separate properties file. Then in Spring’s context configuration file we can use placeholders in style of ${variable_name} to map the keys declared in the properties files see sample bellow.

property file

jdbc.driverClassName=com.mysql.jdbc.Driver

spring bean read property

<property name="driverClass" value="${jdbc.driverClassName}" />

Please find example as bellow.

Declare a PropertyPlaceholderConfigurer bean in Spring’s application context file as follows:

<bean id="appProperties"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <!--<value>classpath:mail.properties</value>--> <!-- add propety file if needed -->
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

The properties file has the following entries

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.db_url=jdbc:mysql://localhost:3306/{db_name}
jdbc.username=root
jdbc.password=root
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true

And the following bean declaration uses some placeholders which will be resolved by Spring

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.db_url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
    <property name="minPoolSize" value="${jdbc.minPoolSize}" />
    <property name="maxStatements" value="${jdbc.maxStatements}" />
    <property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>

 

Spring will replace these placeholders by actual values of the corresponding entries in the properties file. An exception will be thrown if a placeholder could not be resolved.

Java Web Service – Example

Web services are client and server applications that communicate over the World Wide Web’s (WWW) Hyper Text Transfer Protocol (HTTP). As described by the World Wide Web Consortium , web services provide a standard means of inter operating between software applications running on a variety of platforms and frameworks.Technically, Web Services uses XML to exchange data between applications. Web Service is mix of SOAP and WSDL technologies. Now, Let us look at how to develop web service web Application, Download following software.

  • jboss-as-7.1.0.Final

Create web project. This is a PrintService class that write web methods.

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService(name = "printService")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.BARE)
public class PrintService {
@WebMethod
public void PrintName(){
System.out.println("############################################");
System.out.println("## TEST WEB SERVICE ##");
System.out.println("############################################");
}
}

Then we have to map This class in web.xml file as below.

I have used jboss-web.xml file to map root-context.

Then Build and deploy web Application in the jboss-as-7.1.0.Final.
Enter following URL to see WSDL file : http://localhost:8080/TestWebService/printService?wsdl

On a technical level, web services can be implemented in various ways.

Sorting with Java

SelectionSort – int Array

public class SelectionSort {

public int[] selectionSort(int[] data) {
int lenD = data.length;
int j = 0;
int tmp = 0;
for (int i = 0; i < lenD; i++) {
j = i;
for (int k = i; k data[k]) {
j = k;
}
}
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
return data;
}

public static void main(String args[]){
SelectionSort selectionSort = new SelectionSort();
int a[] = {2,3,6,4,9,7};
int b[] = selectionSort.selectionSort(a);
for(int i = 0; i < b.length; i++){
System.out.println(b[i]);
}
}
}

Selection Sort – String array
public class selectionSort2 {
public static void selectionSort(String[] data) {
for (int numSort = 0; numSort < data.length-1; numSort++){
// find the next minimum
int minPos = numSort; // initial position of next min
for (int pos = numSort+1; pos 0)
minPos = pos; // found new min
}
// swap in min to next position in sorted list
String temp = data[minPos];
data[minPos] = data[numSort];
data[numSort] = temp;
}
}

public static void main(String args[]){
String a[] = {"kamal", "amal", "sujith", "nimal", "jagath"};
selectionSort(a);
for(int i = 0; i < a.length; i ++){
System.out.println(a[i]);
}
}
}

InsertionSort – int Array

public class InsertionSort {
public int[] insertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}

public static void main(String args[]){
InsertionSort insertionSort = new InsertionSort();
int a[] = {2,3,6,4,9,7};
int b[] = insertionSort.insertionSort(a);
for(int i = 0; i < b.length; i++){
System.out.println(b[i]);
}
}
}

Bubble Sort – int array
public class BubbleSort {
public int[] bubbleSort(int[] data){
int lenD = data.length;
int tmp = 0;
for(int i = 0;i=(i+1);j--){
if(data[j]<data[j-1]){
tmp = data[j];
data[j]=data[j-1];
data[j-1]=tmp;
}
}
}
return data;
}

public static void main(String args[]){
BubbleSort bubbleSort = new BubbleSort();
int a[] = {2,3,6,4,9,7};
int b[] = bubbleSort.bubbleSort(a);
for(int i = 0; i < b.length; i++){
System.out.println(b[i]);
}

}
}

Using Collections.sort and Comparable in Java

Comparable is used for sort Java object based on its property value.To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see How Car object sort by Car Size.

package com.test;

public class Car implements Comparable{
private String carType;
private int size;
private String colour;
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
@Override
public int compareTo(Car otherCar) {
int carsize = otherCar.getSize();
if(this.size > carsize){
return 1;
}
else if(this.size < carsize){
return -1;
}
else{
return 0;
}
}
}

This class use Collections.sort() method to sort car Objects

package com.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CompareCar{
private static List carList ;
public static List getCarList(){
carList = new ArrayList();
Car car1 = new Car();
car1.setCarType("BMW");
car1.setColour("RED");
car1.setSize(350);

Car car2 = new Car();
car2.setCarType("ALLION");
car2.setColour("YELLOW");
car2.setSize(200);

Car car3 = new Car();
car3.setCarType("SUZUKI");
car3.setColour("BLACK");
car3.setSize(1000);

Car car4 = new Car();
car4.setCarType("ALTO");
car4.setColour("BULE");
car4.setSize(400);

carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
return carList;
}

public static void printValue(List carLIST){
for (int a = 0; a" + carLIST.get(a).getCarType() + " Car Colour -> " + carLIST.get(a).getColour()
+ " Car Size-> " + carLIST.get(a).getSize());
}
}

public static void main(String args[]){
List carLis = CompareCar.getCarList();
Collections.sort(carLis);
printValue(carLis);
}
}

You can see Sorted Car list details in console

Factory Design Pattern

Factory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class.The factory pattern (also known as the factory method pattern) is a creational design pattern.

Let we discuss with simple example,

1. Animal Super class

package com.test.factory;
public abstract class Animal {
public abstract String makeSound();
}

2.Dog class
Dog sub class extends Animal class and Override makeSound() method and return “Woof”

package com.test.factory;
public class Dog extends Animal{
@Override
public String makeSound() {
return "Woof";
}
}

3. Cat Class
Cat sub class extends Animal class and Override makeSound() method and return “Meow”

package com.test.factory;
public class Cat extends Animal{
@Override
public String makeSound() {
return "Meow";
}
}

4.AnimalFactory Class
AnimalFactory class create Dog and Cat Object according to input

package com.test.factory;
public class AnimalFactory {
public Animal getAnimal(String type) {
if ("canine".equals(type)) {
return new Dog();
} else {
return new Cat();
}
}
}

5. Demo class
This class show how to use factory design pattern
package com.test.factory;
public class DemoClass {
public static void main(String[] args) {
AnimalFactory animalFactory = new AnimalFactory();
/* this create Cat object */
Animal a1 = animalFactory.getAnimal("feline");
System.out.println("a1 sound: " + a1.makeSound());
/* this create Dog object */
Animal a2 = animalFactory.getAnimal("canine");
System.out.println("a2 sound: " + a2.makeSound());
}
}

Java Practical Question

1). Find given number even or odd?

2). Write a program that given year is leap year or not?

3). Get out put like given below

4). If ArrayList have duplicate values, write program to get unique values?

5). If you give Birth-date(xxxx-xx-xx format). how to calculate age?

6).Load an ArrayList with Strings from a text file of names. Show the names sorted in order of first name and then by last name.

7).To show the polymorphism concept , Write program by getting example as library?

8). Find given number Prime Number or not?

9). write a program to calculate area of circle?

10). write program to find reverse number of given number?

Follow

Get every new post delivered to your Inbox.