You are on page 1of 18

CIA 1 Middleware Technologies

 Transactional processing monitors:


 A database can reduce the amount of code necessary in a large application by about
40 %. It takes care of all aspects related to data management, from physical storage
to concurrency control(many servers can be connected in parallel to the same
database and the database will still have correct data) and recovery(if a server fails
in the middle of an operation, the database makes sure this does not affect the data
or other servers).
 Unfortunately, these properties are provided only to operations performed within
the database. In principle, they do not apply when:
o An operation spawns several databases
o The operations access data not in the database (e.g., in the server)
 To help with this problem, the Distributed Transaction processing Model was
created by X/Open (a standard’s body). The heart of this model is the XA interface
for 2 Phase Commit, which can be used to ensure that an operation spawning
several databases enjoy the same atomicity properties as if 1 database.
 Dbs follow single thread execution model where a client can have only one
outstanding call to one server only.
 Databases provide no mechanism to bundle together several requests into a single
work unit .
 The XA interface solves this problem for databases by providing an interface that
supports a 2 Phase Commit protocol. However, without any further support, the
client becomes the one responsible for running the protocol which is highly
impractical.
 2 Phase Commit:
o Coordinator send PREPARE to all participants.
o Upon receiving a PREPARE message, a participant sends a message with YES
or NO (if the vote is NO, the participant aborts the transaction and stops).
o Coordinator collects all votes:
All YES = Commit and send COMMIT to all others.
Some NO = Abort and send ABORT to all which voted YES.
o A participant receiving COMMIT or ABORT messages from the coordinator
decides accordingly and stops.
 To run 2 Phase Commit:
o Control of participants-keep track of participated ones
o Make sure the same participant isn’t invoked several times
o Transactional protocols
 TP monitor functionalities:
o It is os built on another os. Not suitable for transactional processing.
o Very much system dependent and not well defined.
o It is meant to improve the existing systems
o It provides clean data exchange in a heterogeneous environment ensuring
acid properties.
o It is an integration tool that let’s designers tie up systems of a
heterogeneous environment.
o It manages, controls distributed applications performing load-balancing,
recovery of components,scheduling..etc
 Two-Phase Locking –A transaction is said to follow the Two-Phase Locking protocol if
Locking and Unlocking can be done in two phases. 
o Growing Phase: New locks on data items may be acquired but none can be
released.
o Shrinking Phase: Existing locks may be released but no new locks can be
acquired.

 COM:
 Developed by microsoft in 1993 which is an interface to design sw components. It
helps in intercommunication irrespective of any programming language.
 It provides effective communication between components. Provides reusability of
code just like modules.
 Also used in the creation of dynamic objects with certain binary standards and also
creates pointers.
 DCOM:
 Designed for distributed applications. It was also called as “Network OLE”
before.it came into existence to serve the needs not fulfilled by COM.
 It helps remote object to run by ORPC protocol.10 million people use of
Windows every day in networked environments DCOM
 Supports dynamic object creation and activation and help components
engage with each other.
 It has garbage collector that enhances cpu utilization.

 Different Types of Middleware

1] Message Oriented Middleware (MOM)

 Message Oriented Middleware (MOM) is a term used to refer to a software infrastructure


which is designed to offer the provision for messages to be sent and received over diff
platforms,diff newtwork protocols,os,languages.
 MOM provides asynchronous communication, and it just sends the message and performs
its asynchronous operations.
 So asynchronous system consists of a message queue that provides a temporary stage so
that the destination program becomes busy or might not be connected. Message Queue
helps in storing the message on a MOM platform. MOM clients can send and receive the
message through the queue.
 Ex- messaging queues ll
2] Remote Procedure Call (RPC) Middleware

Just as the name suggests, RPC calls procedures on remote systems and is designed to perform
synchronous as well as asynchronous interactions between applications or systems.

3] Database Middleware

Database middleware is a type of middleware that allows direct access to databases. It is designed to
provide direct interaction with databases, and offers multiple database gateways and options for
connectivity.

Examples of database-oriented middleware include ODBC, JDBC and transaction processing


monitors.

4] Application Programming Interface (API)


Application Programming Interface or API is a term used to refer to tools, definitions and protocols
which assist developers in application development. APIs also allow applications to communicate
with each other through a common layer.

Sharing flight information between airlines and travel sites. Using Google Maps in a rideshare app.

5] Object Middleware

Also referred to as “Object Request Broker (ORB)“, Object middleware is designed to manage
communication between all objects in a distributed computing system. Sends and receives objects in
an object oriented system.

6] Transaction Processing (TP) Middleware

The purpose of Transaction Processing (TP) Middleware is used in transaction processing monitors.
Its purpose is to provide the environment for development and deployment of disparate
applications. It also encompasses web-application servers.
 RPC:
 Remote Procedure Call (RPC) is a communication technology that is used by one
program to make a request to another program for utilizing its service on a network without
even knowing the network’s details.
 A function call or a subroutine call are other terms for a procedure call.
 It is based on the client-server concept. The client is the program that makes the
request, and the server is the program that gives the service.
Working Procedure for RPC Model:
 The process arguments are placed in a precise location by the caller when the procedure
needs to be called.
 Control at that point passed to the body of the method, which is having a series of
instructions.
 The procedure body is run in a recently created execution environment that has
duplicates of the calling instruction’s arguments.

 The call to a procedure is possible only for those procedures that are not within the
caller’s address space because both processes (caller and callee) have distinct address
space and the access is restricted to the caller’s environment’s data and variables from
the remote procedure.
 The caller and callee processes in the RPC communicate to exchange information via the
message-passing scheme.
 The first task from the server-side is to extract the procedure’s parameters when a
request message arrives, then the result, send a reply message, and finally wait for the
next call message.
 Only one process is enabled at a certain point in time.
 The caller is not always required to be blocked.
 The asynchronous mechanism could be employed in the RPC that permits the client to
work even if the server has not responded yet.
 In order to handle incoming requests, the server might create a thread that frees the
server for handling consequent requests.
 RMI:
 Defining a remote interface

import java.rmi.Remote;

public interface Addition extends Remote{


   public int add(int a,int b) throws RemoteException;
}

 Implementing the remote interface.

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class rmiimplementation extends UnicastRemoteObject implements addition {


  
        public rmiimplementation() throws RemoteException{}
            public int add(int a,int b){
                return(a+b);    
  }
}

 Creating Stub and Skeleton objects from the implementation class using rmic (RMI
compiler)
 Start the rmiregistry
 Create and execute the server application program

import java.rmi.*;
import java.net.*;
public class Addserver{
    public static void main(String[] args) {
        try{
            rmiimplementation locobj=new rmiimplementation();
            Naming.rebind("rmi:///addition", locobj);
    }
        catch(RemoteException re){
            re.printStackTrace();
    }
        catch(MalformedURLException mfe){
            mfe.printStackTrace();
    }
  }
}

 Create and execute the client application program.

import java.rmi.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class Addclient{


    public static void main(String[] args) {
        String host="localhost";
        Scanner s=new Scanner(System.in);
        System.out.println("Enter first no:");
        int a=s.nextInt();
        System.out.println("Enter second no:");
        int b=s.nextInt();
        try{
            addition  rmiobj=(addition)Naming.lookup("rmi://"+host+"/addition");
            System.out.println(rmiobj.add(a, b));

    }
        catch(RemoteException re){
            re.printStackTrace();
    }
        catch(NotBoundException nbe){
            nbe.printStackTrace();
    }
        catch(MalformedURLException mfe){
            mfe.printStackTrace();
    }
  }
}

 Architecture of an RMI Application


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

 Working of an RMI Application


o The following points summarize how an RMI application works −
o When the client makes a call to the remote object, it is received by the stub which
eventually passes this request to the RRL.
o 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.
o 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.
 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.

 RMI Registry

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.
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).

 Socket Programming using UDP 1 way communication:


 Java provides DatagramSocket to communicate over UDP instead of TCP. It is also
built on top of IP. DatagramSockets can be used to both send and receive packets over the
Internet.
 UDP is loss-tolerant but delay-resistant.Ex: live coverage, multi-player gaming.
 This is a simple implementation of one-sided client-server program wherein the
client sends messages to server and server just prints it until the client sends “bye”.
 Client side Implementation:

// Java program to illustrate Client side


// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
  
public class udpBaseClient_2
{
    public static void main(String args[]) throws IOException
    {
        Scanner sc = new Scanner(System.in);
  
        // Step 1:Create the socket object for
        // carrying the data.
        DatagramSocket ds = new DatagramSocket();
  
        InetAddress ip = InetAddress.getLocalHost();
        byte buf[] = null;
  
        // loop while user not enters "bye"
        while (true)
        {
            String inp = sc.nextLine();
  
            // convert the String input into the byte array.
            buf = inp.getBytes();
  
            // Step 2 : Create the datagramPacket for sending
            // the data.
            DatagramPacket DpSend =
                  new DatagramPacket(buf, buf.length, ip, 1234);
  
            // Step 3 : invoke the send call to actually send
            // the data.
            ds.send(DpSend);
  
            // break the loop if user enters "bye"
            if (inp.equals("bye"))
                break;
        }
    }
}

 Server side Implementation:

// Java program to illustrate Server side


// Implementation using DatagramSocket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
  
public class udpBaseServer_2
{
    public static void main(String[] args) throws IOException
    {
        // Step 1 : Create a socket to listen at port 1234
        DatagramSocket ds = new DatagramSocket(1234);
        byte[] receive = new byte[65535];
  
        DatagramPacket DpReceive = null;
        while (true)
        {
  
            // Step 2 : create a DatgramPacket to receive the data.
            DpReceive = new DatagramPacket(receive, receive.length);
  
            // Step 3 : revieve the data in byte buffer.
            ds.receive(DpReceive);
  
            System.out.println("Client:-" + data(receive));
  
            // Exit the server if the client sends "bye"
            if (data(receive).toString().equals("bye"))
            {
                System.out.println("Client sent bye.....EXITING");
                break;
            }
  
            // Clear the buffer after every message.
            receive = new byte[65535];
        }
    }
  
    // A utility method to convert the byte array
    // data into a string representation.
    public static StringBuilder data(byte[] a)
    {
        if (a == null)
            return null;
        StringBuilder ret = new StringBuilder();
        int i = 0;
        while (a[i] != 0)
        {
            ret.append((char) a[i]);
            i++;
        }
        return ret;
    }
}

 Socket Programming using TCP 1 way communication:

Client program:
// A Java program for a Client
import java.net.*;
import java.io.*;
 
public class Client
{
    // initialize socket and input output streams
    private Socket socket            = null;
    private DataInputStream  input   = null;
    private DataOutputStream out     = null;
 
    // constructor to put ip address and port
    public Client(String address, int port)
    {
        // establish a connection
        try
        {
            socket = new Socket(address, port);
            System.out.println("Connected");
 
            // takes input from terminal
            input  = new DataInputStream(System.in);
 
            // sends output to the socket
            out    = new
DataOutputStream(socket.getOutputStream());
        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
 
        // string to read message from input
        String line = "";
 
        // keep reading until "Over" is input
        while (!line.equals("Over"))
        {
            try
            {
                line = input.readLine();
                out.writeUTF(line);
            }
            catch(IOException i)
            {
                System.out.println(i);
            }
        }
 
        // close the connection
        try
        {
            input.close();
            out.close();
            socket.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
 
    public static void main(String args[])
    {
        Client client = new Client("127.0.0.1", 5000);
    }
}
Server program:
// A Java program for a Server
import java.net.*;
import java.io.*;
 
public class Server
{
    //initialize socket and input stream
    private Socket          socket   = null;
    private ServerSocket    server   = null;
    private DataInputStream in       =  null;
 
    // constructor with port
    public Server(int port)
    {
        // starts server and waits for a connection
        try
        {
            server = new ServerSocket(port);
            System.out.println("Server started");
 
            System.out.println("Waiting for a client ...");
 
            socket = server.accept();
            System.out.println("Client accepted");
 
            // takes input from the client socket
            in = new DataInputStream(
                new BufferedInputStream(socket.getInputStream()));
 
            String line = "";
 
            // reads message from client until "Over" is sent
            while (!line.equals("Over"))
            {
                try
                {
                    line = in.readUTF();
                    System.out.println(line);
 
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
            System.out.println("Closing connection");
 
            // close connection
            socket.close();
            in.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
 
    public static void main(String args[])
    {
        Server server = new Server(5000);
    }
}

 Socket Programming using TCP 2 way communication


Client:

import java.net.*;  
import java.io.*;  
class MyClient{  
public static void main(String args[])throws Exception{  
Socket s=new Socket("localhost",3333);  
DataInputStream din=new DataInputStream(s.getInputStream());  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  
String str="",str2="";  
while(!str.equals("stop")){  
str=br.readLine();  
dout.writeUTF(str);  
dout.flush();  
str2=din.readUTF();  
System.out.println("Server says: "+str2);  
}  
  
dout.close();  
s.close();  
}}  
server:

import java.net.*;  
import java.io.*;  
class MyServer{  
public static void main(String args[])throws Exception{  
ServerSocket ss=new ServerSocket(3333);  
Socket s=ss.accept();  
DataInputStream din=new DataInputStream(s.getInputStream());  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
  
String str="",str2="";  
while(!str.equals("stop")){  
str=din.readUTF();  
System.out.println("client says: "+str);  
str2=br.readLine();  
dout.writeUTF(str2);  
dout.flush();  
}  
din.close();  
s.close();  
ss.close();  
}}  

 Socket Programming using UDP 2 way communication


Server:

//if client says stop both exits.


import java.io.*;
import java.net.*;
import java.util.Scanner;
 
class UDPServer_2way
{
   public static void main(String args[]) throws Exception
      {Scanner sc=new Scanner(System.in);
         DatagramSocket serverSocket = new DatagramSocket(9876);
  //Server Socekt Created
 
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  System.out.println("Client: " + sentence);

                if(data(receiveData).toString().equals("stop")){
                    System.out.println("Exiting..");
                    serverSocket.close();
                    break;
                }
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                    String capitalizedSentence=sc.nextLine();
                    if(capitalizedSentence.equals("stop")){
                        break;
                    }
                 // String capitalizedSentence = sentence.toUpperCase();
   //Change sentence to Capital letter
                  sendData = capitalizedSentence.getBytes();
 
                  DatagramPacket sendPacket =
                  new DatagramPacket(sendData, sendData.length, IPAddress,
port);
                  serverSocket.send(sendPacket);
                  receiveData = new byte[1024];
                  sendData = new byte[1024];
   //Send Capitalized data back to client
               }serverSocket.close();
      }
      // A utility method to convert the byte array
    // data into a string representation.
    public static StringBuilder data(byte[] a)
    {
        if (a == null)
            return null;
        StringBuilder ret = new StringBuilder();
        int i = 0;
        while (a[i] != 0)
        {
            ret.append((char) a[i]);
            i++;
        }
        return ret;
    }
}

Client:

import java.io.*;
import java.net.*;
 
class UDPClient_2way
{
   public static void main(String args[]) throws Exception
   {
      BufferedReader inFromUser =
         new BufferedReader(new InputStreamReader(System.in));
 
      DatagramSocket clientSocket = new DatagramSocket();
 //Client Socket is created
 
      InetAddress IPAddress = InetAddress.getByName("localhost");
 //Gets the IP Address
 
      byte[] sendData = new byte[1024];
      byte[] receiveData = new byte[1024];
 while(true){
      String sentence = inFromUser.readLine();
 
      sendData = sentence.getBytes();
 //sends data
 
      DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
      clientSocket.send(sendPacket);
      if(sentence.equals("stop")){
        System.out.println("Exiting..");
        clientSocket.close();
        break;
      }
      DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
      clientSocket.receive(receivePacket);
 
      String modifiedSentence = new String(receivePacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
     
      receiveData = new byte[1024];
     sendData = new byte[1024];
   }clientSocket.close();
}
// A utility method to convert the byte array
    // data into a string representation.
    public static StringBuilder data(byte[] a)
    {
        if (a == null)
            return null;
        StringBuilder ret = new StringBuilder();
        int i = 0;
        while (a[i] != 0)
        {
            ret.append((char) a[i]);
            i++;
        }
        return ret;
    }
}

 JDBC steps:

 Load the packages java.sql.*;


 Register the driver class of database. The driver class translates the api calls to
operations.
 Establish a connection using connection interface.
 Create stmt objects using stmt interface to execute queries.
 Create resultset object from the resultset interface to retrieve data from queries.
 Close the connection.

Program:

import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.cj.jdbc.Driver");

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sam","root","Kaveya1@");

Statement stmt=con.createStatement();

//inserting
//String sql = "INSERT INTO emp VALUES (103, 'Zara')";

// stmt.executeUpdate(sql);

//update

String sql2 ="update emp set ID=104 where Name='Ram'";

stmt.executeUpdate(sql2);

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()) {

System.out.println(rs.getInt(1)+" "+rs.getString(2)); }

con.close();

if(con!=null){

System.out.println("sucess");

catch(Exception e){ System.out.println(e);}  
}  
}  

You might also like