RPC Programming
1. Implement PI calculation Service .
a. Server file:
import grpc
from concurrent import futures
import pi_service_pb2
import pi_service_pb2_grpc
class PiCalculatorServicer(pi_service_pb2_grpc.PiCalculatorServicer):
def CalculatePi(self, request, context):
# Leibniz formula for PI
iterations = [Link]
pi = 0.0
for i in range(iterations):
pi += ((-1) ** i) / (2 * i + 1)
pi *= 4 # Leibniz formula converges to PI/4
return pi_service_pb2.PiResponse(value=pi)
def serve():
server = [Link]([Link](max_workers=10))
pi_service_pb2_grpc.add_PiCalculatorServicer_to_server(PiCalculatorServicer(), server)
server.add_insecure_port('[::]:50051')
[Link]()
print("PI Calculation Service is running on port 50051")
server.wait_for_termination()
if __name__ == "__main__":
serve()
Client file:
import grpc
import pi_service_pb2
import pi_service_pb2_grpc
def run():
with grpc.insecure_channel('localhost:50051') as channel:
stub = pi_service_pb2_grpc.PiCalculatorStub(channel)
# Define the number of iterations to approximate PI
iterations = 10000
response = [Link](pi_service_pb2.PiRequest(iterations=iterations))
print(f"Calculated PI value: {[Link]}")
if __name__ == "__main__":
run()
2. Implement Calculator Service using SUN RPC.
Server file:
from [Link] import SimpleXMLRPCServer
# Define Calculator Service with basic operations
class CalculatorService:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y == 0:
return "Cannot divide by zero"
return x / y
# Start the XML-RPC server
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(CalculatorService())
print("Calculator Service is running on port 8000...")
server.serve_forever()
Client file:
import [Link]
# Connect to the Calculator Service
with [Link]("[Link] as proxy:
# Perform remote calculations
print("Addition (10 + 5):", [Link](10, 5))
print("Subtraction (10 - 5):", [Link](10, 5))
print("Multiplication (10 * 5):", [Link](10, 5))
print("Division (10 / 5):", [Link](10, 5))
print("Division (10 / 0):", [Link](10, 0)) # Handle division by zero
3. Implement RPC programming on windows using DCOM.
import pythoncom
import [Link]
from [Link] import wrap
class Calculator:
_public_methods_ = ['Add', 'Subtract', 'Multiply', 'Divide']
_reg_progid_ = "[Link]"
_reg_clsid_ = "{0D4B768C-31EC-4DD6-9E6E-C79C8C1A1234}" # Generate a unique CLSID for
the component
def Add(self, x, y):
return x + y
def Subtract(self, x, y):
return x - y
def Multiply(self, x, y):
return x * y
def Divide(self, x, y):
if y == 0:
return "Cannot divide by zero"
return x / y
def register_calculator():
# Register the COM server
import [Link]
[Link](Calculator)
if __name__ == "__main__":
register_calculator()
Client file:
import [Link]
def run_calculator():
# Connect to the remote DCOM server
calculator = [Link]("[Link]")
# Perform operations
print("Addition (10 + 5):", [Link](10, 5))
print("Subtraction (10 - 5):", [Link](10, 5))
print("Multiplication (10 * 5):", [Link](10, 5))
print("Division (10 / 5):", [Link](10, 5))
print("Division (10 / 0):", [Link](10, 0)) # Handle division by zero
if __name__ == "__main__":
run_calculator()
RMI Programming
1. Implementation of “Hello Word” Service using JAVA RMI
File 1:
import [Link];
import [Link];
public class HelloWorldImpl extends UnicastRemoteObject implements HelloWorld {
public HelloWorldImpl() throws RemoteException {
super();
}
@Override
public String sayHello() throws RemoteException {
return "Hello, World!";
}
}
File 2:
import [Link];
import [Link];
public class HelloWorldServer {
public static void main(String[] args) {
try {
HelloWorldImpl hello = new HelloWorldImpl();
Registry registry = [Link](1099);
[Link]("HelloWorldService", hello);
[Link]("Hello World Service is running...");
} catch (Exception e) {
[Link]();
}
}
public class HelloWorldClient {
public static void main(String[] args) {
try {
Registry registry = [Link]("localhost", 1099);
HelloWorld hello = (HelloWorld) [Link]("HelloWorldService");
[Link]([Link]());
} catch (Exception e) {
[Link]();
}
}
}
2. Implementation of “Calculator” Service using JAVA RMI
Remote interface:
import [Link];
import [Link];
public class CalculatorImpl extends UnicastRemoteObject implements Calculator {
public CalculatorImpl() throws RemoteException {
super();
}
@Override
public double add(double a, double b) throws RemoteException {
return a + b;
}
@Override
public double subtract(double a, double b) throws RemoteException {
return a - b;
}
@Override
public double multiply(double a, double b) throws RemoteException {
return a * b;
}
@Override
public double divide(double a, double b) throws RemoteException {
if (b == 0) throw new ArithmeticException("Cannot divide by zero");
return a / b;
}
}
File2:
import [Link];
import [Link];
public class CalculatorServer {
public static void main(String[] args) {
try {
CalculatorImpl calculator = new CalculatorImpl();
Registry registry = [Link](1099);
[Link]("CalculatorService", calculator);
[Link]("Calculator Service is running...");
} catch (Exception e) {
[Link]();
}
}
public class CalculatorClient {
public static void main(String[] args) {
try {
Registry registry = [Link]("localhost", 1099);
Calculator calculator = (Calculator) [Link]("CalculatorService");
[Link]("Addition (10 + 5): " + [Link](10, 5));
[Link]("Subtraction (10 - 5): " + [Link](10, 5));
[Link]("Multiplication (10 * 5): " + [Link](10, 5));
[Link]("Division (10 / 5): " + [Link](10, 5));
} catch (Exception e) {
[Link]();
}
}
}
3. Implement RMI –IIOP Programming.
import [Link];
import [Link];
import [Link];
public class MyServer {
public static void main(String[] args) {
try {
// Set up properties for JNDI
Properties props = new Properties();
[Link](Context.INITIAL_CONTEXT_FACTORY,
"[Link]");
[Link](Context.PROVIDER_URL, "iiop://localhost:1050"); // Set CORBA naming
service URL
// Create an initial context
Context context = new InitialContext(props);
// Create and bind the service
MyService myService = new MyServiceImpl();
[Link]("MyService", myService);
[Link]("Service bound and ready for clients to connect.");
} catch (Exception e) {
[Link]();
}
}
public class MyClient {
public static void main(String[] args) {
try {
// Set up properties for JNDI
Properties props = new Properties();
[Link](Context.INITIAL_CONTEXT_FACTORY,
"[Link]");
[Link](Context.PROVIDER_URL, "iiop://localhost:1050");
// Create an initial context
Context context = new InitialContext(props);
// Lookup the service
MyService myService = (MyService) [Link]("MyService");
// Invoke the remote method
String response = [Link]("John Doe");
[Link]("Response from server: " + response);
} catch (Exception e) {
[Link]();
}
}
}
Thread Programming in Java
1. Write an application that executes two threads. One thread display “HELLO WOLD” every 1000
milliseconds and another thread display “How Are You” every 2000 milliseconds. Create the threads
by implementing Runnable interface.
Code:
public class MessageThreads {
public static void main(String[] args) {
// First thread to display "HELLO WORLD" every 1000 milliseconds
Runnable helloTask = () -> {
try {
while (true) {
[Link]("HELLO WORLD");
[Link](1000);
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
};
// Second thread to display "How Are You" every 2000 milliseconds
Runnable howAreYouTask = () -> {
try {
while (true) {
[Link]("How Are You");
[Link](2000);
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
};
Thread thread1 = new Thread(helloTask);
Thread thread2 = new Thread(howAreYouTask);
// Start the threads
[Link]();
[Link]();
}
}
2. Implement Multithreaded Echo server using Socket.
Server code:
import [Link].*;
import [Link].*;
public class EchoServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
[Link]("Echo Server started on port 12345");
while (true) {
// Accept client connections
Socket clientSocket = [Link]();
[Link]("Client connected: " + [Link]());
// Start a new thread for each client
new Thread(new EchoClientHandler(clientSocket)).start();
}
} catch (IOException e) {
[Link]();
}
}
}
class EchoClientHandler implements Runnable {
private final Socket clientSocket;
public EchoClientHandler(Socket socket) {
[Link] = socket;
}
@Override
public void run() {
try (BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true)) {
String message;
while ((message = [Link]()) != null) {
[Link]("Received from client: " + message);
[Link]("Echo: " + message); // Echo the message back to the client
}
} catch (IOException e) {
[Link]();
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
[Link]("Client disconnected");
}
}
}
Client code:
import [Link].*;
import [Link].*;
public class EchoClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader consoleInput = new BufferedReader(new InputStreamReader([Link]))) {
String userInput;
while ((userInput = [Link]()) != null) {
[Link](userInput); // Send to server
[Link]([Link]()); // Read echo from server
}
} catch (IOException e) {
[Link]();
}
}
}
3. Implement producer consumer example.
Code(Create the Aglet Agent):
import [Link];
import [Link];
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(5); // Buffer with a capacity of 5
// Producer task
Runnable producerTask = () -> {
int value = 0;
while (true) {
try {
[Link]("Producer produced: " + value);
[Link](value); // Add value to buffer
value++;
[Link](1000); // Simulate production delay
} catch (InterruptedException e) {
[Link]().interrupt();
break;
}
}
};
// Consumer task
Runnable consumerTask = () -> {
while (true) {
try {
int value = [Link](); // Retrieve value from buffer
[Link]("Consumer consumed: " + value);
[Link](1500); // Simulate consumption delay
} catch (InterruptedException e) {
[Link]().interrupt();
break;
}
}
};
// Start producer and consumer threads
Thread producerThread = new Thread(producerTask);
Thread consumerThread = new Thread(consumerTask);
[Link]();
[Link]();
}
}
4. Mobile Agent (IBM’s Aglet) Programming
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HelloAglet extends Aglet {
// This method is called when the aglet is created
@Override
public void onCreation(Object init) {
[Link]("HelloAglet created at " + new Date());
}
// This method is called when the aglet starts running
@Override
public void run() {
[Link]("Hello from HelloAglet! Running task...");
}
// This method is called when the aglet arrives at a new host
@Override
public void onArrival() {
[Link]("HelloAglet has arrived at a new host.");
}
// This method is called when the aglet is disposed of
@Override
public void onDispose() {
[Link]("HelloAglet is being disposed.");
}
}
Launch the Aglet Programmatically
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HelloAgletLauncher {
public static void main(String[] args) {
try {
// Get the default aglet context (local host)
AgletContext context = [Link]().getAgletContext();
// Create an instance of HelloAglet
AgletProxy proxy = [Link]([Link]());
[Link]("HelloAglet agent created: " + [Link]());
// Optionally, you can dispatch the aglet to another host
// [Link](new URL("aglets://<remote-host>:<port>"));
} catch (Exception e) {
[Link]();
}
}
}
5. Implement CORBA File
[Link]
import [Link];
import [Link];
import [Link].*;
import [Link];
public class FileServiceImpl extends FileServicePOA {
private ORB orb;
public void setORB(ORB orb) {
[Link] = orb;
}
// Method to upload a file
@Override
public void uploadFile(String filename, byte[] fileData) {
try (FileOutputStream fileOut = new FileOutputStream(filename)) {
[Link](fileData);
[Link]("File " + filename + " uploaded successfully.");
} catch (IOException e) {
[Link]();
}
}
// Method to download a file
@Override
public byte[] downloadFile(String filename) {
try (FileInputStream fileIn = new FileInputStream(filename)) {
byte[] fileData = new byte[[Link]()];
[Link](fileData);
[Link]("File " + filename + " downloaded successfully.");
return fileData;
} catch (IOException e) {
[Link]();
return new byte[0];
}
}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FileServer {
public static void main(String[] args) {
try {
ORB orb = [Link](args, null);
// Get reference to root POA & activate the POAManager
POA rootpoa = [Link](orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
// Create and register the FileService servant
FileServiceImpl fileServiceImpl = new FileServiceImpl();
[Link](orb);
// Register the FileService servant with the ORB
Object ref = rootpoa.servant_to_reference(fileServiceImpl);
FileService href = [Link](ref);
// Bind the object reference in the naming service
[Link] ncRef =
[Link](
orb.resolve_initial_references("NameService"));
[Link] path[] = ncRef.to_name("FileService");
[Link](path, href);
[Link]("File Server is running...");
// Wait for incoming requests
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
public class FileClient {
public static void main(String[] args) {
try {
ORB orb = [Link](args, null);
// Get the naming context
NamingContextExt ncRef =
[Link](orb.resolve_initial_references("NameService"));
// Look up the FileService object
FileService fileService = [Link](ncRef.resolve_str("FileService"));
// Upload a file
String filename = "[Link]";
byte[] fileData = "Hello, this is a test file.".getBytes();
[Link](filename, fileData);
[Link]("Uploaded file: " + filename);
// Download the file
byte[] downloadedData = [Link](filename);
[Link]("Downloaded file data: " + new String(downloadedData));
} catch (Exception e) {
[Link]();
}
}
}
6. Incrementing a counter in shared memory. Tools/ Apparatus: Unix/Linux C
Programming Environment
Producer Program (Counter Incrementer)
// producer.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <string.h>
#define SHARED_MEM_NAME "/my_shared_mem"
#define SEMAPHORE_NAME "/my_semaphore"
int main() {
int shm_fd;
int *counter;
sem_t *semaphore;
// Create shared memory object
shm_fd = shm_open(SHARED_MEM_NAME, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("Failed to create shared memory");
exit(1);
}
// Set the size of the shared memory object
ftruncate(shm_fd, sizeof(int));
// Map shared memory object
counter = (int *)mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (counter == MAP_FAILED) {
perror("Failed to map shared memory");
exit(1);
}
// Initialize counter to 0
*counter = 0;
// Create semaphore for synchronization
semaphore = sem_open(SEMAPHORE_NAME, O_CREAT, 0666, 1);
if (semaphore == SEM_FAILED) {
perror("Failed to create semaphore");
exit(1);
}
// Increment counter in a loop
for (int i = 0; i < 10; i++) {
sem_wait(semaphore); // Lock semaphore
(*counter)++; // Increment counter
printf("Producer incremented counter to %d\n", *counter);
sem_post(semaphore); // Unlock semaphore
sleep(1); // Sleep for a second
}
// Cleanup
munmap(counter, sizeof(int));
close(shm_fd);
sem_close(semaphore);
return 0;
}
. Consumer Program (Counter Reader)
// consumer.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <string.h>
#define SHARED_MEM_NAME "/my_shared_mem"
#define SEMAPHORE_NAME "/my_semaphore"
int main() {
int shm_fd;
int *counter;
sem_t *semaphore;
// Open shared memory object
shm_fd = shm_open(SHARED_MEM_NAME, O_RDWR, 0666);
if (shm_fd == -1) {
perror("Failed to open shared memory");
exit(1);
}
// Map shared memory object
counter = (int *)mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (counter == MAP_FAILED) {
perror("Failed to map shared memory");
exit(1);
}
// Open semaphore for synchronization
semaphore = sem_open(SEMAPHORE_NAME, 0);
if (semaphore == SEM_FAILED) {
perror("Failed to open semaphore");
exit(1);
}
// Read counter in a loop
for (int i = 0; i < 10; i++) {
sem_wait(semaphore); // Lock semaphore
printf("Consumer read counter value: %d\n", *counter);
sem_post(semaphore); // Unlock semaphore
sleep(1); // Sleep for a second
}
// Cleanup
munmap(counter, sizeof(int));
close(shm_fd);
sem_close(semaphore);
return 0;
}
7. Implement Network File System (NFS)
NFS Server Script (nfs_server_setup.sh)
#!/bin/bash
# Variables
SHARE_DIR="/srv/nfs_share"
CLIENT_SUBNET="[Link]/24"
# Install NFS server
sudo apt update
sudo apt install -y nfs-kernel-server
# Create and configure the shared directory
sudo mkdir -p $SHARE_DIR
sudo chown nobody:nogroup $SHARE_DIR
sudo chmod 777 $SHARE_DIR
# Add the shared directory to /etc/exports
echo "$SHARE_DIR $CLIENT_SUBNET(rw,sync,no_subtree_check)" | sudo tee -a /etc/exports
# Export the shared directory and restart NFS server
sudo exportfs -a
sudo systemctl restart nfs-kernel-server
echo "NFS server setup complete. Shared directory: $SHARE_DIR"
NFS Client Script (nfs_client_setup.sh)
#!/bin/bash
# Variables
SERVER_IP="[Link]" # Replace with your NFS server's IP
SHARE_DIR="/srv/nfs_share"
MOUNT_POINT="/mnt/nfs_share"
# Install NFS client
sudo apt update
sudo apt install -y nfs-common
# Create mount point
sudo mkdir -p $MOUNT_POINT
# Mount the NFS share
sudo mount $SERVER_IP:$SHARE_DIR $MOUNT_POINT
echo "NFS share mounted at $MOUNT_POINT"
Programmatic NFS Mounting in C
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *server_ip = "[Link]"; // Replace with your NFS server IP
const char *share_dir = "/srv/nfs_share";
const char *mount_point = "/mnt/nfs_share";
// Create the mount point directory
system("mkdir -p /mnt/nfs_share");
// Construct the mount command
char command[256];
snprintf(command, sizeof(command), "mount %s:%s %s", server_ip, share_dir, mount_point);
// Execute the mount command
int result = system(command);
if (result == 0) {
printf("NFS share mounted successfully at %s\n", mount_point);
} else {
printf("Failed to mount NFS share\n");
}
return 0;
}
8 . Creation of A BPEL (Business Process Execution Language) Module and a
Composite Application
Steps to Create a BPEL Module
1. Open JDeveloper: Launch JDeveloper and select the SOA Application workspace.
2. Create a New Application:
o Go to File > New > Applications > SOA Application.
o Give the application a name (e.g., BPELModuleApp), select a directory to save it, and
click OK.
3. Create a New Project within the Application:
o Right-click the application, select New > Project > SOA Project.
o Name the project (e.g., BPELModuleProject) and select BPEL Process as the type of
process to create.
o Specify the template for the BPEL process (for example, Synchronous BPEL Process or
Asynchronous BPEL Process).
4. Define the BPEL Process:
o A new BPEL process will open in the design view. You will see options like Receive,
Invoke, Assign, Reply, etc.
o Define the Input and Output messages for the BPEL process by dragging and dropping
these activities from the palette.
5. Create BPEL Activities:
o Configure the following basic activities to design your BPEL process flow:
Receive: Waits for an input from an external client.
Invoke: Calls another service as part of the process.
Assign: Performs data mapping or variable assignments.
Reply: Sends a response back to the client.
o For example, if you are creating a process to calculate an order total, the Receive activity
could accept order details, the Assign could calculate totals, and the Reply could send
back the result.
6. Configure Partner Links (Optional):
o If your BPEL process needs to communicate with external services, configure Partner
Links for those services.
7. Validate the Process:
o Once the process is defined, validate the design by clicking the Validate button in the IDE
to ensure there are no syntax or configuration errors.
8. Deploy the BPEL Module:
o Right-click the project, select Deploy > To Application Server.
o Choose the target application server (e.g., Oracle SOA Suite) and follow the prompts to
complete deployment.
Steps to Create a Composite Application
A Composite Application bundles together multiple services and components, allowing them to be
orchestrated and deployed as a single unit. In Oracle SOA, this involves configuring an SCA (Service
Component Architecture) Composite.
1. Create a New Composite Application:
o In the SOA Project, go to File > New > Project and select Composite Application Project.
o Name the composite application (e.g., CompositeOrderApplication).
2. Add Components to the Composite:
o The composite editor shows three main areas: Components, Services, and References.
o Drag the BPEL Module (from the previous step) into the Components section of the
composite.
3. Define Services and References:
o Service: Define a service interface for the composite that external clients will use to
access the application. For example, if your composite application is an Order Processing
system, this would be a web service interface for order submission.
o Reference: If your composite depends on other services (e.g., credit check, inventory),
add those as references here.
4. Wire Components:
o Wire the BPEL Module to the Service in the composite diagram, so incoming requests to
the service are routed to the BPEL process.
o If your BPEL process invokes other services (like inventory or credit checks), wire those
References to the BPEL process as well.
5. Define Business Rules and Mediators (Optional):
o If you need to incorporate business rules or transform data between services, add a
Business Rule component or a Mediator component within the composite.
o The mediator can handle data transformations and message routing, while the business
rules component can define conditional logic for process flows.
6. Deploy the Composite Application:
o Once the composite design is complete, validate the configuration by clicking the
Validate button.
o Right-click the composite application project and choose Deploy > To Application
Server.
o Follow the prompts to deploy the composite to the target application server.
7. Test the Composite Application:
o Use the Enterprise Manager Console (for Oracle SOA) or any web services testing tool
(like SOAP UI) to test the composite application.
o Send a test request to the service interface, and observe how the BPEL process handles
the request, invokes other services, and responds.
8. Web Service Programming
There are two main types of web services: SOAP-based and RESTful. Below, I'll cover how to create a
basic example of each type using Java.
1. SOAP-based Web Service (Java JAX-WS)
SOAP (Simple Object Access Protocol) is a protocol that uses XML for message exchange. JAX-WS (Java
API for XML Web Services) is a Java API for creating SOAP web services.
Steps to Create a SOAP Web Service with JAX-WS
1. Set Up a Java Project:
o Create a new Java project in your IDE (e.g., Eclipse or IntelliJ).
2. Define the Service Endpoint Interface (SEI):
o The SEI defines the methods available in the web service.
import [Link];
import [Link];
@WebService
public interface CalculatorService {
@WebMethod
int add(int a, int b);
@WebMethod
int subtract(int a, int b);
}
Implement the Service:
Create an implementation class for the SEI.
import [Link];
@WebService(endpointInterface = "CalculatorService")
public class CalculatorServiceImpl implements CalculatorService {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int subtract(int a, int b) {
return a - b;
}
}
Publish the Web Service:
import [Link];
public class CalculatorServicePublisher {
public static void main(String[] args) {
[Link]("[Link] new CalculatorServiceImpl());
[Link]("Calculator Service is running at [Link]
}
}
RESTful Web Service (Java JAX-RS)
REST (Representational State Transfer) uses standard HTTP methods (GET, POST, PUT, DELETE) and
typically works with JSON or XML. JAX-RS (Java API for RESTful Web Services) is an API for creating
RESTful web services in Java.
Steps to Create a RESTful Web Service with JAX-RS
1. Set Up a Java Project:
o Create a Java project and add dependencies for JAX-RS. Most Java EE servers (like Tomcat
or GlassFish) come with JAX-RS support, or you can add a dependency like Jersey.
xml
Copy code
<!-- Maven dependency for Jersey -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.34</version>
</dependency>
2. Define a RESTful Resource Class:
o This class represents the resource that the web service will expose.
java
Copy code
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Path("/calculator")
public class CalculatorResource {
@GET
@Path("/add")
@Produces(MediaType.TEXT_PLAIN)
public String add(@QueryParam("a") int a, @QueryParam("b") int b) {
return [Link](a + b);
}
@GET
@Path("/subtract")
@Produces(MediaType.TEXT_PLAIN)
public String subtract(@QueryParam("a") int a, @QueryParam("b") int b) {
return [Link](a - b);
}
}
3. Configure JAX-RS Application:
o Create an application configuration class that sets up the JAX-RS application.
java
Copy code
import [Link];
import [Link];
@ApplicationPath("/api")
public class CalculatorApplication extends Application {
// No need to implement any methods for basic setup
}
4. Deploy and Test the RESTful Web Service:
o Deploy the application on a server (e.g., Tomcat or GlassFish).
o The endpoints should be accessible at:
[Link]
[Link]
o You can test these endpoints in a browser or with a tool like Postman.