Cloud Computing 32890
Cloud Computing 32890
MASTER OF SCIENCE
In
COMPUTER SCIENCE
Year 2023-2024
By
CERTIFICATE
Name Application ID
Mr. Prathamesh Rajigare 32890
This code sets up a RESTful web service using Java with the help of the javax.ws.rs API to return the current time.
1. Make sure you have the necessary dependencies in your project (e.g., javax.ws.rs, Jersey).
2. Run the server code on a Java server container like Tomcat or use a framework like Jersey's Grizzly HTTP
server for a standalone version.
// TimeServer.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Path("/time")
@GET
@Produces(MediaType.TEXT_PLAIN)
This service will provide the current time in the format YYYY-MM-DD HH:MM:SS whenever accessed via HTTP GET.
1. Add this service to a Jersey-based server (e.g., in a web.xml or via annotations for configuration).
This Java client calls the Time Server and displays the current time received from the server.
// TimeClient.java
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
.request(MediaType.TEXT_PLAIN)
.get(String.class);
• If the server logs requests, you’ll see log entries indicating incoming requests to the /time endpoint.
Client Output:
Running TimeClient.java should yield something similar to the following output in the console:
sql
Copy code
We'll set up the server code for a REST API that provides a list of friends as a JSON response.
This example uses javax.ws.rs and javax.ws.rs.core APIs along with Jersey to create a RESTful web service.
java
Copy code
// Friend.java
this.id = id;
this.name = name;
this.email = email;
java
Copy code
// FriendService.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;
@Path("/friends")
@GET
@Produces(MediaType.APPLICATION_JSON)
return friends;
}
}
This code defines a RESTful endpoint /friends that, when accessed via an HTTP GET request, returns a list of friends in
JSON format.
1. Package and deploy the application on a Java web server (e.g., Tomcat) or use Jersey’s Grizzly HTTP server for
standalone testing.
When you access http://localhost:8080/<your_app_context>/friends, the service should return a JSON response
similar to this:
json
Copy code
{
"id": 1,
"email": "[email protected]"
},
"id": 2,
"email": "[email protected]"
},
"id": 3,
"email": "[email protected]"
Here's a simple Java client that consumes the FriendService API and prints the list of friends.
java
Copy code
// FriendClient.java
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import java.util.List;
.request(MediaType.APPLICATION_JSON)
System.out.println("List of Friends:");
System.out.println("ID: " + friend.getId() + ", Name: " + friend.getName() + ", Email: " + friend.getEmail());
Expected Output
Running FriendClient.java should yield something like the following in the console:
yaml
Copy code
List of Friends:
Server Code
java
Copy code
// Matrix.java
import java.util.Arrays;
public Matrix() {}
this.data = data;
return data;
this.data = data;
@Override
return Arrays.deepToString(data);
}
This class represents a matrix with a 2D integer array data.
java
Copy code
// StrassenMatrixMultiplier.java
int n = A.length;
if (n == 1) {
return C;
// Calculate submatrices of C
join(C11, C, 0, 0);
join(C12, C, 0, n / 2);
join(C21, C, n / 2, 0);
join(C22, C, n / 2, n / 2);
return C;
private static void split(int[][] P, int[][] C, int iB, int jB) { /*...*/ }
private static void join(int[][] C, int[][] P, int iB, int jB) { /*...*/ }
Note: To keep the code concise, implement add, subtract, split, and join methods similarly to how matrix operations
are typically handled.
Step 3: Define the Matrix Multiplication Service
java
Copy code
// MatrixService.java
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/matrix")
@POST
@Path("/multiply")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
int[][] A = request.getMatrixA();
int[][] B = request.getMatrixB();
// Validate matrices
return Response.status(Response.Status.BAD_REQUEST)
.build();
This service takes a JSON object containing two matrices (matrixA and matrixB), multiplies them using Strassen’s
algorithm, and returns the result as a JSON response.
To test the service, you can use a tool like Postman. Here’s an example of the JSON payload you can send to the
endpoint POST http://localhost:8080/<your_app_context>/matrix/multiply:
json
Copy code
"matrixA": [
[1, 2],
[3, 4]
],
"matrixB": [
[5, 6],
[7, 8]
Expected Output
The server will return the result of the matrix multiplication in JSON format:
json
Copy code
"data": [
[19, 22],
[43, 50]
]
Here’s a Java client to send the matrices to the service and print the result:
java
Copy code
// MatrixClient.java
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
);
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(request, MediaType.APPLICATION_JSON));
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
System.out.println("Resulting Matrix:");
}
System.out.println();
} else {
}}
yaml
Copy code
Resulting Matrix:
19 22
43 50
4. Demonstrate CRUD Operations with Database Using SOAP or RESTful Web Service
• Objective: Implement basic CRUD (Create, Read, Update, Delete) operations using a database.
Create a Maven project and add the following dependencies in your pom.xml file:
xml
Copy code
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>EmployeeCRUD</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
properties
Copy code
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
java
Copy code
package com.example.employeecrud;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Employee() {}
this.name = name;
this.department = department;
this.salary = salary;
Create an interface EmployeeRepository.java to handle database operations using Spring Data JPA.
java
Copy code
package com.example.employeecrud;
import org.springframework.data.jpa.repository.JpaRepository;
java
Copy code
package com.example.employeecrud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/employees")
@Autowired
private EmployeeRepository employeeRepository;
// Create Employee
@PostMapping
return employeeRepository.save(employee);
@GetMapping
return employeeRepository.findAll();
@GetMapping("/{id}")
// Update Employee by ID
@PutMapping("/{id}")
if (employee.isPresent()) {
existingEmployee.setName(employeeDetails.getName());
existingEmployee.setDepartment(employeeDetails.getDepartment());
existingEmployee.setSalary(employeeDetails.getSalary());
return ResponseEntity.ok(updatedEmployee);
} else {
return ResponseEntity.notFound().build();
// Delete Employee by ID
@DeleteMapping("/{id}")
if (employeeRepository.existsById(id)) {
employeeRepository.deleteById(id);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
In the terminal, run the following command to start the Spring Boot application:
bash
Copy code
mvn spring-boot:run
The application will run on http://localhost:8080. You can test the endpoints using tools like Postman or curl.
1. Create an Employee
o Request Body:
json
Copy code
"name": "Alice",
"department": "HR",
"salary": 50000.0
}
o Response:
json
Copy code
"id": 1,
"name": "Alice",
"department": "HR",
"salary": 50000.0
o Response:
json
Copy code
"id": 1,
"name": "Alice",
"department": "HR",
"salary": 50000.0
3. Get Employee by ID
o Response:
json
Copy code
"id": 1,
"name": "Alice",
"department": "HR",
"salary": 50000.0
4. Update Employee
o Endpoint: PUT http://localhost:8080/api/employees/1
o Request Body:
json
Copy code
"department": "Finance",
"salary": 55000.0
o Response:
json
Copy code
"id": 1,
"department": "Finance",
"salary": 55000.0
5. Delete Employee
Explanation
2. Read Posts: Users can view all posts or a specific post by ID.
Tech Stack
Project Setup
1. Initialize a Spring Boot Project with Spring Web and Spring Data JPA.
xml
Copy code
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>MicroBlogger</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
In src/main/resources/application.properties:
properties
Copy code
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
java
Copy code
package com.example.microblogger;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Post() {}
this.author = author;
this.content = content;
}
Step 4: Create the Repository
java
Copy code
package com.example.microblogger;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
Copy code
package com.example.microblogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/posts")
@Autowired
@PostMapping
return postRepository.save(post);
@GetMapping
return postRepository.findAll();
// Get a post by ID
@GetMapping("/{id}")
// Update a post by ID
@PutMapping("/{id}")
if (post.isPresent()) {
existingPost.setAuthor(postDetails.getAuthor());
existingPost.setContent(postDetails.getContent());
return ResponseEntity.ok(postRepository.save(existingPost));
} else {
return ResponseEntity.notFound().build();
// Delete a post by ID
@DeleteMapping("/{id}")
if (postRepository.existsById(id)) {
postRepository.deleteById(id);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
@GetMapping("/author/{author}")
return postRepository.findByAuthor(author);
}
}
bash
Copy code
mvn spring-boot:run
1. Create a Post
o Request Body:
json
Copy code
"author": "john_doe",
o Response:
json
Copy code
"id": 1,
"author": "john_doe",
o Response:
json
Copy code
"id": 1,
"author": "john_doe",
3. Get Post by ID
o Response:
json
Copy code
"id": 1,
"author": "john_doe",
4. Update a Post
o Request Body:
json
Copy code
"author": "john_doe",
o Response:
json
Copy code
"id": 1,
"author": "john_doe",
5. Delete a Post
json
Copy code
"id": 1,
"author": "john_doe",
Explanation
• Repository: PostRepository provides basic CRUD functionality and a custom method for finding posts by
author.
• Controller: PostController manages the API endpoints, allowing users to create, read, update, delete, and
filter posts.
6. To develop an application that consumes Google’s Search or Google Maps RESTful API, you’ll need to set up
the Google API and use it to make HTTP requests. Here, I’ll demonstrate how to consume Google Maps API
in a Java Spring Boot application to search for nearby places.
Prerequisites
o Go to Google Cloud Console, enable Google Maps API (such as Places API), and create an API key.
Note that this API key should be kept secure.
2. Dependencies: We’ll use Spring Boot along with RestTemplate to make HTTP requests.
Project Setup
2. Add Google API Key: Store the Google API key in a properties file for security.
Step-by-Step Implementation
xml
Copy code
<dependencies>
<!-- Spring Boot Starter Web for REST API and HTTP requests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
properties
Copy code
google.api.key=YOUR_GOOGLE_API_KEY
java
Copy code
package com.example.googlemaps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
@Service
@Value("${google.api.key}")
String url =
UriComponentsBuilder.fromHttpUrl("https://maps.googleapis.com/maps/api/place/nearbysearch/json")
.queryParam("location", location)
.queryParam("radius", radius)
.queryParam("type", type)
.queryParam("key", apiKey)
.toUriString();
• location: The latitude and longitude of the search area (e.g., 37.7749,-122.4194 for San Francisco).
• radius: The search radius in meters (e.g., 500 for 500 meters).
java
Copy code
package com.example.googlemaps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/maps")
@Autowired
@GetMapping("/nearby")
• Endpoint: /api/maps/nearby
• Parameters:
bash
Copy code
mvn spring-boot:run
You can test the API endpoint using a tool like Postman or curl:
o URL: http://localhost:8080/api/maps/nearby?location=37.7749,-
122.4194&radius=500&type=restaurant
json
Copy code
"html_attributions": [],
"results": [
"geometry": {
"location": {
"lat": 37.7741,
"lng": -122.4192
},
},
"geometry": {
"location": {
"lat": 37.7745,
"lng": -122.4195
},
],
"status": "OK"
}
The results array contains nearby places with information like name, location coordinates, and vicinity (address).
Explanation
1. GoogleMapsService: This service class handles requests to Google Maps API using RestTemplate.
2. GoogleMapsController: Exposes the /api/maps/nearby endpoint to accept search parameters and return
nearby places.
3. Output: The response includes details about nearby places, including names, coordinates, and addresses.
7. Develop application to download image/video from server or upload image/video
to server using MTOM techniques.
Steps
1. Create a JAX-WS web service with MTOM support for uploading and downloading files.
Prerequisites
Define a web service interface that enables file upload and download. Annotate the interface to support MTOM.
java
Copy code
package com.example.mtom;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.soap.MTOM;
import javax.activation.DataHandler;
@MTOM
@WebService
@WebMethod
@WebMethod
In this implementation, files are stored on the server’s local file system.
java
Copy code
package com.example.mtom;
import javax.activation.DataHandler;
import javax.jws.WebService;
import java.io.*;
@WebService(endpointInterface = "com.example.mtom.FileService")
@Override
int bytesRead;
outputStream.write(buffer, 0, bytesRead);
} catch (IOException e) {
e.printStackTrace();
@Override
} else {
return null;
In this code:
• The uploadFile method reads an incoming file stream and saves it to the server's local storage.
• The downloadFile method retrieves a file from the server's file system.
Configure and deploy the service to your web server (e.g., Apache Tomcat).
xml
Copy code
<servlet>
<servlet-name>FileService</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileService</servlet-name>
<url-pattern>/FileService</url-pattern>
</servlet-mapping>
2. Deploy the service on your server and access the WSDL at:
bash
Copy code
http://localhost:8080/your-app-name/FileService?wsdl
shell
Copy code
The client will call the web service to upload and download files.
java
Copy code
package com.example.mtom.client;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import com.example.mtom.FileService;
service.uploadFile("uploaded_image.jpg", fileData);
java
Copy code
package com.example.mtom.client;
import javax.activation.DataHandler;
import java.io.*;
if (fileData != null) {
int bytesRead;
outputStream.write(buffer, 0, bytesRead);
} catch (IOException e) {
e.printStackTrace();
} else {
1. Start the Server: Ensure the web service is deployed and running on your web server.
3. Download the File: Run FileClientDownload to download the file from the server.
Expected Output