Sunday, May 13, 2012

Establishing different database connections with generic program

In my previous post, I've explained about establishing the connection. In this post, I'm now going to cover a generic program which can be used to any database in run time dynamically (i.e.; without changing the program source code). I'm going explain.

import java.sql.*;

public class GenericJDBCApp
{
  public static void main(String args[]) throws Exception
  {
    String driverClass, jdbcURL, userName, password;
    //Reading the user defined system properties
    driverClass = System.getProperty("driverClass");
    jdbcURL = System.getProperty("jdbcURL");
    userName = System.getProperty("userName");
    password = System.getProperty("password");
    Class.forName(driverClass);
    Connection connection = DriverManager.getConnection(jdbcURL, userName, password);
    DataBaseMetaData metaData = connection.getMetaData();
    System.out.println("Connected to...."+metaData.getDatabaseProductName()+" "+metaData.getDatabaseMajorVersion()+"."+metaData.getDatabaseMinorVersion());
    System.out.println("Supports stored procedures: "+metaData.suportsStoredProcedures());
  }
}


If the above program is executed by using the following command, it will establish the connection with MySQL
java -DdriverClass=com.mysql.jdbc.Driver -DuserName=root -Dpassword=test -DjdbcURL=jdbc:mysql://localhost:3308/test GenericJDBCApp

By changing the values of the system parameter, we can make the application connect to any other database server.

DatabaseMetaData is an interface, when the above application eecutes connection.getMetaData(), the code provided by the JDBC driver vendor will be executed and this code creates an object based on a class provided by the vendor implemeting DatabaseMetaData.

JDBC - Java Database Connectivity

JDBC API: As part of Java 2 Standard Edition (J2SE), an API is provided to access the data managed by database servers like ORACLE, MySQL, Microsoft SQL Server, DB2, Sybase, etc. The name of the API is Java Database Connectivity (JDBC).

JDBC is a open specification i.e.; the specification is released as a public document and it is available for every one. As part of JDBC specification, Javasoft has provided various interfaces like java.sql.Driver, java.sql.Connection, java.sql.Statement, java.sql.PreparedStatement, java.sql.CallableStatement, java.sql.ResultSet etc.

Any company can provide a set of classes implementing the interfaces specified by Javasoft as part of JDBC API. These classes combined together is called as JDBC driver.

Oralce's JDBC driver is a set of classes that implements JDBC interfaces and the code in these classes is provided to deal with Oracle. For a single databse server, there can be multiple JDBC drivers avaialbe in market. The vendors of JDBC drivers suply the classes as part of JAR file. Oracle corp. provides ojdc14.jar

In order to use a JDBC driver, we must read the documentation provided by the JDBC driver vendor for the following information.
a. Name of the driver class. Eg: com.mysql.jdbc.Driver, oracle.jdbc.driver.OracleDriver
b. Format of the JDBC URL. Eg: jdbc:mysql://[domain or host]:[port]/[DB name], jdbc:oracle:thin:@[domain or host]:[port]:[DB name]

If the MySQL server and Java application are running on the same machine, then we can use localhost as a domain name in the above example JDBC URL.

Procedure for establishing the connection:
1. Register the driver using DriverManager.registerDriver() method as shown below
   DriverManager.registerDriver(new com.mysql.jdbc.Driver());
2. Establish the connection with the database server using DriverManager.getConnection as below
  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/test", "root", "test");

import java.sql.*;

public class DBApp1
{
  public static void main(String args[]) throws Exception
  {
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/test", "root", "test");
    System.out.println("Connection to DB..."+connection.getClass());
  }
}
Instead of using DriverManager.registerDriver(new com.mysql.jdbc.Driver()), we can use Class.forName("com.mysql.jdbc.Driver"); for registering the driver. As part of the driver class, the JDBC driver implementer provides a static block to register the driver.

When the above Class.forName(...) is executed, the driver class will be loaded and the static block of the driver class will be executed this static block which will take care of registering the driver.

When DriverManager.getConnection(...) is executed, the code provided by the JDBC driver vendor will be executed. This code creates an object based on a class implements the Connection interface provided by the JDBC driver vendor.

More to follow... stay tuned...

Tuesday, April 24, 2012

What is a Java collection - quick overview

We can use collection classes and objects to handle group of objects (other than arrays). Java has a collection frame work to deal with collections.

Collection framework: A collection framework is a class library to handle group of objects. It is implemented in java.util package.

Collection class: A collection class or container class is a class whose object can store a group of other objects.

Collection object: A collection object is an object that stores a group of other objects. It is also called container class object. The collection object stores objects references.


References of other objects are available in collection objects. All the classes in collection framework have been divided into 3 categories.

1. Set: A group of elements (objects). A class which implements java.util.Set interface is called as a set. Eg: HashSet, LinkedHashSet, TreeSet.

2. Lists: Collection of elements (objects). A class which implements java.util.List interface is called as a List. Eg: LinkedList, ArrayList, Vector.

3. Maps: A map stores elements in the form of key-value pairs. Eg: Hashtable, HashMap

I'll details about each type of collection in further posts... please checkout...

Java mobile browser detection

Hi guys - I've posted an article 2 years ago on developing a mobile web application by using the existing desktop application. You can read more here

X-WAP-PROFILE is not a full measure for us to decide the mobile user as the latest smartphone devices are not using this header. So, we need to look for another alternative. Here the technique is to identify the user based on the other headers called USER-AGENT and ACCEPT.

We can assure that 95% of mobile users can be detected by these 3 checks (X-WAP-PROFILE, USER-AGENT, ACCEPT).

Here the code snippet to identify the mobile users

MobileUtil.java
import javax.servlet.http.HttpServletRequest;

public class MobileUtil
{
 public boolean detectMobileBrowser(HttpServletRequest request)
 {
  String[] mobileUAA = { "midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows ce", "mmp/", "blackberry", "mib/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up.b", "audio", "SIE-", "SEC-", "samsung", "HTC", "mot-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "moto", "webos" };
  if (request.getHeader("X-WAP-PROFILE") != null)
  {
   return true;
  }
  else if (request.getHeader("user-agent") != null)
  {
   for (int i = 0; i < mobileUAA.length; i++)
   {
          if ((request.getHeader("user-agent").toLowerCase()).indexOf(mobileUAA[i]) != -1)
    {
     return true;
    }
   }
  }
  else if (request.getHeader("ACCEPT") != null && ((request.getHeader("ACCEPT")).toLowerCase()).indexOf("wap") != -1)
  {
   return true;
  }
  return false;
 }
}
OK, how to take this mobile detection program into a real mobile website implementation... Checkout in my further posts...

Saturday, March 17, 2012

What is a Web Service?


Most of the web applicatoins components are currently being developed with web service. It's important to understand the what is web service and how it works?

Web services are application components. They are designed to communicate with open protocols (ie.; XML, SOAP etc). Web services can be implemented on any platform and on any language i.e.; a web service which has originally been developed in Java can be accessed through .NET application.

Web service platform works with 3 different elements SOAP, UDDI, WSDL.

SOAP: SOAP stands for Simple Object Access Protocol. It is a communication protocol and it is a W3C standard. SOAP is designed to communicate through internet. SOAP communicates by sending XML messages. It is simple and extensible. SOAP is platform and language independent protocol.

WSDL: WSDL stands for Web Service Description Language. WSDL is used to locate and describe web services. WSDL is written in XML. This is the key element to develop Web service.

UDDI: UDDI stands for Universal Description, Discovery and Integration. It is a directory of web service interface described by WSDL.

Thursday, March 08, 2012

Classification of Java errors

Bug: An error in a program or software is called a bug. Removing the error is called debugging.

There are 3 types of errors

1.Syntax errors (compile time error): These are the errors detected by Java compiler at the time of compilation of a program. The errors due to improper syntax and grammar comes under compile time errors. Desk checking is a solution for compile time errors. Checking the program word by word, line by line is called desk checking. Java compiler can display upto 100 compile time errors only. These errors are called as checked exceptions in Java.

2.Runtime errors: These are the errors which are detected by JVM at the time of reunning the program. These errors happen because of inefficiency of computer system Eg: insufficient memory, unable to execute the instruction. These runtime errors are also called exceptions.

3.Logical errors: These errors are not detected by the Java compiler and JVM. These are the errors due to bad logic. The programmer is completely responsible for these errors. Logical errors can be detected by comparing the output of the program with manually calculated results.

In my next posts, I'm going to explain more about handling the exception in details... Watch out... :)

Extract source from Java class file

As you know Java has become popular because of the byte code instructions. JVM can understand only the byte code instructions i.e.; every Java class will be converted into byte code instructions when it is compiled. In the other words, every Java file will generate a corresponding .class file after it is successfully compiled.

Since, byte code instructions are part of .class file, it's not that hard to extract the source code from a .class file.  This process is called as de-compilation. You can even write a program on your own to get the Java code. Or you can use any of the open source available decompilers to extract the source code.

I'm going to explain here with a open source Java decompiler. You can download this tool @http://java.decompiler.free.fr/?q=jdgui.

Just download and execute the exe file. You can see the below screenshot on your screen.

Java Decompiler

You can open a class file as shown in the below screenshot.

Java Decompiler - open file

It will immediately show you the Java source code. You can choose "Save source" if you want to save the sorce code.

Java Decompiler - view source
You can even open a JAR file and the tool will show you the source code for all the class files part of the JAR. You can then save all the source files of JAR with "Save all source codes" option.