Tuesday, 21 June 2011

Database Connection Pooling in Tomcat using Eclipse

atabase Connection Pooling is a great technique used by lot of application servers to optimize the performance. Database Connection creation is a costly task thus it impacts the performance of application. Hence lot of application server creates a database connection pool which are pre initiated db connections that can be leverage to increase performance.
Apache Tomcat also provide a way of creating DB Connection Pool. Let us see an example to implement DB Connection Pooling in Apache Tomcat server. We will create a sample web application with a servlet that will get the db connection from tomcat db connection pool and fetch the data using a query. We will use Eclipse as our development environment. This is not a prerequisite i.e. you may want to use any IDE to create this example.

Step 1: Create Dynamic Web Project in Eclipse

Create a Dynamic Web Project in Eclipse by selecting:
File -> New -> Project… ->Dynamic Web Project.

Step 2: Create context.xml

Apache Tomcat allow the applications to define the resource used by the web application in a file called context.xml (from Tomcat 5.x version onwards). We will create a file context.xml under META-INF directory.

Copy following content in the context.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<Context>

<!-- Specify a JDBC datasource -->

<Resource name="jdbc/testdb" auth="Container"

type="javax.sql.DataSource" username="DB_USERNAME" password="DB_PASSWORD"

driverClassName="oracle.jdbc.driver.OracleDriver"

url="jdbc:oracle:thin:@xxx:1525:dbname"

maxActive="10" maxIdle="4" />



</Context>

In above code snippet, we have specify a database connection pool. The name of the resource is jdbc/testdb. We will use this name in our application to get the data connection. Also we specify db username and password and connection URL of database. Note that I am using Oracle as the database for this example. You may want to change this Driver class with any of other DB Providers (like MySQL Driver Class).

Step 3: Create Test Servlet and WEB xml entry

Create a file called TestServlet.java. I have created this file under package: com.vaani.servlet. Copy following code into it.

import java.io.IOException;

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.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;

public class TestServlet extends HttpServlet {

private DataSource dataSource;

private Connection connection;

private Statement statement;

public void init() throws ServletException {

try {

// Get DataSource

Context initContext = new InitialContext();

Context envContext = (Context)initContext.lookup("java:/comp/env");

dataSource = (DataSource)envContext.lookup("jdbc/testdb");

} catch (NamingException e) {

e.printStackTrace();

}

}

public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

ResultSet resultSet = null;

try {

// Get Connection and Statement

connection = dataSource.getConnection();

statement = connection.createStatement();

String query = "SELECT * FROM STUDENT";

resultSet = statement.executeQuery(query);

while (resultSet.next()) {

System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3));

}

} catch (SQLException e) {

e.printStackTrace();

}finally {

try { if(null!=resultSet)resultSet.close();} catch (SQLException e)

{e.printStackTrace();}

try { if(null!=statement)statement.close();} catch (SQLException e)

{e.printStackTrace();}

try { if(null!=connection)connection.close();} catch (SQLException e)

{e.printStackTrace();}

}

}

}

In the above code we initiated the datasource using InitialContext lookup:

Context initContext  = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/testdb");

Create test servlet mapping in the web.xml file (deployment descriptor) of the web application. The web.xml file will look like:

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>TomcatConnectionPooling</display-name>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>TestServlet</servlet-name>

<servlet-class>

com.vaani.servlet.TestServlet

</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>TestServlet</servlet-name>

<url-pattern>/servlet/test</url-pattern>

</servlet-mapping>

</web-app>


Now Run the web application in Tomcat using Eclipse (Alt + Shift + X, R). You will be able to see the result of the query executed.

Thus this way we can create a database pool in Tomcat and get the connections from it.

Apache POI api for Java people

It is one of the great tool from the Apache,

1st of all i want to write about what is POI?,why we need POI?.

What is POI?
“Poor Obfuscation Implementation”

Why we need POI?
reading and writing files in Microsoft Office formats, such as Word, PowerPoint and Excel using Java.
when i was trying to read the data from the .doc files by normal datainputstream reader , i get some garbage data along with original data.
then i startred searching for resolving this issue..at last i found that this API is very useful to work with microsoft formats.
i worked with only .doc file for  reading data line by line , in next post i will explain how to do that.
you can find more info regarding apache POI at WIKI and at apache project site .
Apache POI api  download from here.

Monday, 20 June 2011

SpringMVC + Hibernate Error: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

http://sivalabs.blogspot.com/2011/05/springmvc-hibernate-error-no-hibernate.html

Spring JdbcTemplate to retrieve List and Map

org.springframework.jdbc.core.JdbcTemplate used to perform query for specific result through out some query parameters. Some of the basic queries like query, queryForList, QueryForObject as the common understandings of the methods name. A query or queryForList method returns a list of desired rows but queryForMap returns only a single row where all the column names are key of the Map.
To retrieve a list, org.springframework.jdbc.core.RowMapper can be used along with java.sql.ResultSet. A sample code is like,

List sampleClassList = 
jdbcTemplate.query(query, new Object[]{parameters.....},
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
SampleClass sampleClass = new SampleClass();
sampleClass.setValue1(rs.getString("column1"));
sampleClass.setValue2(rs.getString("column2"));
return sampleClass;
}
});

In most of the cases developers convert a retrieved list to their desired Map later by manipulating the list. The basic reason behind is a map will not contain duplicate values as key but to a list data can be redundant. Its also possible to get a Map where one column as key and other as value of the map. org.springframework.jdbc.core.ResultSetExtractor can be used for customize results like Map. The following sample code can do this thing. Its really a very good option if one do not want to have duplicate value in a specific column. Its easier to make that thing a key.

Map map = (Map)jdbcTemplate.query(query, new Object[]{parameters....},
new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException {
Map map = new LinkedHashMap();
while (rs.next()) {
String col1 = rs.getString("col1");
String col2 = rs.getString("col2");
map.put(col1, col2);
}
return map;
};
});

How-to: Get timestamp in ANT scripts

http://javabeanz.wordpress.com/2010/10/13/how-to-get-timestamp-in-ant-scripts/

Saturday, 18 June 2011

Interview Question: Compare two web services type SOAP and RESTful (SOAP Vs RESTful)

Here are the differences between SOAP and Restful web services :





Criteria SOAP RESTful Comments
Orientation Wraps business logic Accesses resources/data
Developer View Object oriented Resource Oriented
Language Independence Yes Yes
Platform Independence Yes Yes
Simplicity No Yes
Standards Based Yes No SOAP web services are based on SOAP and WS-* specifications
Security SSL, WS-Security SSL WS-Security provides end-to-end security covering message integrity and authentication
Transactions WS-AtomicTransaction No
Reliability WS-ReliableMessaging Application specific
Performance Good Better Caching and lower message payload makes RESTful web services performance efficient and scalable
Caching No GET operations can be cached
Transport protocol support HTTP, SMTP, JMS HTTP Multiple transport protocol support makes SOAP Web Services flexible
Message Size Heavy, has SOAP and WS-* specific markup Lightweight, no extra xml markup
Message Communication protocol XML XML, JSON, other valid MIME type This flexibility of REST makes its extremely useful in providing consumer need specific message payloads
Message Encoding Yes No SOAP Web Services support text and binary encoding, RESTful encoding is limited to text
Service Description WSDL No formal contract definition In REST, no formal way to describe a service interface means more dependence on written documentation
Human intelligible Payload No Yes
Developer Tooling Yes Minimal or none Complexity of SOAP Web Services dictates the need for using frameworks to facilitate rapid application development. REST on the other hand due to its simplicity can be developed without any framework


Now we come to most important stage of deciding which type to select. There is no one answer for selecting either SOAP based or RESTful Web Services. Neither is the right choice for every situation. The choice is dependant upon specific needs and which solution addresses them best. An architect should ask the following questions and the responses should assist him/her in making an informed decision:
  • Does the service expose data or business logic? (REST can be a good choice for exposing data, SOAP/WS-* might be a better choice for logic)
  • Does the service need the capabilities of WS-*, or is a simpler RESTful approach sufficient?
  • What’s best for the developers who will build clients for the service?
Areas where RESTful WebServices are a great choice:
  • Limited bandwidth and resources: Remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
  • Totally stateless operations: If an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is suitable.
  • Caching situations: If the information can be cached because of the totally stateless operation of the REST approach, this is perfect.
Areas where SOAP based WebServices is a great solution:
  • Asynchronous processing and invocation: If application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging etc.
  • Formal contracts: If both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations: If the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.
I have used a lot of information from resources generously shared by fellow bloggers. It would inconsiderate in case I do not mention them. The resources are:
  1. REST and SOAP: When to use each (or both)?
  2. SOAP vs REST: Complements or Competitors
  3. Introduction to Web APIs: REST vs SOAP