0% found this document useful (0 votes)
187 views32 pages

DS Practical

The document describes programs for implementing concurrent and distributed systems in Java. It includes code for an echo client-server application using threads, remote procedure calls to add two numbers, remote method invocation to lookup prices in a warehouse, and synchronized bank account deposits using threads. The code provided implements the server and client for each example and shows the expected output.

Uploaded by

Kushal Bhatt
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)
187 views32 pages

DS Practical

The document describes programs for implementing concurrent and distributed systems in Java. It includes code for an echo client-server application using threads, remote procedure calls to add two numbers, remote method invocation to lookup prices in a warehouse, and synchronized bank account deposits using threads. The code provided implements the server and client for each example and shows the expected output.

Uploaded by

Kushal Bhatt
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/ 32

ITM Universe, Vadodara

Bachelor of Computer Science, Engineering


SEM-7th 3170719- Distributed System Practical

Practical: 1

Write a Program to implement Concurrent Echo Client Server


Application.

EchoClient.java

import java.io.*;
import java.net.*;

public class EchoClient{


public static void main(String[] args){
try{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do{
line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}while ( !line.trim().equals("bye") );

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

1 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

EchoServer.java

import java.io.*;
import java.net.*;
public class EchoServer{
private ServerSocket server;
public EchoServer(int port){
try{
server = new ServerSocket(port);
}catch(Exception e){
System.out.println(e);
}
}
public void serve(){
try{
while(true){
Socket client = server.accept();
BufferedReader r = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line;
do{
line = r.readLine();
if ( line != null ){
System.out.println(" hi "+ line);
w.println("Got: "+ line);
}
}while (!line.trim().equals("bye"));
client.close();
}
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args){
EchoServer s = new EchoServer(9999);
s.serve();
}
}

2 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Output:

3 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 2

Write a Programs for Remote Procedure call.

AddClient

import java.rmi.Naming;
public class AddClient {
public static void main(String[] args) {
try{
String addServerURL = "rmi://"+"localhost"+"/AddServer";

AddServerIntf addServerIntf =(AddServerIntf)Naming.lookup(addServerURL);

System.out.println("The First Number "+ args[1]);

double d1 = Double.valueOf(args[1]).doubleValue();

System.out.println("The Second Number"+ args[2]);

double d2 = Double.valueOf(args[2]).doubleValue();

System.out.println("The Sum is:"+ addServerIntf.add(d1, d2));

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

4 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

AssServer

import java.rmi.*;

class AddServer{
public static void main(String args[]) {
try{
AddServerImpl addServerImpl = new AddServerImpl();

Naming.rebind("AddServer", addServerImpl);

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

AddServerlmpl

import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf{
public AddServerImpl() throws RemoteException{}

public double add(double d1, double d2) throws RemoteException{


return d1+d2;
}
}

AddServerlntf

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface AddServerIntf extends Remote{


double add(double d1,double d2) throws RemoteException;
}

5 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Output:
Server

Client

6 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 3

Write a program for Remote Method Invocation.

Warehouse.java

import java.rmi.*;

public interface Warehouse extends Remote {


double getPrice(String description) throws RemoteException;
}

WarhouseImpl.java

import java.util.*; import


java.rmi.*; import
java.rmi.server.*;

public class WarehouseImpl extends UnicastRemoteObject implements Warehouse{


private Map<String, Double> prices;
public WarehouseImpl() throws RemoteException{
prices = new HashMap<>();
prices.put("Blackwell Toaster", 24.95); prices.put("ZapXpress
Microwave Oven", 49.95);
}
public double getPrice(String description) throws RemoteException{
Double price = prices.get(description); return price
== null ? 0 : price;
}
}

7 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

WarehouseServer.java

import java.rmi.*; import


javax.naming.*;

public class WarehouseServer{


public static void main(String[] args) throws RemoteException, NamingException{
System.out.println("Constructing server implementation...");
WarehouseImpl centralWarehouse = new WarehouseImpl();
System.out.println("Binding server implementation to registry..."); Context
namingContext = new InitialContext();
namingContext.bind("rmi:Warehouse", centralWarehouse);
System.out.println("Waiting for invocations from clients...");
}
}

WarehouseClient.java

import java.rmi.*;
import java.util.*;
import javax.naming.*;

public class WarehouseClient {


/**
* @param args
* @throws NamingException
* @throws RemoteException
*/
public static void main(String[] args) throws NamingException, RemoteException {
Context namingContext = new InitialContext();
System.out.print("RMI registry bindings: ");

Enumeration<NameClassPair> e = namingContext.list("rmi://localhost/");

while (e.hasMoreElements())
System.out.println(e.nextElement().getName());
String url = "rmi://localhost/Warehouse";
Warehouse centralWarehouse = (Warehouse) namingContext.lookup(url); /*
typecasting to Interface */
String descr = "Blackwell Toaster";
double price = centralWarehouse.getPrice(descr);
System.out.println(descr + ": " + price);
}
}

8 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Output:

Server

Client

9 |P a ge 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 4

Write the programs for thread programming in JAVA.

Deposit.java
import java.io.*;

public class Deposit {


static int balance = 1000;

public static void main(String args[]) {


PrintWriter out = new PrintWriter(System.out, true);
Account account = new Account(out); /* shared object by two threads */
DepositThread first, second;
first = new DepositThread(account, 1000, "#1");
second = new DepositThread(account, 1000, "#2");
first.start(); second.start(); try {
first.join(); second.join();
} catch (InterruptedException e) {
}
out.println("balance " + balance);
}
}

Account.java
import java.io.*;
class Account {
PrintWriter out;

Account(PrintWriter out) { this.out


= out;
}

/* critical section */ synchronized void deposit(int amount, String name) /* locked by


one thread */
{
int balance;
out.println("name " + amount); out.println("getting
balance " + name); balance = getBalance();
out.println("after getting balance " + balance);
balance += amount; setBalance(balance);
out.println("set balance " + Deposit.balance);
}

10 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

int getBalance() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return Deposit.balance;
}
void setBalance(int balance) { try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
Deposit.balance = balance;
}
}

DepositThread.jav

public class DepositThread extends Thread {


Account account; int depositAmount;
String message;

DepositThread(Account account, int amount, String message) {


this.message = message; this.account = account;
this.depositAmount = amount;
}
public void run() {
account.deposit(depositAmount, message);
}
}

Output:

11 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 5

Implement Network File System (NFS).

Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {


private static DataOutputStream dataOutputStream = null;
private static DataInputStream dataInputStream = null;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
System.out.println("listening to port:5000");
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket + " connected\n");
dataInputStream = new DataInputStream(clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
String message;
while (true) {
message = dataInputStream.readUTF();
System.out.println(message);
if (message.equalsIgnoreCase("exit()"))
break;
}
clientSocket.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}

Client.java
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private static DataOutputStream dataOutputStream = null;
private static DataInputStream dataInputStream = null;
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
while (true) {
System.out.print("input> ");
String message = scanner.nextLine();

12 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

dataOutputStream.writeUTF(message);
if (message.equalsIgnoreCase("exit()"))
break;
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
}

Output:
Server

Client

13 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Program II

FileServer_1.java
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import
java.net.ServerSocket; import
java.net.Socket;

public class FileServer_1 extends Thread {

private ServerSocket ss;

public FileServer_1(int port) {


try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}

public void run() {


while (true) {
try {
Socket clientSock = ss.accept();
saveFile(clientSock);
} catch (IOException e) {
e.printStackTrace();
}
}
}

private void saveFile(Socket clientSock) throws IOException {


DataInputStream dis = new
DataInputStream(clientSock.getInputStream());
FileOutputStream fos = new FileOutputStream("testfile_1.jpg");
byte[] buffer = new byte[4096];

int filesize = 15123; // Send file size in separate msg


int read = 0; int
totalRead = 0; int
remaining = filesize;
while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0)
{
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");

14 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

fos.write(buffer, 0, read);
}

fos.close();
dis.close();
}

public static void main(String[] args) {


FileServer_1 fs = new FileServer_1(1988); fs.start();
}
}

FileClient_1.java
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException; import
java.net.Socket;

public class FileClient_1 {

private Socket s;

public FileClient_1(String host, int port, String file) {


try {
s = new Socket(host, port);
sendFile(file);
} catch (Exception e) {
e.printStackTrace();
}
}

public void sendFile(String file) throws IOException {


DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];

while (fis.read(buffer) > 0) {


dos.write(buffer);
}

fis.close();
dos.close();
}

public static void main(String[] args) {


FileClient_1 fc = new FileClient_1("localhost", 1988,
"halloween.jpg");

15 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

}
}

Output:
Server

Client

16 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Program III

Server_filw.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server_file { private static DataOutputStream


dataOutputStream = null; private static DataInputStream
dataInputStream = null;

public static void main(String[] args) { try (ServerSocket


serverSocket = new ServerSocket(5000)) {
System.out.println("listening to port:5000");
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket + " connected.");
dataInputStream = new
DataInputStream(clientSocket.getInputStream());
dataOutputStream = new
DataOutputStream(clientSocket.getOutputStream());

receiveFile("Xenum_1.txt");
receiveFile("account_1.doc");

dataInputStream.close();
dataOutputStream.close(); clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void receiveFile(String fileName) throws Exception {


int bytes = 0;
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
long size = dataInputStream.readLong(); // read file size
byte[] buffer = new byte[4 * 1024];
while (size > 0 && (bytes = dataInputStream.read(buffer, 0, (int) Math.min(buffer.length,
size))) != -1) {
fileOutputStream.write(buffer, 0, bytes);
size -= bytes; // read upto file size
}
fileOutputStream.close();
}
}

17 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Client_file.java
Import java.io.*; import java.net.Socket;

public class Client_file { private static DataOutputStream


dataOutputStream = null; private static DataInputStream
dataInputStream = null;

public static void main(String[] args) {


try (Socket socket = new Socket("localhost", 5000)) {
dataInputStream = new
DataInputStream(socket.getInputStream());
dataOutputStream = new
DataOutputStream(socket.getOutputStream());

sendFile("C:/Java Practicals/File Transfer/Xenum.txt");


sendFile("C:/Java Practicals/File Transfer/account.doc"); //
sendFile("path/to/file2.pdf");

dataInputStream.close();
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void sendFile(String path) throws Exception {


int bytes = 0;
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
// send file size
dataOutputStream.writeLong(file.length());
// break file into chunks byte[] buffer = new
byte[4 * 1024]; while ((bytes = fileInputStream.read(buffer))
!= -1) { dataOutputStream.write(buffer, 0, bytes);
dataOutputStream.flush();
}
fileInputStream.close();
}
}

18 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Output:
Server

Client

19 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 6

Creation of BPEL (Business Process Execution Language) Module and a


Composite Application.
 Business Process Execution Language for Web Services (BPEL or BPEL4WS) is a
language used for the definition and execution of business processes using Web
services. BPEL enables the top-down realization of Service Oriented Architecture
(SOA) through composition, orchestration, and coordination of Web services. BPEL
provides a relatively easy and straightforward way to compose several Web services
into new composite services called business processes.
 In this article, you will learn how to create an example business process that
combines a set of fictional travel-related Web services and then deploy it to the
Oracle BPEL Process Manager runtime environment.
 First, some background. BPEL builds on the foundation of XML and Web services; it
uses an XML-based language that supports the Web services technology stack,
including SOAP, WSDL, UDDI, WS-Reliable Messaging, WS-Addressing, WS-
Coordination, and WS-Transaction.
 BPEL represents a convergence of two early workflow languages: Web Services
Flow Language (WSFL) and XLANG. WSFL was designed by IBM and is based on
the concept of directed graphs. XLANG, a block-structured language, was designed
by Microsoft. BPEL combines both approaches and provides a rich vocabulary for
description of business processes.
 The first version of BPEL was developed in August 2002. Since then, many major
vendors have joined (including Oracle), resulting in several modifications and
improvements, and the adoption of version 1.1 in March 2003. In April 2003, BPEL
was submitted to the Organization for the Advancement of Structured Information
Standards (OASIS) for standardization purposes, and the Web Services Business
Process Execution Language Technical Committee (WSBPEL TC) was formed. This
effort has led to even broader acceptance in industry.
 Within the enterprise, BPEL is used to standardize enterprise application integration
as well as to extend the integration to previously isolated systems. Between
enterprises, BPEL enables easier and more effective integration with business
partners. BPEL stimulates enterprises to further define their business processes,
which in turn leads to business process optimization, reengineering, and the selection
of the most appropriate processes, thus further optimizing the organization.
Definitions of business processes described in BPEL do not affect existing systems,
thereby stimulating upgrades. BPEL is the key technology in environments where
functionalities are already or will be exposed via Web services. With increases in the
use of Web services, the importance of BPEL will increase as well.
 Web services can be combined in two ways:
1. Orchestration-
In orchestration, which is usually used in private business processes, a central
process (which can be another Web service) takes control of the involved Web
services and coordinates the execution of different operations on the Web
services involved in the operation. The involved Web services do not "know"
(and do not need to know) that they are involved in a composition process and
that they are taking part in a higher-level business process. Only the central

20 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

coordinator of the orchestration is aware of this goal, so the orchestration is


centralized with explicit definitions of operations and the order of invocation
of Web services.

Figure 1: Composition of Web Services with Orchestration

2. Choreography-
Choreography, in contrast, does not rely on a central coordinator. Rather, each
Web service involved in the choreography knows exactly when to execute its
operations and with whom to interact. Choreography is a collaborative effort
focusing on the exchange of messages in public business processes. All
participants in the choreography need to be aware of the business process,
operations to execute, messages to exchange, and the timing of message
exchanges.

Figure 2: Composition of Web Services with Choreography

21 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 7

Implement a COBRA file.

Hello.idl
module HelloApp
{
interface Hello
{
string sayHello(); /* declaration of method */
double square(in string number); /* declaration of method */
// oneway void shutdown();
};
};

HelloImpl.java
import HelloApp.*; import
org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*; import
org.omg.PortableServer.*; import
org.omg.PortableServer.POA; import java.util.Properties;

class HelloImpl extends HelloPOA { private


ORB orb;

public void setORB(ORB orb_val) { orb =


orb_val;
}

// implement sayHello() method public


String sayHello() { return "\nHello
world !!\n";
}

// implement square() method public double


square(String number) {
double x = Double.valueOf(number).doubleValue(); /* String to double conversion */
return (double) (x * x);
}
// implement shutdown() method
/*
public void shutdown() {
orb.shutdown(false);
* }
*/ }

22 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

HelloServer.java
import HelloApp.*; import
org.omg.CosNaming.*;
import
org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*; import
org.omg.PortableServer.*; import
org.omg.PortableServer.POA;

public class HelloServer {


public static void main(String args[]) { try {
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// get reference to rootpoa & activate the POAManager
POA rootpoa =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
// create servant and register it with the ORB HelloImpl
helloImpl = new HelloImpl(); helloImpl.setORB(orb);

org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);


Hello href = HelloHelper.narrow(ref);

// get the root naming context


// NameService invokes the name service org.omg.CORBA.Object
objRef = orb.resolve_initial_references("NameService");
// Use NamingContextExt which is part of the Interoperable
// Naming Service (INS) specification.
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
// bind the Object Reference in Naming
String name = "Hello";
NameComponent path[] = ncRef.to_name(name);
ncRef.rebind(path, href);
System.out.println("HelloServer ready and waiting ...");
// wait for invocations from clients
orb.run(); } /* end of try */

catch (Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}

System.out.println("HelloServer Exiting ...");


} /* End of main() */ } /*
End of class */

23 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

HelloClient.java
Import HelloApp.*; import org.omg.CosNaming.*;
import
org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*; import java.util.*;
public class HelloClient {
static Hello helloImpl;

public static void main(String args[]) { try {


// create and initialize the ORB
ORB orb = ORB.init(args, null); //
get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
// Use NamingContextExt instead of NamingContext. This is
// part of the Interoperable naming Service.
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
// resolve the Object Reference in Naming String
name = "Hello";
helloImpl = HelloHelper.narrow(ncRef.resolve_str(name)); /* getting Remote object
*/
System.out.println("Obtained a handle on server object: " + helloImpl);
System.out.println(helloImpl.sayHello()); /* sayHello() is remotely called */
System.out.println("Enter the value ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(helloImpl.square(str)); /* square(str) is remotely called */
// helloImpl.shutdown();
} catch (Exception e) {
System.out.println("ERROR : " + e);
e.printStackTrace(System.out);
}
}}

24 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Output:
Server

Client

25 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Practical: 8

Study of Web Service Programming.

 Web Services
Using Erl’s terminology, this business process can be broken down into two “independent
units of logic”—the Purchase Order Service and theInventory Management Service. As
services participating in an SOA composite application, these “units of logic” can be
described in terms of their input and output messages. The Purchase Order Service (upper-
right corner of Figure 2–1) is responsible for providing the following service:

 Purchase Order Service


I. Input Message: A PO number and a list of items being ordered.
II. Processing: Determine whether the Purchase Order covers the items being ordered
and what payment terms are required.
III. Output Message: An authorization for the items being ordered and a description of
the payment terms required for those items.

As indicated in Figure 2–1, the Purchase Order Service is implemented using Java EE 5.
The other service composed by the Order Management System is the Inventory
Management System. It is responsible for providing the following service:

 Inventory Management Service


I. Input Message: A list of the items being ordered.
II. Processing: Determines whether the items are in stock and when they will be
available to ship.
III. Output Message: A list of the items and their estimated ship dates — referred to as
Item Availability.
The Order Management System, pictured in the centre of Figure 2–1, is described as an
SOA composite application because it is a composite of the underlying services provided
by the Purchase Order Service and the Inventory Management Service. It processes the
incoming Customer Order by invoking first the Purchase Order Service and then the
Inventory Management Service, and combining the information received from those
services to create the Order Confirmation. Notice that this Order Management System itself
can be considered a service. In fact, to the sender of the Customer Order, it is treatedexactly
as any other service. Hence, using SOA, services can be composed of underlying services.
The Order Management Service thus constructed can be described as follows:

 Order Management Service


I. Input Message: A Customer Order containing, among other information, a PO Number,
and a list of Order Items — the products and quantities being ordered.
II. Processing: Determines whether the customer is authorized to purchase the requested
items under the specified PO, and if so, what the payment terms are and when the items
will be available to ship.
III. Output Message: Order Confirmation—detailing the payment terms and the anticipated

26 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

delivery dates for the items. As indicated in Figure 2–1, the Order Management Service
is implemented using Java EE 5.

Figure 3: An SOA composite application for order management

 Basic SOA using REST


The basic tools and techniques for implementing SOA components using the REST
paradigm. REST stands for Representational State Transfer. It was first introduced by
Roy Fielding1 in his 2000 doctoral dissertation [Fielding]. For the past several years, a
great debate has been going on about the merits of the REST versus SOAP architectural
styles for Web Services. It is not my intention, in this book, to weigh in on either side of
that debate. My feeling is that both approaches are useful for implementing SOA
components. For simple applications, REST is an easy way to get started.
 REST
Some readers may wonder why this book starts with REST before discussing SOAP and
WSDL-based Web Services. The reason is that REST is easy to understand. By starting
with REST, I can describe some of the basic SOA
Web Services concepts without getting into the complexities of SOAP and WSDL. Also,
the limitations of REST provide the motivation for introducing SOAP and WSDL.
a. REST-style services (i.e., RESTful services) adhere to a set of constraints and
architectural principles that include the following:

27 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

b. RESTful services are stateless. As Fielding writes in Section 5.1.3 of his thesis, “each
request from client to server must contain all the information necessary to understand
the request and cannot take advantage of any stored context on the server.”
c. RESTful services have a uniform interface. This constraint is usually taken to mean
that the only allowed operations are the HTTP operations: GET, POST, PUT, and
DELETE.
d. REST-based architectures are built from resources (pieces of information) that are
uniquely identified by URIs. For example, in a RESTful purchasing system, each
purchase order has a unique URI.
e. REST components manipulate resources by exchanging representations of the
resources. For example, a purchase order resource can be represented by an XML
document. Within a RESTful purchasing system, a purchase order might be updated by
posting an XML document containing the changed purchase order to its URI.
These are the basic principles behind REST. However, when people talk about the benefits
of RESTful systems today, they usually are not strictly applying these principles. For
example, among REST advocates, keeping shopping cart data on the server and
maintaining a session related to the shopping process that is using the cart is acceptable.2
In fact, the XML/HTTP Binding provided by JAX-WS for implementing RESTful services
provides for session management capabilities using cookies, URL rewriting, and SSL
session IDs.
More significant deviations from Fielding’s definition of REST involve getting around
the “uniform interface” constraint by embedding verbs and parameters inside URLs. The
Amazom.com REST interface, for example, includes verbs in query strings and doesn’t
have unique URIs for each resource. Systems like this, although labelled as RESTful, are
really starting to look very much like RPC using XML over HTTP without SOAP.

RESTful Web Services in contrast to SOAP Web Services. Table illustrates the principal
differences.
Table – RESTful Web Services vs SOAP Web Services
REST SOAP
Message Format XML XML inside a SOAP Envelope
Interface Definition none WSDL
Transport HTTP HTTP, FTP, MIME, JMS, SMTP, etc.
This is consistent with common usage in the REST versus SOAP debates. REST uses
simple XML over HTTP without a WSDL interface definition.

 REST Clients with and without JWS


A basic capability you often need when implementing an SOA Web service is easily
downloading and uploading XML files from/to an HTTP server. For example,
suppose that the OMS runs a nightly batch job and writes all new and changed orders
from the previous day to a set of XML documents that can be accessed using a Web
service named New Orders. The CSS can then, each morning, retrieve those files and
update its Customer History. This is a simple, but common and highly practical, form
of SOA-style loosely coupled integration.

28 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

The next few sections focus on uploading/downloading XML documents with bare-
bones RESTful Web Services. I show how to write clients for RESTful services with
and without JWS. This material may seem very basic to advanced Java programmers,
but it is always good to review the basics before diving into a complex subject like
SOA with Java Web Services.

It is a common misconception that implementing Web Services with Java requires


lots of heavy machinery like JAX-WS. This is not the case, as even J2SE 1.4 provides
powerful tools for HTTP communication and XML processing that enable you to
build and consume RESTful Web services. JAX-WS and the other JWS tools provide
many advantages, of course, which we discuss later in this section and throughout the
rest of this book. Doing REST without JWS gives you a hands-on appreciation for
what HTTP can and cannot do. It quickly becomes clear that, although it is easy to do
simple things without the JWS machinery, as you get more ambitious, you start to
need some more powerful tools to handle invocation, serialization, and the other
components of an SOA Web Services infrastructure. Since this is a book about Java, I
start with the assumption that the EISs have Java APIs for accessing the needed
records. The challenge addressed in the next few sections is to deploy a Java API as a
Web service or to invoke a Web service using Java.

Since this is a book about Java, I start with the assumption that the EISs have Java
APIs for accessing the needed records. The challenge addressed in the next few
sections is to deploy a Java API as a Web service or to invoke a Web service using
Java.
 Getting EIS Records from a REST Service without Using JWS
This section briefly examines how to get an XML document from a RESTful Web
service. In this example, the Web service is accessed with an HTTP GET request. The
client application needs to issue the HTTP GET and process the HTTP response stream
that contains the XML document. Instead of using the JWS APIs (e.g., JAX-WS), I
simply use the javax.net.HttpURLConnection class to handle most of the work related
to generating the HTTP GET and processing the response.

29 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Figure 4: The client uses the HttpURLConnection class to make an HTTP GET
request and receive an HTTP response.

Program 1 shows the client-side code for issuing the HTTP GET request and
receiving the XML document via the HTTP response. Notice that the String used to
construct the URL instance is passed to the client as args[0]. The
HttpULRConnection—con—doesn’t send the HTTP request until its connect ()
method gets invoked. Before this happens, the setRequestMethod() is invoked to
specify that a GET request should be sent.

Program 1 Implementing a Java Client to Download an XML Document from a RESTful


Web Service .
Code:
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println
("Usage: java GetNewOrders <Web Service URL>");
System.exit(1);
}
// Create the HTTP connection to the URL
URL url = new URL(args[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
// write the XML from the input stream to standard out
InputStream in = con.getInputStream(); byte[] b =

30 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

new byte[1024]; // 1K buffer


int result = in.read(b);

while (result != -1) {


System.out.write(b,0,result);
result =in.read(b);
}
in.close();
con.disconnect();
}

In this program, the HttpURLConnection class does all the work. It sends the HTTP GET
request to the Web service URL6 and provides access to the response as an InputStream.
Now, let’s look at how this is done using JWS.

Program 2 shows the code used to implement the JAX-WS version of GetNewOrders.
Browsing through this code, you can see some of the awkwardness that comes from applying
the WSDL-oriented Service API in a REST context. First, notice that you must create
QName instances for the Service instance and the “port” that corresponds to the RESTful
Web service. In a SOAP scenario, these qualified names would correspond to the WSDL
definitions for the wsdl: service and wsdl: port. Since there is no WSDL when invoking a
RESTful service, these QName instances are gratuitous in this example. They are required by
the API, but not used to invoke the RESTful service.

31 | P a g e 190950131124_JANKI SHAH
ITM Universe, Vadodara
Bachelor of Computer Science, Engineering
SEM-7th 3170719- Distributed System Practical

Program 2 The GetNewOrders Client As Implemented with JAX-WS


Code:
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println
("Usage: java GetNewOrders <Web Service URL>");
System.exit(1);
}
QName svcQName = new QName("http://sample", "svc");
QName portQName = new QName("http://sample", "port");
Service svc = Service.create(svcQName);
svc.addPort(portQName, HTTPBinding.HTTP_BINDING, args[0]);
Dispatch<Source> dis =
svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
Map<String, Object> requestContext = dis.getRequestContext();
requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "GET");
Source result = dis.invoke(null);
try {
TransformerFactory.newInstance().newTransformer()
.transform(result, new StreamResult(System.out));
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}

32 | P a g e 190950131124_JANKI SHAH

You might also like