0% found this document useful (0 votes)
6 views

Unit-V Java

Uploaded by

Prabhu B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit-V Java

Uploaded by

Prabhu B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

IT T45- Java Programming

Unit: V
RMI- JDBC- Developing Java Program for RMI and JDBC.

5.1 Remote Method Invocation

RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in
one system (JVM) to access/invoke an object running on another JVM. RMI is used to build
distributed applications; it provides remote communication between Java programs. It is provided in the
package java.rmi.

5.1.1 Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on the server) and
a client program (resides on the client).
 Inside the server program, a remote object is created and reference of that object is made available for
the client (using the registry).
 The client program requests the remote objects on the server and tries to invoke its methods.

The following diagram (Fig 5.1) shows the architecture of an RMI application.

Fig 5.1 Architecture of an RMI Application


The components of the RMI architecture are

 Transport Layer − This layer connects the client and the server. It manages the existing connection and
also sets up new connections.

 Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system;
it acts as a gateway for the client program.

 Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to
pass request to the remote object.

 RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to
the remote object.

SMVEC-Department of Information Technology Page 1


IT T45- Java Programming

5.1.2 Working of an RMI Application


 When the client makes a call to the remote object, it is received by the stub which eventually passes this
request to the RRL.

 When the client-side RRL receives the request, it invokes a method called invoke() of the
object remoteRef. It passes the request to the RRL on the server side.

 The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally
invokes the required object on the server.

 The result is passed all the way back to the client.


5.1.3 Marshalling and Unmarshalling
Whenever a client invokes a method that accepts parameters on a remote object, the
parameters are bundled into a message before being sent over the network. These parameters may be of
primitive type or objects. In case of primitive type, the parameters are put together and a header is attached
to it. In case the parameters are objects, then they are serialized. This process is known as marshalling.

At the server side, the packed parameters are unbundled and then the required method is
invoked. This process is known as unmarshalling.

5.1.4 RMI Registry


bind ( ) - RMI registry is a namespace on which all server objects are placed. Each time the server creates
an object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are
registered using a unique name known as bind name.

lookup( )- To invoke a remote object, the client needs a reference of that object. At that time, the client
fetches the object from the registry using its bind name (using lookup() method).

The following illustration explains the entire process −

Fig 5.2 Working of RMI

SMVEC-Department of Information Technology Page 2


IT T45- Java Programming

5.1.5 Goals of RMI


 To minimize the complexity of the application.
 To preserve type safety.
 Distributed garbage collection.
 Minimize the difference between working with local and remote objects.

5.2 Developing java program for RMI

The steps that are to be followed to write the RMI program:


1. Create the remote interface
2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

Fig 5.3 RMI example

5.2.1 Creating the remote interface


For creating the remote interface, extend the Remote interface and declare the RemoteException
with all the methods of the remote interface. Here, we are creating a remote interface that extends the
Remote interface. There is only one method named add( ) and it declares RemoteException.

Adder.java
import java.rmi.*;
public interface Adder extends Remote
{
public int add(int x,int y)throws RemoteException;
public int sub(int x,int y)throws RemoteException;

}
5.2.2 Provide the implementation of the remote interface
For providing the implementation of the Remote interface, we need to Either extend the
UnicastRemoteObject class,or use the exportObject() method of the UnicastRemoteObject class.In
case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.

SMVEC-Department of Information Technology Page 3


IT T45- Java Programming

AdderRemote.java
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder
{
AdderRemote()throws RemoteException
{
super( );
}
public int add(int x,int y)
{
return x+y;
}
public int add(int x,int y)
{
return x-y;
}
}

5.2.3 Create the stub and skeleton objects using the rmic tool.
The rmic tool invokes the RMI compiler and creates stub and skeleton objects.

>rmic AdderRemote

5.2.4 Start the registry service by the rmiregistry tool


If we don't specify the port number, it uses a default port number. In this example, we are using the port
number 5000.
>start rmiregistry

5.2.5 Create and run the server application


Now rmi services need to be hosted in a server process. The Naming class provides methods to
get and store the remote object.In this example, we are binding the remote object by the name addition.
MyServer.java
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer
{
public static void main(String args[])
{
try
{
AdderRemote stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
System.out.println(“Server is Ready”);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

SMVEC-Department of Information Technology Page 4


IT T45- Java Programming

5.2.6 Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client applications,
in the same machine so we are using localhost. If you want to access the remote object from another
machine, change the localhost to the host name (or IP address) where the remote object is located.

MyClient.java
import java.rmi.*;
public class MyClient
{
public static void main(String args[])
{
try
{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/addition");
System.out.println(“The sum is “+stub.add(34,4));
System.out.println (“The Difference is”+stub.sub(20,10));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
For running this rmi example,

1. compile all the java files

javac *.java

2.create stub and skeleton object by rmic tool

rmic AdderRemote

3.start rmi registry in one command prompt

start rmiregistry

4.start the server in another command prompt

java MyServer

5.start the client application in another command prompt

java MyClient

The sum is :38

The Difference is:10

SMVEC-Department of Information Technology Page 5


IT T45- Java Programming

5.3 Java Database Connectivity


JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases. It is
a part of JavaSE (Java Standard Edition).JDBC API uses JDBC drivers to connect with the database.
There are four types of JDBC drivers:
 JDBC-ODBC Bridge Driver,
 Native Driver,
 Network Protocol Driver, and
 Thin Driver
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables, such
as Java Applications,Java Applets,Java Servlets,Java ServerPages (JSPs),Enterprise JavaBeans (EJBs).
5.3.1 What is API
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs can follow
to communicate with each other. An API can be created for applications, libraries, operating systems,
etc.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage. By the help of JDBC API, we can save, update, delete and fetch data
from the database.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables, such
as :
 Java Applications
 Java Applets
 Java Servlets
 Java Server Pages (JSPs)
 Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.

Fig 5.4 JDBC Connectivity

SMVEC-Department of Information Technology Page 6


IT T45- Java Programming

5.3.2 JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers :

 JDBC API: This provides the application-to-JDBC Manager connection.


 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases. Following is the architectural diagram, which shows the location of the
driver manager with respect to the JDBC drivers and the Java application.

Fig 5.5 JDBC Architecture

5.3.3 Common JDBC Components

The JDBC API provides the following interfaces and classes −


 Driver Manager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication sub protocol.
 Driver: This interface handles the communications with the database server.The Driver
Manager objects, which manages the objects of this type.
 Connection: This is an interface with all methods for contacting a database. The connection
object represents all communication with database is through connection object only.
 Statement: The objects created from this interface are used to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
 ResultSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
 SQLException: This class handles any errors that occur in a database application.

SMVEC-Department of Information Technology Page 7


IT T45- Java Programming

5.3.4 JDBC Drivers

JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC
drivers:

1. Type-1 driver or JDBC-ODBC bridge driver


2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

Type-1 driver

Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-1 driver is also
called Universal driver because it can be used to connect to any of the databases.

 As a common driver is used in order to interact with different databases, the data transferred
through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.

Type-2 driver

The Native API driver uses the client -side libraries of the database. This driver converts JDBC method
calls into native calls of the database API. In order to interact with different database, this driver needs
their local API, that’s why data transfer is much more secure as compared to type-1 driver.

 Driver needs to be installed separately in individual client machines


 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver

SMVEC-Department of Information Technology Page 8


IT T45- Java Programming

Type-3 driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. Here all the database connectivity drivers are
present in a single server, hence no need of individual client-side installation.

 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

Type-4 driver
Type-4 driver is also called native protocol driver. This driver interact directly with database. It does
not require any native database library, that is why it is also known as Thin Driver.

 Does not require any native library and Middleware server, so no client-side or server-side
installation.
 It is fully written in Java language, hence they are portable drivers.

SMVEC-Department of Information Technology Page 9


IT T45- Java Programming

5.3.5 Steps to connect a Java Application to Database

The following 5 steps are the basic steps involve in connecting a Java application with Database using
JDBC

1. Register the Driver- Class.forName() is used to load the driver class explicitly.
2. Create a Connection- getConnection() method of DriverManager class is used to create a
connection.

Syntax
 getConnection(String url)
 getConnection(String url, String username, String password)
 getConnection(String url, Properties info)

3. Create SQL Statement- createStatement() method is invoked on current Connection object to


create a SQL Statement.

Syntax:
public Statement createStatement() throws SQLException

4. Execute SQL Statement-executeQuery() method of Statement interface is used to execute SQL


statements.
Syntax:
public ResultSet executeQuery(String query) throws SQLException

5. Closing the connection-After executing SQL statement you need to close the connection and
release the session. The close() method of Connection interface is used to close the connection.

Syntax:
public void close() throws SQLException

5.3.3 Java Program for JDBC Connectivity

The following SQL statement creates a table named student with three columns −

SMVEC-Department of Information Technology Page 10


IT T45- Java Programming

SQL> CREATE TABLE student


(
id INT NOT NULL,
name VARCHAR(255),
dept VARCHAR(255),
PRIMARY KEY ( id )
);

The following SQL INSERT statement inserts a new row in the student database created earlier SQL>

INSERT INTO student VALUES (101, 'Neha', 'IT');


INSERT INTO studentVALUES (102, 'Zara', 'IT');

The JDBC program which access the data inserted into the student table and displays the data from the
database

OracleCon.Java
import java.sql.*;
class OracleCon
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system", "root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next( ))
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3) );
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

SMVEC-Department of Information Technology Page 11


IT T45- Java Programming

Two Marks
1. Write in brief about the working principle of the RMI.
RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM. RMI is
used to build distributed applications; it provides remote communication between Java programs.
It is provided in the package java.rmi.

2. What do you mean by Stub and Skeleton?


Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system;
it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to
pass request to the remote object.

3. What do you mean by Marshalling and Unmarshalling?


Whenever a client invokes a method that accepts parameters on a remote object, the
parameters are bundled into a message before being sent over the network. These parameters may be of
primitive type or objects. In case of primitive type, the parameters are put together and a header is attached
to it. In case the parameters are objects, then they are serialized. This process is known as marshalling.

At the server side, the packed parameters are unbundled and then the required method is
invoked. This process is known as unmarshalling.

4. What is the need of RMI in network communication?


It is a mechanism that allows an object residing in one system (JVM) to access/invoke an
object running on another JVM. RMI is used to build distributed applications; it provides remote
communication between Java programs.
5. To minimize the complexity of the application.
6. To preserve type safety.
7. Distributed garbage collection.
8. Minimize the difference between working with local and remote objects.

9. How data base connectivity is achieved in java?


JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.
It is a part of JavaSE (Java Standard Edition).JDBC API uses JDBC drivers to connect with the
database.

10. What is the need of JDBC in developing applications?


The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage. By the help of JDBC API, we can save, update, delete and fetch data
from the database.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
SMVEC-Department of Information Technology Page 12
IT T45- Java Programming

11. What are the JDBC related classes

 Statement.
 PreparedStatement.
 CallableStatement.
 ResultSet.
 Connection
 SQLException
12. List out the different types of Drivers in JDBC
There are 4 types of JDBC drivers:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver
Type-3 driver or Network Protocol driver
Type-4 driver or Thin driver

SMVEC-Department of Information Technology Page 13

You might also like