Friday, 7 July 2017

Tomcat DataSource JNDI Example in Java

In my previous post, I explained how to create connection to the database using DataSource element. In this post, I am going to explain how can we configure datasource in tomcat as a resource and how to get the resource using JNDI.

We can configure data source as a resource in three ways.
         a. web.xml configuration
         b. context.xml configuration
         c. Global configuration

a. Configure data source using web.xml file
Data source configuration is defined in META-INF/context.xml file. Container takes care of loading and unloading the data source.

context.xml
<Context>

 <Resource name="jdbc/organization" auth="Container" type="javax.sql.DataSource"
  maxActive="50" maxIdle="30" maxWait="10000" username="derbyuser"
  password="derbyuser" driverClassName="org.apache.derby.jdbc.ClientDriver"
  url="jdbc:derby://localhost:1527/myOrganization;create=true" />

</Context>
We should refer the resource that we defined in META-INF/context.xml in the web.xml file.

web.xml

<?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/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jdbcDataSourceExample</display-name>
  
  <resource-ref>
    <description>Derby Datasource example</description>
    <res-ref-name>jdbc/organization</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
  
</web-app>

Disadvantages
a. Since the configurations are tightly couple with the application, we need to redeploy the war file, wheneve we change the configurations in context.xml file.
b. The data source is created at application level, so we can't use this data source across different applications.
c. If anyone define a global data source with the same name, then it takes priority than the application level data source.

b. Configure data source using server context.xml file
You can configure the data source in '$CATALINA_BASE/conf/server.xml' file. The file is in tomcat/conf directory. The scope of the resource is application specific.

For example,
if you define a DataSource connection pool of 10 connections in server.xml. Assume there are 50 applications deployed. Then the datasource will be created for each of the application. This will result in 50*10 = 500 connections that will obviously consume all the database server resources and degrade the system performance.

c. Global Configuration
By define the GlobalNamingResources element in server.xml file of the tomcat server, you can make the data source available to all the applications that deployed in this server. 

In the below application, I am going to define data source using first approach.

How to configure MySQL DataSource in Tomcat using application web.xml file

Step 1: Create new dynamic web project in Eclipse.

File -> New -> Other
Search for ‘Dynamic Web Project’.

Give the project name as ‘jdbcDataSourceExample’.

Press Next.


Select the option ‘Generate web.xml deployment descriptor’ and press Finish.


Project structure is created like below.


Step2: Mavenize the project.
Right click on the project -> Configure -> Convert to Maven project.

Add below dependency to the pom.xml.


Step 3: Create META-INF/context.xml

context.xml

<Context>

 <Resource name="jdbc/organization" auth="Container" type="javax.sql.DataSource"
  maxActive="50" maxIdle="30" maxWait="10000" username="derbyuser"
  password="derbyuser" driverClassName="org.apache.derby.jdbc.ClientDriver"
  url="jdbc:derby://localhost:1527/myOrganization;create=true" />

</Context>

Step 4: Define data source in web.xml.

         <resource-ref>
                 <description>Derby Datasource example</description>
                 <res-ref-name>jdbc/organization</res-ref-name>
                 <res-type>javax.sql.DataSource</res-type>
                 <res-auth>Container</res-auth>
         </resource-ref>

web.xml

<?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/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jdbcDataSourceExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <resource-ref>
    <description>Derby Datasource example</description>
    <res-ref-name>jdbc/organization</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

Step 5: Define package ‘com.sample’ and define the classes 'DataSourceUtil' and  ‘HelloWorld’ there.

DataSourceUtil.java

package com.sample;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DataSourceUtil {

 public static DataSource getDataSource() {
  DataSource dataSource = null;

  try {
   Context ctx = new InitialContext();
   dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/organization");
  } catch (NamingException e) {
   e.printStackTrace();
  }

  return dataSource;
 }

 public static void createAndInsertDataIntoTable() throws SQLException {
  Connection conn = getDataSource().getConnection();

  /* Create table employee */
  String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
  Statement stmt = conn.createStatement();
  stmt.execute(query);

  /* Insert data to employee table */
  query = "INSERT INTO employee values(1, 'Krishna')";
  stmt.execute(query);
  query = "INSERT INTO employee values(2, 'Arjun')";
  stmt.execute(query);

  query = "SELECT * FROM employee";
  ResultSet rs = stmt.executeQuery(query);

  while (rs.next()) {
   int id = rs.getInt("id");
   String name = rs.getString("name");
   System.out.println(id + " " + name);
  }
  rs.close();
  conn.close();
 }
}


HelloWorld.java

package com.sample;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
 private static final long serialVersionUID = 1L;
 

 /**
  * Default constructor.
  */
 public HelloWorld() {

 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  try {
   DataSourceUtil.createAndInsertDataIntoTable();
  } catch (Exception e) {
   response.getWriter().append("data insertion failed, please check logs");
   e.printStackTrace();
  }
  response.getWriter().append("data inserted succesfully to the table employee ");
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doGet(request, response);
 }

}


Total project structure looks like below.


Run the Application and hit below url.


In the console, you can able to see below output.

1 Krishna
2 Arjun






Previous                                                 Next                                                 Home

Thursday, 6 July 2017

JDBC Data Source Example

This is continuation to my jdbc tutorial series. In jdbc tutorial series I explained how to connect to the database using jdbc. Just for your reference, below statements are used to connect to the database.

         /* Load the jdbc driver */
         Class.forName("com.mysql.jdbc.Driver");
        
        /* Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);

Why do we require a data source?
If you are going to connect to the database using DriverManager, you need to provide the username, password, url to connect etc., to connect to the database and you are responsible to open and closing the connections.

In case of data source, application server takes care of the details to connect to the database. You need to provide the JNDI name to connect to the database. Let use first see an example, how to connect to the database using data source and later I will explain how to configure the database properties in tomcat and connect to the database using JNDI.

I am going to use Apache Derby in client-server mode. If you would like to know, how to configure Apache Derby in client-server mode, I recommend you to go through my below tutorial series.


Below snippet is used to create a data source element. Once you get the data source elements, you can get connection objects to that data source.

         public static DataSource getDataSource(String database, String userName, String password) throws SQLException {
                 ClientDataSource clientDataSource = new ClientDataSource();

                 // DatabaseName can include Derby URL Attributes
                 clientDataSource.setDatabaseName(database);

                 clientDataSource.setUser(userName);

                 clientDataSource.setPassword(password);

                 // The host on which Network Server is running
                 clientDataSource.setServerName("localhost");

                 // port on which Network Server is listening
                 clientDataSource.setPortNumber(1527);

                 return clientDataSource;
         }
        
Below snippet is used to create connection to the database 'organization'.

                 String database = "organization;create=true";
                 String userName = "derbyuser";
                 String password = "derbyuser";

                 DataSource dataSource = getDataSource(database, userName, password);
                 Connection conn = dataSource.getConnection();

Find the below working application.


Test.java

package com.sample;

/* Step 1: Import sql package */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.derby.jdbc.ClientDataSource;

public class Test {

 /**
  * Return the data source
  * 
  * @return
  * @throws SQLException
  */
 public static DataSource getDataSource(String database, String userName, String password) throws SQLException {
  ClientDataSource clientDataSource = new ClientDataSource();

  // DatabaseName can include Derby URL Attributes
  clientDataSource.setDatabaseName(database);

  clientDataSource.setUser(userName);

  clientDataSource.setPassword(password);

  // The host on which Network Server is running
  clientDataSource.setServerName("localhost");

  // port on which Network Server is listening
  clientDataSource.setPortNumber(1527);

  return clientDataSource;
 }

 public static void main(String args[]) throws SQLException, ClassNotFoundException {
  String database = "organization;create=true";
  String userName = "derbyuser";
  String password = "derbyuser";

  DataSource dataSource = getDataSource(database, userName, password);
  Connection conn = dataSource.getConnection();

  /* Create table employee */
  String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
  Statement stmt = conn.createStatement();
  stmt.execute(query);

  /* Insert data to employee table */
  query = "INSERT INTO employee values(1, 'Krishna')";
  stmt.execute(query);
  query = "INSERT INTO employee values(2, 'Arjun')";
  stmt.execute(query);

  query = "SELECT * FROM employee";
  ResultSet rs = stmt.executeQuery(query);

  while (rs.next()) {
   int id = rs.getInt("id");
   String name = rs.getString("name");
   System.out.println(id + " " + name);
  }
  rs.close();
  conn.close();
 }
}

Output

1 Krishna
2 Arjun

One great advantage of DataSource over DriverManager is it supports connection pooling and distributed transaction support.

Can I register data source object using JNDI?
Yes, a DataSource object can be registered with a JNDI naming service. An application can use the JNDI API to access that DataSource object. Once you got the reference to the DataSource object, you can create connections to the database.

Previous                                                 Next                                                 Home

Monday, 3 July 2017

PowerMock, EasyMock : Pass any object as an argument to instance method

In this post, I am going to explain how to pass any object as an argument to mocked instance method. EasyMock class provide 'anyObject()' by using this we can tell the mocked method to accept any object as argument.

Following snippet is used to mock the method 'toUpper' which accepts any argument and return 'HELLO PTR'.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "toUpper");
EasyMock.expect(stringUtil.toUpper(EasyMock.anyObject())).andReturn("HELLO PTR").times(1);
EasyMock.replay(stringUtil);    
String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

Find the following working application.

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpper(String str) {
  throw new MethodNotImplementedException();
 }

 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = toUpper(str);
  return upperCase + upperCase;
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice() {
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "toUpper");

  EasyMock.expect(stringUtil.toUpper(EasyMock.anyObject())).andReturn("HELLO PTR").times(1);

  EasyMock.replay(stringUtil);
  
  String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

  assertEquals(result, "HELLO PTRHELLO PTR");

  PowerMock.verifyAll();
 }
}




Previous                                                 Next                                                 Home

Saturday, 1 July 2017

Java: Get package specific information

Package is a name space that provides a way to organise interfaces, classes  to avoid naming collisions.

Packages are like Directories. For Example, All the audio files in one directory, video files in other directory and text files in one directory. Similarly, A project can contain several files, so it is always good to organise them in consistent way. Packages used to Organise the classes and interfaces.

How to get package specific information?
‘java.lang.Package’ class is used to get package specific information like package name, title, vendor who implemented this package, specification version, implementation version of the package etc.,

Test.java
public class Test {

 public static void printPackage(Package p) {
  String name = p.getName();
  String title = p.getImplementationTitle();
  String vendorWhoImplentedThisPackage = p.getImplementationVendor();
  String implementationVersion = p.getImplementationVersion();
  
  String titleOfTheSpecification = p.getSpecificationTitle();
  String specVendor = p.getSpecificationVendor();
  String specVersion = p.getSpecificationVersion();
  

  System.out.println("name : " + name);
  System.out.println("title : " + title);
  System.out.println("vendorWhoImplentedThisPackage : " + vendorWhoImplentedThisPackage);
  System.out.println("implementationVersion : " + implementationVersion);
  System.out.println("titleOfTheSpecification : " + titleOfTheSpecification);
  System.out.println("specVendor : " + specVendor);
  System.out.println("specVersion : " + specVersion);
 }

 public static void main(String args[]) {

  Package p = Package.getPackage("java.lang");
  printPackage(p);

 }
}


Output
name : java.lang
title : Java Runtime Environment
vendorWhoImplentedThisPackage : Oracle Corporation
implementationVersion : 1.8.0_131
titleOfTheSpecification : Java Platform API Specification
specVendor : Oracle Corporation
specVersion : 1.8




PowerMock, EasyMock : Partially mock an object

Sometimes, you want to test some(not all) methods of an object. In that case, you need to mock the object partially. You can mock the object partially by using ‘createPartialMock’ method of PowerMock class.

Following snippet is used to mock the method ‘getEmployeeFirstNames’ of the class EmployeeService.

EmployeeService empService = PowerMock.createPartialMock(EmployeeService.class, "getEmployeeFirstNames");
EasyMock.expect(empService.getEmployeeFirstNames(emps)).andReturn(empNames);

PowerMock.replayAll();

‘createPartialMock’ method takes the class and the methods to mock as arguments. By using EasyMock.expect, we can set the expectation on calling of the method.

Find the following working application.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public Employee(int id, String firstName, String lastName) {
  super();
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}


EmployeeService.java
package com.sample.service;

import java.util.List;

import com.sample.model.Employee;
import com.sample.model.MethodNotImplementedException;

public class EmployeeService {

 /**
  * Return all the first names of the employees.
  * 
  * @param employees
  * @return
  */
 public List<String> getEmployeeFirstNames(List<Employee> employees) {
  throw new MethodNotImplementedException();
 }

 /**
  * Sort the names in their natural ordering.
  * 
  * @param names
  * @return
  */
 public List<String> sortListOfEmployeeNames(List<String> names) {
  names.sort(null);
  return names;
 }

 public List<String> sortAndGetAllTheEmployeeNames(List<Employee> employees) {
  List<String> empNames = getEmployeeFirstNames(employees);
  return sortListOfEmployeeNames(empNames);
 }
}


EmployeeServiceTest.java
package com.sample.tests;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

import org.easymock.EasyMock;
import org.junit.Test;
import org.powermock.api.easymock.PowerMock;

import com.sample.model.Employee;
import com.sample.service.EmployeeService;

public class EmployeeServiceTest {

 /**
  * This method test the function sortListOfEmployeeNames.
  * 
  */
 @Test
 public void sortAndGetAllTheEmployeeNames_ListOfEmployees_ExpectInNaturalOrdering() {
  Employee emp1 = new Employee(1, "Hari Krishna", "Gurram");
  Employee emp2 = new Employee(2, "Chamundeswari", "Majety");
  Employee emp3 = new Employee(3, "Rama Krishna", "Gurram");
  Employee emp4 = new Employee(4, "Gopi", "Battu");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4);
  List<String> empNames = Arrays.asList("Hari Krishna", "Chamundeswari", "Rama Krishna", "Gopi");

  EmployeeService empService = PowerMock.createPartialMock(EmployeeService.class, "getEmployeeFirstNames");
  EasyMock.expect(empService.getEmployeeFirstNames(emps)).andReturn(empNames);

  PowerMock.replayAll();
  List<String> names = empService.sortAndGetAllTheEmployeeNames(emps);

  PowerMock.verifyAll();

  assertEquals(names.get(0), "Chamundeswari");
  assertEquals(names.get(1), "Gopi");
  assertEquals(names.get(2), "Hari Krishna");
  assertEquals(names.get(3), "Rama Krishna");

 }
}






Previous                                                 Next                                                 Home

Friday, 30 June 2017

PowerMock, EasyMock : Mock an object

In this post, I am going to explain how to create mock object and how to mock the methods of the mocked object.

By using PowerMock class 'createMock' method we can create a mock object. Once the mock object is created, we can set expectations to the methods.

Following snippet, create mock object for File class, and set expectations to the methods 'getName', 'getAbsolutePath’.

File file = PowerMock.createMock(File.class);
                
EasyMock.expect(file.getName()).andReturn("TestFile");
EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile");
                
PowerMock.replayAll();

Following is the complete working application.

Test.java
package com.sample.tests;

import java.io.File;

import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;

public class Test {

 public static void main(String args[]){
  File file = PowerMock.createMock(File.class);
  
  EasyMock.expect(file.getName()).andReturn("TestFile");
  EasyMock.expect(file.getAbsolutePath()).andReturn("/Users/HariKrishna/TestFile");
  
  PowerMock.replayAll();
  
  System.out.println(file.getName());
  System.out.println(file.getAbsolutePath());
 }
}



Previous                                                 Next                                                 Home