Wednesday, June 3, 2015

Java Features

Important Features Of Java:
01. Platform Independence.
02. Object Oriented.
03. Compiler/Interpreter
04. Robust.
05. Security
06. Automatic Memory Management
07. Dynamic Binding
08. Good Performance
09. Threading
10. Built in Networking

Tell me something about HTTP?

The Hypertext Transfer Protocol (HTTP) is an Internet protocol that describes a method for sending all types of files (e.g., text, graphic images, sound, video) over the Internet.
The HTTP is a generic, stateless application level protocol which has applications for many other tasks besides hypertext mode, such as name servers and distributed object management systems, through extension of its request methods, error codes and headers.
A clear and concise description of the protocol can be found at: HTTP Made Really Easy: A Practical Guide to Writing Clients and Servers. The full protocol is available in RFC2616.

Hyper Text Transfer Protocol (HTTP):
 
Web applications use the HTTP to move the data between the browser running on your computer and application running on the server.

Stateful protocols:
 
Many server applications communicate using protocols other than HTTP.
Some of these maintain an ongoing connection between the computers. The application server knows exactly who is connected at all times and can tell when a connection is dropped. Because they know the state of each connection and the identity of each person using it, these are known as stateful protocols.

Stateless protocols:
 
HTTP is known as a stateless protocol. An HTTP server will accept any request from any client and will always provide some type of response, even if the response is just to say no. Without the overhead of negotiating and retaining a connection, stateless protocols can handle a large volume of requests. This is one reason why the Internet has been able to scale to millions of computers.
Another reason HTTP has become the universal standard is its simplicity.
An HTTP request looks like an ordinary text document. This has made it easy for applications to make HTTP requests. You can even send an HTTP request by hand using a standard utility such as Telnet. When the HTTP response comes back, it is also in plain text that developers can read.

Related Reference: For a list of HTTP Error Code refer to the article published at HTTP Error Codes

Difference between JRE and JDK

Some people are confused about the functionality of JRE and JDK. Many times I am confused about JRE and JDK when I install Java. So here are a few points about JRE and JDK.

What is JRE?
 
The Java virtual machine is used to compile the Java program which converts source code to byte code (a readable form of machine language). This byte code varies from one platform to platform.
Here JRE is used as a interpreter of byte code into machine code. So JRE is a interpreter for the Java program.
Now we can see what JDK is
JDK contains software development tools which are used to compile and run the Java program.
Both JDK and JRE contains the JVM.
JRE contains the runtime environment such as JVM and other Java classes (AWT, SWING), but does not contain any development tools such as a compiler or a debugger.
In a previous article, Mr Akshaya Bhatia, wrote about the basic tools of JDK. Please refer to this article since it has more details which are not included here.

Summary
 
The Java Virtual Machine's (JVM) function is to load the appropriate class files for executing a Java Program, and then to execute it.
The Java Runtime Environment (JRE) includes the JVM, as the JRE provides some standard libraries and the JVM which can be used to execute a Java program.
The Java Developers Kit (JDK) also includes the JVM, standard class libraries, and several other tools that a developer needs in order to create a Java program.

Connect the Database through JDBC in Java

Java Database Connectivity (JDBC) is a Java based API that is primarily used in programming of Java applications for interfacing with various SQL supporting databases and other data sources such as spreadsheets or flat files.
Java Database Connectivity (JDBC) is one of the Application Program Interface (API) specifications that allow a user to utilize SQL for connecting Java programs to a database.
JDBC is a call-level interface that allows programmers to write Java applications that execute SQL commands on an external database. Using standard library routines, the Java program connects to the database, then uses JDBC to send queries and update code to the database. The program retrieves and processes the results received from the database in answer to the queries, and then closes the connection to the database.
Since Java runs on most platforms, JDBC makes it possible to write a single Java application that will run on multiple platforms and interact with different databases.
JDBC was developed by JavaSoft, a subsidiary of Sun Microsystems.

Steps to use JDBC in a Java Program

1) The JDBC facilitates the connection to a database through a "Connection object" which is initiated through a "DriverManager object".
2) The Connection object is used to create a "Statement object" for SQL query.
3) The Statement object is used to execute the SQL query to return the results through "ResultSet object".
4) Using the ResultSet object, the results of the query can be displayed by looping through the retrieved record sets.

JDBC Components

JDBC is comprised of the following components:
  • JDBC API — provides programmatic access to relational data from the Java programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.
-Note- The JDBC API is included in both Java EE (Enterprise Edition) and Java SE (Standard Edition). The JDBC API (current version 4.0) is part of the two Java packages,namely, java.sql and javax.sql which are available both in Java EE as well as Java SE.
The JDBC API can be used for both two-tier as well as three-tier processing models for database access.
The two-tier model is typical client-server architecture in which the user’s machine is the client and the data source resides on the server. By the application of a JDBC driver in a Java application, the user on the client can communicate directly with the data source on the server.
The three-tier model involves middleware, where the data source processes the commands and via middleware, the data is sent to the client. The middle tier, which acts as middleware, can be developed using the Java platform. Using this middle tier, the JDBC API can facilitate access to a data source. A middle tier application, developed using Java programming language, can add inbuilt features of multithreading and security in the Java application. The three-tier model normally offers better control over data updates and data security.
  • JDBC DriverManager class — defines objects which can connect Java applications to a JDBC driver.
  • JDBC Test Suite — used to determine that JDBC drivers will run your program.
  • JDBC-ODBC Bridge — provides JDBC access via ODBC drivers. The ODBC binary code must be loaded onto each client machine that uses this driver.
Since ODBC ( Open Database Connectivity ) is a very popular API for database connectivity and the OBDC drivers are available for most of the data sources and database management systems, the JDBC-ODBC bridge is particularly useful on a network where client installation is not an issue, and also, for implementing a three-tier architecture while coding an application server in Java.

//PACKAGE STATEMENTS
package com.marks.db;
/**
* @author Achappan M
* created on 26/04/2008 
*/
//IMPORT STATEMENTS
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
/**
* This Class is used to create the jdbc connection 
* and use the query for select, update, delete
*/
public class DBConnection {
//intialise the Logger for this Class
static Logger mLogger = Logger.getLogger(DBConnection.class.getPackage().getName());
//this method is used to get Create connection from postgre sql driver
public static Connection getConnection() {
Connection connection = null;
try{
//load the pgsql driver
Class.forName("org.postgresql.Driver");
System.out.println("Hi Achappan!! your pgsql driver Loaded Successfully");
// create the datasource
String url = "jdbc:postgresql://10.2.0.5:5432/acti"; System.out.println("Print URL " + url);
// register the driver in Driver Manager and establish the connection from them
connection = DriverManager.getConnection(url, "postgres", "postgres");
System.out.println("Connection Established");
}
catch(Exception exception)
{
System.out.println(exception.getMessage()); }
return connection;
}
//it is used to close the connection
public static void closeConnection(Connection pConnection)
          {
try{
                  if (pConnection != null){
                  pConnection.close();
                  pConnection = null;
}
}
               catch (Exception e){
               System.out.println("Error occured while closing the exception  " + e.getMessage());
} }
/**
* This function is used to Close the statement.
* @param pStatement
*/
public static void closeStatement(Statement pStatement) throws BusinessException
          {
        try{
                  if (pStatement != null)
                  {
pStatement.close(); pStatement = null; } }
              catch (SQLException e)
              {
mLogger.error(new StringBuffer("SQLException while trying to closeStatement in DBAccess: "));
throw new BusinessException("SQLException while trying to closeStatement in DBAccess: " + e.getMessage(), e.getStackTrace());
}
}
/** * This function is used to close the resultset. * @param pResultSet */
public static void closeResultSet(ResultSet pResultSet) throws BusinessException
          {
try
                      {
                       if (pResultSet != null)
                              {
                          pResultSet.close();
pResultSet = null; }
}
                     catch (SQLException e)
                     {
mLogger.error(new StringBuffer("SQLException while trying to closeResultSet in DBAccess: "));
e.printStackTrace();
throw new BusinessException("SQLException while trying to closeResultSet in DBAccess: " + e.getMessage(), e.getStackTrace());
} }
public static void main(String[] args) { DBConnection.getConnection(); } }

Java Database Connectivity

Java Database Connectivity (JDBC) is a Java based API that is primarily used in programming of Java applications for interfacing with various SQL supporting databases and other data sources such as spreadsheets or flat files.
Java Database Connectivity (JDBC) is one of the Application Program Interface (API) specifications that allow a user to utilize SQL for connecting Java programs to a database.
JDBC is a call-level interface that allows programmers to write Java applications that execute SQL commands on an external database. Using standard library routines, the Java program connects to the database, then uses JDBC to send queries and update code to the database. The program retrieves and processes the results received from the database in answer to the queries, and then closes the connection to the database.
Since Java runs on most platforms, JDBC makes it possible to write a single Java application that will run on multiple platforms and interact with different databases.
JDBC was developed by JavaSoft, a subsidiary of Sun Microsystems.

Steps to use JDBC in a Java Program

1) The JDBC facilitates the connection to a database through a "Connection object" which is initiated through a "DriverManager object".
2) The Connection object is used to create a "Statement object" for SQL query.
3) The Statement object is used to execute the SQL query to return the results through "ResultSet object".
4) Using the ResultSet object, the results of the query can be displayed by looping through the retrieved record sets.

JDBC Components

JDBC is comprised of the following components:
  • JDBC API — provides programmatic access to relational data from the Java programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.
-Note- The JDBC API is included in both Java EE (Enterprise Edition) and Java SE (Standard Edition). The JDBC API (current version 4.0) is part of the two Java packages,namely, java.sql and javax.sql which are available both in Java EE as well as Java SE.
The JDBC API can be used for both two-tier as well as three-tier processing models for database access.
The two-tier model is typical client-server architecture in which the user’s machine is the client and the data source resides on the server. By the application of a JDBC driver in a Java application, the user on the client can communicate directly with the data source on the server.
The three-tier model involves middleware, where the data source processes the commands and via middleware, the data is sent to the client. The middle tier, which acts as middleware, can be developed using the Java platform. Using this middle tier, the JDBC API can facilitate access to a data source. A middle tier application, developed using Java programming language, can add inbuilt features of multithreading and security in the Java application. The three-tier model normally offers better control over data updates and data security.


  • JDBC DriverManager class — defines objects which can connect Java applications to a JDBC driver.
  • JDBC Test Suite — used to determine that JDBC drivers will run your program.
  • JDBC-ODBC Bridge — provides JDBC access via ODBC drivers. The ODBC binary code must be loaded onto each client machine that uses this driver.
Since ODBC ( Open Database Connectivity ) is a very popular API for database connectivity and the OBDC drivers are available for most of the data sources and database management systems, the JDBC-ODBC bridge is particularly useful on a network where client installation is not an issue, and also, for implementing a three-tier architecture while coding an application server in Java.
//PACKAGE STATEMENTS
package com.marks.db;
/**
* @author Achappan M
* created on 26/04/2008 
*/
//IMPORT STATEMENTS
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
/**
* This Class is used to create the jdbc connection 
* and use the query for select, update, delete
*/
public class DBConnection {
//intialise the Logger for this Class
static Logger mLogger = Logger.getLogger(DBConnection.class.getPackage().getName());
//this method is used to get Create connection from postgre sql driver
public static Connection getConnection() {
Connection connection = null;
try{
//load the pgsql driver
Class.forName("org.postgresql.Driver");
System.out.println("Hi Achappan!! your pgsql driver Loaded Successfully");
// create the datasource
String url = "jdbc:postgresql://10.2.0.5:5432/acti"; System.out.println("Print URL " + url);
// register the driver in Driver Manager and establish the connection from them
connection = DriverManager.getConnection(url, "postgres", "postgres");
System.out.println("Connection Established");
}
catch(Exception exception)
{
System.out.println(exception.getMessage()); }
return connection;
}
//it is used to close the connection
public static void closeConnection(Connection pConnection)
          {
try{
                  if (pConnection != null){
                  pConnection.close();
                  pConnection = null;
}
}
               catch (Exception e){
               System.out.println("Error occured while closing the exception  " + e.getMessage());
} }
/**
* This function is used to Close the statement.
* @param pStatement
*/
public static void closeStatement(Statement pStatement) throws BusinessException
          {
        try{
                  if (pStatement != null)
                  {
pStatement.close(); pStatement = null; } }
              catch (SQLException e)
              {
mLogger.error(new StringBuffer("SQLException while trying to closeStatement in DBAccess: "));
throw new BusinessException("SQLException while trying to closeStatement in DBAccess: " + e.getMessage(), e.getStackTrace());
}
}
/** * This function is used to close the resultset. * @param pResultSet */
public static void closeResultSet(ResultSet pResultSet) throws BusinessException
          {
try
                      {
                       if (pResultSet != null)
                              {
                          pResultSet.close();
pResultSet = null; }
}
                     catch (SQLException e)
                     {
mLogger.error(new StringBuffer("SQLException while trying to closeResultSet in DBAccess: "));
e.printStackTrace();
throw new BusinessException("SQLException while trying to closeResultSet in DBAccess: " + e.getMessage(), e.getStackTrace());
} }
public static void main(String[] args) { DBConnection.getConnection(); } }

Static Variables and Methods in Java

In place of global variables as in C/C++, Java allows variables in a class to be declared static:
 public class A 
 {
   static int k_var;
  }
A single memory location is assigned to this variable and it exists and is accessible even when no instances of class A are created.
These static variable is also called class variables, since they belong to the class as a whole.
If a class property is also declared final, then it becomes a global constant (i.e. can't be altered):
  public class A
 {
    final static int k_var;
 }
Similarly, methods can also be declared static, and are called class methods
  public class A {
   static void A_method(float x){ }
  }   
These class methods also can be called even when no instance of the class exists. The code in a class method can only refer to static variables and the argument variables.

Run the Java Servlet

Deploy your application in Server:
 Write the following sample code.
  
 //package a;
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;


 public class FirstServlet extends HttpServlet {
   protected void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException, IOException
  {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      
      out.println("<html>");
      out.println("<body>");
      out.println("This is my first SERVLET EVER");
      out.println("</body> </html>");
      out.close();
  }
 } 
 Enter the entry for servlet file in web.xml
 E.g., 
 
 <servlet>
   <servlet-name>FirstServlet</servlet-name>
   <servlet-class>com.sample.FirstServlet</servlet-class>
 </servlet> 

 <servlet-mapping> 
   <servlet-name>FirstServlet</servlet-name>
   <url-pattern>/FirstServlet</url-pattern>
 </servlet-mapping>


 deploy the application in two ways.
 1. Manually create the .war file
 2. write ant script to deploy
 For Apache-Tomcat server application will be deployed on WebApps folder.
 For JBoss application will be deployed on server/default/deploy/MyApp.war

 WAR directory structure:
    
 MyApp.war -- contains WEB-INF folder and .jsp files
            --  WEB-INF Contains classes folder, web.xml, lib folder
 
Run on Browser:
 Now Start your server.
 Run your application on browser like http://localhost:8080/MyApp/login.jsp
   
 Otherwise you can run Directly a Servlet file.
 http://localhost:8080/MyApp/FirstServlet