1a-Calc-RPC-Datagram
CalculatorServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class CalculatorServer {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(9999);
byte[] receiveBuffer = new byte[1024];
System.out.println("Server is running...");
while (true) {
DatagramPacket request = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(request);
String data = new String(request.getData(), 0, request.getLength());
System.out.println("Request received: " + data);
String[] parts = data.split(",");
double num1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double num2 = Double.parseDouble(parts[2]);
double result = 0;
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "/": result = num2 != 0 ? num1 / num2 : Double.NaN; break;
default: result = Double.NaN;
}
String response = "Result: " + result;
byte[] sendBuffer = response.getBytes();
DatagramPacket reply = new DatagramPacket(sendBuffer, sendBuffer.length,
request.getAddress(), request.getPort());
socket.send(reply);
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
CalculatorClient.java
import javax.swing.*;
// import java.awt.event.*;
import java.net.*;
public class CalculatorClient extends JFrame {
private JTextField num1Field = new JTextField(5);
private JTextField num2Field = new JTextField(5);
private JComboBox<String> operatorBox = new JComboBox<>(new String[]{"+", "-", "*", "/"});
private JButton calculateBtn = new JButton("Calculate");
private JLabel resultLabel = new JLabel("Result: ");
public CalculatorClient() {
setTitle("RPC Calculator (UDP)");
setSize(300, 150);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
num1Field.setBounds(20, 20, 60, 25);
operatorBox.setBounds(90, 20, 60, 25);
num2Field.setBounds(160, 20, 60, 25);
calculateBtn.setBounds(90, 60, 100, 25);
resultLabel.setBounds(20, 100, 250, 25);
add(num1Field);
add(operatorBox);
add(num2Field);
add(calculateBtn);
add(resultLabel);
calculateBtn.addActionListener(e -> sendRequest());
}
private void sendRequest() {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
String operator = (String) operatorBox.getSelectedItem();
String message = num1 + "," + operator + "," + num2;
DatagramSocket socket = new DatagramSocket();
byte[] sendBuffer = message.getBytes();
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket request = new DatagramPacket(sendBuffer, sendBuffer.length, serverAddress, 9999);
socket.send(request);
byte[] receiveBuffer = new byte[1024];
DatagramPacket response = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(response);
String result = new String(response.getData(), 0, response.getLength());
resultLabel.setText(result);
socket.close();
} catch (Exception ex) {
resultLabel.setText("Error: " + ex.getMessage());
}
}
public static void main(String[] args) {
new CalculatorClient().setVisible(true);
}
}
1b-DateTime-RPC-Datagram
DateTimeServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeServer {
public static void main(String[] args) {
final int PORT = 8888;
try {
DatagramSocket socket = new DatagramSocket(PORT);
byte[] receiveBuffer = new byte[1024];
System.out.println("DateTime Server is running on port " + PORT + "...");
while (true) {
DatagramPacket request = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(request);
String message = new String(request.getData(), 0, request.getLength());
System.out.println("Received request: " + message);
String responseMessage;
if (message.equalsIgnoreCase("GET_DATE_TIME")) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
responseMessage = "Server Time: " + formatter.format(new Date());
} else {
responseMessage = "Invalid RPC Method!";
}
byte[] sendBuffer = responseMessage.getBytes();
DatagramPacket response = new DatagramPacket(
sendBuffer,
sendBuffer.length,
request.getAddress(),
request.getPort()
);
socket.send(response);
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DateTimeCLient.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class DateTimeClient {
public static void main(String[] args) {
final int PORT = 8888;
final String SERVER_ADDRESS = "localhost";
try {
DatagramSocket socket = new DatagramSocket();
String requestMessage = "GET_DATE_TIME";
byte[] sendBuffer = requestMessage.getBytes();
InetAddress serverAddress = InetAddress.getByName(SERVER_ADDRESS);
DatagramPacket request = new DatagramPacket(sendBuffer, sendBuffer.length, serverAddress, PORT);
socket.send(request);
byte[] receiveBuffer = new byte[1024];
DatagramPacket response = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(response);
String result = new String(response.getData(), 0, response.getLength());
System.out.println("Response from server: " + result);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2a-Calc-RPC-SocketServer
CalculatorServerTCP.java
import java.io.*;
import java.net.*;
public class CalculatorServerTCP {
public static void main(String[] args) {
final int PORT = 5000;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Calculator TCP Server running on port " + PORT + "...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request = in.readLine(); // e.g. "10,+,5"
System.out.println("Received: " + request);
String[] parts = request.split(",");
double num1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double num2 = Double.parseDouble(parts[2]);
double result = 0;
switch (operator) {
case "+" -> result = num1 + num2;
case "-" -> result = num1 - num2;
case "*" -> result = num1 * num2;
case "/" -> result = num2 != 0 ? num1 / num2 : Double.NaN;
default -> result = Double.NaN;
}
out.println("Result: " + result);
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}}}
CalculatorClientTCP.java
import javax.swing.*;
// import java.awt.event.*;
import java.io.*;
import java.net.*;
public class CalculatorClientTCP extends JFrame {
private JTextField num1Field = new JTextField(5);
private JTextField num2Field = new JTextField(5);
private JComboBox<String> operatorBox = new JComboBox<>(new String[]{"+", "-", "*", "/"});
private JButton calculateBtn = new JButton("Calculate");
private JLabel resultLabel = new JLabel("Result: ");
public CalculatorClientTCP() {
setTitle("TCP Calculator (Client GUI)");
setSize(320, 180);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
num1Field.setBounds(20, 20, 60, 25);
operatorBox.setBounds(90, 20, 60, 25);
num2Field.setBounds(160, 20, 60, 25);
calculateBtn.setBounds(90, 60, 100, 25);
resultLabel.setBounds(20, 100, 250, 25);
add(num1Field);
add(operatorBox);
add(num2Field);
add(calculateBtn);
add(resultLabel);
calculateBtn.addActionListener(e -> sendRequest());
}
private void sendRequest() {
final int PORT = 5000;
final String HOST = "localhost";
Socket socket = null;
try {
double num1 = Double.parseDouble(num1Field.getText().trim());
double num2 = Double.parseDouble(num2Field.getText().trim());
String operator = (String) operatorBox.getSelectedItem();
String message = num1 + "," + operator + "," + num2;
socket = new Socket(HOST, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
String response = in.readLine();
resultLabel.setText(response);
} catch (NumberFormatException nfe) {
resultLabel.setText("Invalid input: enter numbers only.");
} catch (IOException ioe) {
resultLabel.setText("Connection error: " + ioe.getMessage());
} finally {
try {
if (socket != null) socket.close();
} catch (IOException ex) {
ex.printStackTrace();
} } }
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CalculatorClientTCP().setVisible(true));
}}
2b-DateTime-RPC-SocketServer
DateTimeServerTCP.java
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeServerTCP {
public static void main(String[] args) {
final int PORT = 6000;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("DateTime Server running on port " + PORT + "...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String command = in.readLine(); // e.g., GET_DATE_TIME
System.out.println("Received: " + command);
if ("GET_DATE_TIME".equalsIgnoreCase(command)) {
String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
out.println("Current Server Time: " + dateTime);
} else {
out.println("Invalid command.");
}
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
} }}
DateTimeClientTCP.java
import java.io.*;
import java.net.*;
public class DateTimeClientTCP {
public static void main(String[] args) {
final int PORT = 6000;
final String HOST = "localhost";
try (
Socket socket = new Socket(HOST, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
) {
System.out.println("Connected to DateTime Server.");
out.println("GET_DATE_TIME");
String response = in.readLine();
System.out.println("Server response: " + response);
} catch (IOException e) {
e.printStackTrace();
} }}
3-RMI-DateTime
DateServer.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.Naming;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateServer extends UnicastRemoteObject implements DateInterface {
protected DateServer() throws RemoteException {
super();
}
public String getDateTime() throws RemoteException {
try {
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, dd MMM yyyy HH:mm:ss");
return sdf.format(new Date());
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
public static void main(String args[]) {
try {
LocateRegistry.createRegistry(1099);
DateServer obj = new DateServer();
Naming.rebind("rmi://localhost:1099/DateService", obj);
System.out.println("Date Server is ready.");
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}
DateClient.java
import java.rmi.Naming;
public class DateClient {
public static void main(String[] args) {
try {
DateInterface stub = (DateInterface) Naming.lookup("rmi://localhost:1099/DateService");
String serverTime = stub.getDateTime();
System.out.println("Date & Time from Server: " + serverTime);
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}
DateInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface DateInterface extends Remote {
String getDateTime() throws RemoteException;
}
EqServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class EqServer {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(1234);
System.out.println("Server Started... Waiting for data...");
byte[] receiveData = new byte[1024];
byte[] sendData;
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
ds.receive(receivePacket);
String input = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + input);
// Extract a and b
String[] values = input.split(" ");
int a = Integer.parseInt(values[0]);
int b = Integer.parseInt(values[1]);
// Equation (a–b)² = a² – 2ab + b²
int result = (a * a) - (2 * a * b) + (b * b);
String output = "Result = " + result;
sendData = output.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length,
receivePacket.getAddress(),
receivePacket.getPort()
);
ds.send(sendPacket);
System.out.println("Sent: " + output);
}
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}
EqClient.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class EqClient {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getByName("localhost");
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of a: ");
int a = sc.nextInt();
System.out.print("Enter value of b: ");
int b = sc.nextInt();
String msg = a + " " + b;
byte[] sendData = msg.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 1234);
ds.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
ds.receive(receivePacket);
String output = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server Response: " + output);
} catch (Exception e) {
System.out.println("Client Error: " + e);
}
}
}
4-RMI-Library
Bill.java
import java.io.Serializable;
import java.sql.Date;
public class Bill implements Serializable {
private String consumerName;
private Date dueDate;
private double amount;
// Getters and setters
public String getConsumerName() { return consumerName; }
public void setConsumerName(String name) { this.consumerName = name; }
public Date getDueDate() { return dueDate; }
public void setDueDate(Date date) { this.dueDate = date; }
public double getAmount() { return amount; }
public void setAmount(double amt) { this.amount = amt; }
}
BillingService.java
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.List;
public interface BillingService extends Remote {
List<Bill> getAllBills() throws RemoteException, SQLException, ClassNotFoundException;
}
BillingServiceImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BillingServiceImpl extends UnicastRemoteObject implements BillingService {
private static final long serialVersionUID = 1L;
protected BillingServiceImpl() throws RemoteException {
super();
}
@Override
public List<Bill> getAllBills() throws RemoteException, SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Electric Bill database connection
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Electric_Bill",
"root",
"Neha@0401"
);
stmt = conn.createStatement();
String sql = "SELECT consumer_name, bill_due_date, bill_amount FROM Bill";
rs = stmt.executeQuery(sql);
List<Bill> bills = new ArrayList<>();
while(rs.next()) {
Bill bill = new Bill();
bill.setConsumerName(rs.getString("consumer_name"));
bill.setDueDate(rs.getDate("bill_due_date"));
bill.setAmount(rs.getDouble("bill_amount"));
bills.add(bill);
}
return bills;
} finally {
closeResources(rs, stmt, conn);
}
}
private void closeResources(ResultSet rs, Statement stmt, Connection conn) {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Book.java
import java.io.Serializable;
public class Book implements Serializable {
private int bookId;
private String bookName;
private String author;
// Getters and setters
public int getBookId() { return bookId; }
public void setBookId(int id) { this.bookId = id; }
public String getBookName() { return bookName; }
public void setBookName(String name) { this.bookName = name; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}
DatabaseClient.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.SQLException;
import java.util.List;
public class DatabaseClient {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
LibraryService libraryService =
(LibraryService) registry.lookup("LibraryService");
BillingService billingService =
(BillingService) registry.lookup("BillingService");
List<Book> books = libraryService.getAllBooks();
System.out.println("\nAvailable Books:");
books.forEach(book -> {
System.out.println("ID: " + book.getBookId() +
", Name: " + book.getBookName() +
", Author: " + book.getAuthor());
});
List<Bill> bills = billingService.getAllBills();
System.out.println("\nPending Bills:");
bills.forEach(bill -> {
System.out.println("Consumer: " + bill.getConsumerName() +
", Due Date: " + bill.getDueDate() +
", Amount: Rs. " + bill.getAmount());
});
} catch (Exception e) {
System.err.println("Error accessing remote services:");
if (e instanceof java.rmi.ConnectException) {
System.err.println("Connection error: Could not connect to RMI registry");
} else if (e instanceof java.rmi.NotBoundException) {
System.err.println("Service not found: LibraryService or BillingService not registered");
} else if (e instanceof java.rmi.RemoteException) {
System.err.println("Remote service error: " + e.getMessage());
} else if (e instanceof SQLException) {
System.err.println("Database error: " + e.getMessage());
} else {
System.err.println("Unexpected error: " + e.getMessage());
}
e.printStackTrace();
}
}
}
DatabaseServer.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class DatabaseServer {
public static void main(String[] args) {
try {
LibraryService libraryService = new LibraryServiceImpl();
BillingService billingService = new BillingServiceImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("LibraryService", libraryService);
registry.bind("BillingService", billingService);
System.out.println("Database Server started!");
} catch (Exception e) {
System.err.println("Error starting server: " + e.getMessage());
e.printStackTrace();
}
}
}
LibraryService.java
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
import java.sql.SQLException;
public interface LibraryService extends Remote {
List<Book> getAllBooks() throws RemoteException, SQLException, ClassNotFoundException;
}
LibraryServiceImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class LibraryServiceImpl extends UnicastRemoteObject implements LibraryService {
private static final long serialVersionUID = 1L;
protected LibraryServiceImpl() throws RemoteException {
super();
}
@Override
public List<Book> getAllBooks() throws RemoteException, SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Library",
"root",
"Neha@0401"
);
stmt = conn.createStatement();
String sql = "SELECT book_id, book_name, author FROM Book";
rs = stmt.executeQuery(sql);
List<Book> books = new ArrayList<>();
while(rs.next()) {
Book book = new Book();
book.setBookId(rs.getInt("book_id"));
book.setBookName(rs.getString("book_name"));
book.setAuthor(rs.getString("author"));
books.add(book);
}
return books;
} finally {
closeResources(rs, stmt, conn);
}
}
private void closeResources(ResultSet rs, Statement stmt, Connection conn) {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
MySQL
-- create library DB and table
CREATE DATABASE IF NOT EXISTS Library;
USE Library;
CREATE TABLE IF NOT EXISTS Book (
book_id INT PRIMARY KEY,
book_name VARCHAR(255),
author VARCHAR(255)
);
INSERT INTO Book (book_id, book_name, author) VALUES
(1, 'Introduction to Java', 'Herbert Schildt'),
(2, 'Database Systems', 'Ramakrishnan');
-- create electric bill DB and table
CREATE DATABASE IF NOT EXISTS Electric_Bill;
USE Electric_Bill;
CREATE TABLE IF NOT EXISTS Bill (
consumer_name VARCHAR(255),
bill_due_date DATE,
bill_amount DOUBLE
);
INSERT INTO Bill (consumer_name, bill_due_date, bill_amount) VALUES
('Alice', '2025-12-05', 1250.50),
('Bob', '2025-12-10', 980.75);
Compile
javac -cp .;lib\mysql-connector-java-8.0.33.jar *.java
Run Server
java -cp .;lib\mysql-connector-java-8.0.33.jar DatabaseServer
Run Client
java -cp . DatabaseClient
Output
Available Books:
ID: 1, Name: Introduction to Java, Author: Herbert Schildt
ID: 2, Name: Database Systems, Author: Ramakrishnan
Pending Bills:
Consumer: Alice, Due Date: 2025-12-05, Amount: Rs. 1250.5
Consumer: Bob, Due Date: 2025-12-10, Amount: Rs. 980.75
5-MutualExclusion
TokenRingMain.java
import java.util.Scanner;
class TokenRing {
private int n;
private boolean[] state;
private int token;
public TokenRing(int n) {
this.n = n;
this.state = new boolean[n];
this.token = 0;
state[token] = true;
}
public void requestCS(int processId) {
if (processId == token) {
System.out.println("Process " + processId + " has entered the Critical Section.");
releaseCS(processId);
} else {
System.out.println("Process " + processId + " requested CS but does not have token.");
}
}
private void releaseCS(int processId) {
System.out.println("Process " + processId + " is leaving Critical Section.");
state[processId] = false;
token = (processId + 1) % n;
state[token] = true;
System.out.println("Token passed to Process " + token + "\n");
}
}
public class TokenRingMain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of processes: ");
int n = sc.nextInt();
TokenRing ring = new TokenRing(n);
while (true) {
System.out.print("Enter process id to request CS (-1 to exit): ");
int id = sc.nextInt();
if (id == -1) break;
if (id >= n) {
System.out.println("Invalid process id!");
continue;
}
ring.requestCS(id);
}
sc.close();
}
}
Output
Enter number of processes: 3
Enter process id to request CS (-1 to exit): 0
Process 0 has entered the Critical Section.
Process 0 is leaving Critical Section.
Token passed to Process 1
Enter process id to request CS (-1 to exit): 2
Process 2 requested CS but does not have token.
Enter process id to request CS (-1 to exit): 1
Process 1 has entered the Critical Section.
Process 1 is leaving Critical Section.
Token passed to Process 2
Enter process id to request CS (-1 to exit): -1
ElectionMain.java
import java.util.Scanner;
class Election {
private int n;
private boolean[] active;
public Election(int n) {
this.n = n;
this.active = new boolean[n];
for (int i = 0; i < n; i++) {
active[i] = true;
}
}
public void holdElection(int initiator) {
System.out.println("Election initiated by Process " + initiator);
int newCoordinator = -1;
for (int i = initiator + 1; i < n; i++) {
if (active[i]) {
System.out.println("Process " + i + " responds OK.");
newCoordinator = i;
}
}
if (newCoordinator == -1) {
newCoordinator = initiator;
}
announceCoordinator(newCoordinator);
}
private void announceCoordinator(int coord) {
System.out.println("Process " + coord + " is the new Coordinator!\n");
}
public void failProcess(int id) {
active[id] = false;
System.out.println("Process " + id + " has failed."); }
public void recoverProcess(int id) {
active[id] = true;
System.out.println("Process " + id + " has recovered.");
}}
public class ElectionMain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of processes: ");
int n = sc.nextInt();
Election e = new Election(n);
while (true) {
System.out.print("\n1. Start Election\n2. Fail Process\n3. Recover Process\n4. Exit\nEnter choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter initiator process id: ");
int id = sc.nextInt();
e.holdElection(id);
break;
case 2:
System.out.print("Enter process id to fail: ");
e.failProcess(sc.nextInt());
break;
case 3:
System.out.print("Enter process id to recover: ");
e.recoverProcess(sc.nextInt());
break;
case 4:
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}
Output
Enter number of processes: 3
1. Start Election
2. Fail Process
3. Recover Process
4. Exit
Enter choice: 1
Enter initiator process id: 1
Election initiated by Process 1
Process 2 responds OK.
Process 2 is the new Coordinator!
1. Start Election
2. Fail Process
3. Recover Process
4. Exit
Enter choice: 2
Enter process id to fail: 1
Process 1 has failed.
1. Start Election
2. Fail Process
3. Recover Process
4. Exit
Enter choice: 1
Enter initiator process id: 0
Election initiated by Process 0
Process 2 responds OK.
Process 2 is the new Coordinator!
1. Start Election
2. Fail Process
3. Recover Process
4. Exit
Enter choice: 2
Enter process id to fail: 2
Process 2 has failed.
ChatApp
ChatServer.java
import java.io.*;
import java.net.*;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public class ChatServer {
private static final int PORT = 12345;
// thread-safe set
private static Set<ClientHandler> clientHandlers = new CopyOnWriteArraySet<>();
public static void main(String[] args) {
System.out.println("Chat Server starting on port " + PORT);
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getRemoteSocketAddress());
ClientHandler handler = new ClientHandler(clientSocket);
clientHandlers.add(handler);
new Thread(handler).start();
}
} catch (IOException e) {
System.err.println("Server Error: " + e.getMessage());
e.printStackTrace();
}
}
static void broadcast(String message, ClientHandler sender) {
for (ClientHandler client : clientHandlers) {
if (client != sender) {
client.sendMessage(message);
}
}
}
static class ClientHandler implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private String name = "Anonymous";
ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Ask for a name
out.println("Enter your name:");
String inputName = in.readLine();
if (inputName != null && !inputName.trim().isEmpty()) {
name = inputName.trim();
}
System.out.println(name + " joined the chat.");
broadcast(name + " has joined the chat.", this);
String msg;
while ((msg = in.readLine()) != null) {
String formatted = name + ": " + msg;
System.out.println("Received: " + formatted);
broadcast(formatted, this);
}
} catch (IOException e) {
System.out.println("Connection error for " + name + ": " + e.getMessage());
} finally {
// cleanup
clientHandlers.remove(this);
broadcast(name + " has left the chat.", this);
try {
if (in != null) in.close();
if (out != null) out.close();
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println(name + " disconnected.");
}
}
void sendMessage(String message) {
if (out != null) out.println(message);
}
@Override
public int hashCode() {
return socket.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ClientHandler)) return false;
ClientHandler other = (ClientHandler) o;
return this.socket.equals(other.socket);
}
}
}
ChatClient.java
import java.io.*;
import java.net.*;
public class ChatClient {
private static String SERVER = "localhost";
private static final int PORT = 12345;
public static void main(String[] args) {
if (args.length >= 1) SERVER = args[0]; // optional server IP argument
try (Socket socket = new Socket(SERVER, PORT);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
// Thread to receive messages from server
Thread reader = new Thread(() -> {
try {
String serverMsg;
while ((serverMsg = in.readLine()) != null) {
System.out.println(serverMsg);
}
} catch (IOException e) {
System.out.println("Connection closed.");
}
});
reader.setDaemon(true);
reader.start();
// First lines: server may ask for name
// If server asks "Enter your name:", display it and read name from user
// Read server prompt (non-blocking style isn't simple; we prompt user anyway)
System.out.print("Enter your name: ");
String name = console.readLine();
out.println(name); // send name to server
// Main loop: read from console and send to server
String inputMsg;
while ((inputMsg = console.readLine()) != null) {
if (inputMsg.equalsIgnoreCase("/quit")) {
break;
}
out.println(inputMsg);
}
System.out.println("Disconnecting...");
} catch (IOException e) {
System.err.println("Client Error: " + e.getMessage());
}
}
}
Initials
InitialsServer.java
import java.net.*;
public class InitialsServer {
public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receivedData = new byte[1024];
byte[] sendData;
while (true) {
DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
System.out.println("Server Started...");
serverSocket.receive(receivedPacket);
String response = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
System.out.println("Received Request: " + response);
String capName = response.toUpperCase();
String[] parts = capName.trim().split("\\s+");
StringBuilder initials = new StringBuilder();
for (String part : parts) {
if (!part.isEmpty())
initials.append(part.charAt(0)).append(".");
}
String fullResult = "Your Name: " + capName + "\nYour Initials: " + initials;
sendData = fullResult.getBytes();
InetAddress clientAdd = receivedPacket.getAddress();
int port = receivedPacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAdd, port);
serverSocket.send(sendPacket);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
InitialsClient.java
import java.net.*;
import java.util.Scanner;
public class InitialsClient {
public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData;
byte[] receivedData = new byte[1024];
InetAddress add = InetAddress.getByName("localhost");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter your full name (Ex: Rohit Mangesh Joshi): ");
String data = sc.nextLine();
sendData = data.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, add, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receivedData, receivedData.length);
clientSocket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(response);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
String Rev
StringService.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface StringService extends Remote {
String reverseString(String input) throws RemoteException;
}
StringServiceImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.Stack;
public class StringServiceImpl extends UnicastRemoteObject implements StringService {
protected StringServiceImpl() throws RemoteException {
super();
}
@Override
public String reverseString(String input) throws RemoteException {
Stack<Character> stack = new Stack<>();
for (char ch : input.toCharArray()) {
stack.push(ch);
}
StringBuilder reversed = new StringBuilder();
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return reversed.toString();
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
StringService service = new StringServiceImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("StringService", service);
System.out.println("String Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
StringService service = (StringService) registry.lookup("StringService");
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
String input = sc.nextLine();
String reversed = service.reverseString(input);
System.out.println("Reversed string: " + reversed);
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
RMI Banking System
BankInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface BankInterface extends Remote {
double checkBalance(int accountNo) throws RemoteException;
void deposit(int accountNo, double amount) throws RemoteException;
boolean withdraw(int accountNo, double amount) throws RemoteException;
boolean transfer(int fromAcc, int toAcc, double amount) throws RemoteException;
}
BankImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
public class BankImpl extends UnicastRemoteObject implements BankInterface {
private Map<Integer, Double> accounts;
protected BankImpl() throws RemoteException {
super();
accounts = new HashMap<>();
accounts.put(1001, 5000.0);
accounts.put(1002, 3000.0);
accounts.put(1003, 7000.0);
}
@Override
public double checkBalance(int accountNo) throws RemoteException {
return accounts.getOrDefault(accountNo, -1.0);
}
@Override
public void deposit(int accountNo, double amount) throws RemoteException {
accounts.put(accountNo, accounts.getOrDefault(accountNo, 0.0) + amount);
}
@Override
public boolean withdraw(int accountNo, double amount) throws RemoteException {
double balance = accounts.getOrDefault(accountNo, -1.0);
if (balance == -1.0) return false;
if (balance >= amount) {
accounts.put(accountNo, balance - amount);
return true;
}
return false;
}
@Override
public boolean transfer(int fromAcc, int toAcc, double amount) throws RemoteException {
if (withdraw(fromAcc, amount)) {
deposit(toAcc, amount);
return true;
}
return false;
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
BankImpl bank = new BankImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("BankService", bank);
System.out.println("Bank Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
BankInterface bank = (BankInterface) registry.lookup("BankService");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("\n=== Banking Menu ===");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Transfer");
System.out.println("5. Exit");
System.out.print("Choose option: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter Account No: ");
int acc1 = sc.nextInt();
double bal = bank.checkBalance(acc1);
if (bal == -1.0)
System.out.println("Account not found.");
else
System.out.println("Balance: " + bal);
break;
case 2:
System.out.print("Enter Account No: ");
int acc2 = sc.nextInt();
System.out.print("Enter Deposit Amount: ");
double dep = sc.nextDouble();
bank.deposit(acc2, dep);
System.out.println("Deposit successful.");
break;
case 3:
System.out.print("Enter Account No: ");
int acc3 = sc.nextInt();
System.out.print("Enter Withdraw Amount: ");
double wd = sc.nextDouble();
if (bank.withdraw(acc3, wd))
System.out.println("Withdrawal successful.");
else
System.out.println("Insufficient funds or invalid account.");
break;
case 4:
System.out.print("Enter From Account No: ");
int from = sc.nextInt();
System.out.print("Enter To Account No: ");
int to = sc.nextInt();
System.out.print("Enter Amount: ");
double amt = sc.nextDouble();
if (bank.transfer(from, to, amt))
System.out.println("Transfer successful.");
else
System.out.println("Transfer failed (check balance/account).");
break;
case 5:
System.out.println("Exiting...");
sc.close();
System.exit(0);
break;
default:
System.out.println("Invalid choice.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
=== Banking Menu ===
1. Check Balance
2. Deposit
3. Withdraw
4. Transfer
5. Exit
Choose option: 1
Enter Account No: 1001
Balance: 5000.0
Choose option: 4
Enter From Account No: 1001
Enter To Account No: 1002
Enter Amount: 500
Transfer successful.
Choose option: 1
Enter Account No: 1002
Balance: 3500.0
DistanceService.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface DistanceService extends Remote {
double calculateDistance(double lat1, double lon1, double lat2, double lon2) throws RemoteException;
}
DistanceServiceImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class DistanceServiceImpl extends UnicastRemoteObject implements DistanceService {
private static final double R = 6371.0; // Radius of Earth in km
protected DistanceServiceImpl() throws RemoteException {
super();
}
@Override
public double calculateDistance(double lat1, double lon1, double lat2, double lon2) throws RemoteException {
double φ1 = Math.toRadians(lat1);
double φ2 = Math.toRadians(lat2);
double Δφ = Math.toRadians(lat2 - lat1);
double Δλ = Math.toRadians(lon2 - lon1);
double a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
DistanceService service = new DistanceServiceImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("DistanceService", service);
System.out.println("Server is running and DistanceService is bound...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
DistanceService service = (DistanceService) registry.lookup("DistanceService");
Scanner sc = new Scanner(System.in);
System.out.println("Enter latitude of City 1: ");
double lat1 = sc.nextDouble();
System.out.println("Enter longitude of City 1: ");
double lon1 = sc.nextDouble();
System.out.println("Enter latitude of City 2: ");
double lat2 = sc.nextDouble();
System.out.println("Enter longitude of City 2: ");
double lon2 = sc.nextDouble();
double distance = service.calculateDistance(lat1, lon1, lat2, lon2);
System.out.printf("Distance between the two cities: %.3f km%n", distance);
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Enter latitude of City 1:
19.0760
Enter longitude of City 1:
72.8777
Enter latitude of City 2:
28.7041
Enter longitude of City 2:
77.1025
Distance between the two cities: 1148.252 km
6-Concept: Implementation of Cloud Computing Services
Cloud Computing provides different services such as:
- SaaS (Software as a Service)
- PaaS (Platform as a Service)
- IaaS (Infrastructure as a Service)
- Storage as a Service
- And many more…
Storage as a Service is a business model in which a large company rents space in its storage infrastructure to a smaller company or individual.
Implementation of Storage as a Service using Google Docs
Google Service (SaaS):
Steps:
- Click on Blank in Google Docs and proceed with your documentation.
- You can manage your document’s access through Share → Access Management.
- Set permission as Viewer / Commenter / Editor.
Concept: Implementation of Identity Management using Cloud Computing
Identity Management ensures that only authenticated and authorized users can access specific applications, systems, or IT environments.
Implementation of Identity Management using AWS IAM
You can manage access in AWS using IAM users.
IAM allows restricting access for each user.
Steps:
- Click on IAM user in AWS.
- Go to Users under Access Management → click Create User.
- Provide the User Name.
Set Permissions:
- Select Add user to group.
- Click Create Group.
- Choose access permissions (e.g., Read-only access).
The user will now be part of the created group (e.g., ReadManage). You can modify access later if needed.
Enable Console Access:
- Go to Users → select the user.
- Open Security Credentials.
- Click Enable Console Access.
- Provide autogenerated or custom password.
Download Credentials:
- Download the .csv credentials file.
- This contains the username and password.
- Keep it secure.
Cleanup:
- Remove the user from the group when no longer needed.
- Delete the IAM user from Access Management.
Assignment 7 – Virtual Machine Creation
Create a Virtual Machine (VM) on a Cloud Provider
Create a virtual machine (VM) on any cloud provider (AWS / Azure / GCP) with the following specifications:
- Operating System
- VM Type
- Disk Size
- Public IP
- Network Rules
Once created, verify that the VM is running and include a screenshot of the instance details along with a brief description of the steps followed.
Solution
I am creating a virtual machine using the cloud provider AWS. AWS uses EC2 instances for creating virtual machines.
Steps to Create a Virtual Machine Using AWS EC2
Step 1: Select EC2 in AWS
Open AWS Management Console and search for EC2.
Step 2: Open EC2 Instances
Click on Instances under the Instances section in EC2.
Step 3: Launch a New Instance
- Click Launch Instances to create a new Virtual Machine (Free Tier).
- Give a name tag to your instance.
- Select the instance type (ensure it’s Free Tier eligible or choose a paid option if you prefer).
- Create a Key Pair for secure login (used for SSH access).
- Configure network settings during instance creation or modify them later.
- Configure the storage size carefully (larger storage increases cost).
- Under Advanced Settings, you can add startup scripts or project-specific configurations.
Step 4: Launch the Instance
Click Launch Instance.
Go to the EC2 Dashboard → Instances to verify that the instance is running.
Step 5: Terminating the Instance (If No Longer Needed)
If the instance is not in use:
- Select the instance.
- Click Instance State.
- Choose Terminate to delete it from the EC2 dashboard.
Install Virtual Box / VMware / Equivalent Workstation
Install a local virtualization tool to run different Linux or Windows operating systems on top of Windows 8 or above.
Step 1: Open VMware Workstation
Launch VMware Workstation Player.
Click Create a New Virtual Machine.
Step 2: Select Installer
- Choose Installer disc image file (ISO).
- Browse and select your Ubuntu ISO file.
- Click Next.
- VM Name: Ubuntu-VM (or any preferred name).
- Location: Use default or choose another folder.
- Disk Size: 20 GB (adjust according to your requirement).
- Disk Type: Store as a single file or split into multiple files.
- Click Next, then Finish.
Step 5: Start the VM
- Select your virtual machine.
- Click Play virtual machine.
- Ubuntu will boot from the ISO.
- Follow the installation instructions to complete OS setup.