Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

SRI KRISHNA COLLEGE OF ENGINEERING AND TECHNOLOGY

(AN AUTONOMOUS INSTITUTION,


AFFILIATED TO ANNAUNIVERSITY, CHENNAI)
COIMBATORE–641008

DEPARTMENT OF INFORMATION TECHNOLOGY

21CS403 – WEB FRAMEWORKS LABORATORY

CONTINUOUS ASSESSMENT RECORD

Submitted by

Name:……….…………………..……………..

Register No :………….……………….………

Degree & Branch:………….………………..…

Class & Semester:………….……………….…

Academic Year:………….……………….…….
SRI KRISHNA COLLEGE OF ENGINEERING AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION,
AFFILIATED TO ANNAUNIVERSITY, CHENNAI)
COIMBATORE–641008

DEPARTMENT OF INFORMATION TECHNOLOGY

21CS403 – WEB FRAMEWORKS LABORATORY

Continuous Assessment

Record

Submitted by

Name: ……..…….……………………..………… Register No. :.............……………………

Class/Semester:…………………………………. Degree & Branch:……………………………..

BONAFIDE CERTIFICATE

This is to certify that this record is the bonafide record of work done by Mr./Ms.
during the academic year 2022–2023.

Faculty In-charge Head of the Department

Submitted for the University practical examination held on

INTERNAL EXAMINER EXTERNAL EXAMINER


SRIKRISHNA COLLEGE OF ENGINEERING AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION,
AFFILIATED TO ANNAUNIVERSITY, CHENNAI)
COIMBATORE–641008

DEPARTMENT OF INFORMATION TECHNOLOGY

21CS403 – WEB FRAMEWORKS LABORATORY

Record of laboratory

ODD SEMESTER- 2022-2023

Name of the Faculties Dr. T.Keerthika


Dr. K N. Sivabalan
Dr.U.Barakkath Nisha

CONTINUOUS EVALUATION SHEET

REFERENCES RUBRICS TABLE

Range of Marks
Criteria Below
Excellent Good Average
Average
Aim & Algorithm
(20 marks)
19-20 17-18 15-16 0-14

Program with Proper


27-30 21-26 15-20 0-14
Syntax and Structure
(30 Marks)
Compilation and
27-30 21-26 15-20 0-14
Debugging
(30 Marks)
Documentation 9-10 7-8 5-6 0-4
(10 Marks)
Viva(10 Marks) 9-10 7-8 5-6 0-4

OverallMarks 90-100 70-89 50-69 0-49


INDEX
Page
Ex.No Name of the Experiment
No.
1 Display the information about the current weather in a certain location using RESTful API
using a weather forecast provider such as openweathermap.org.
Create your own app that embeds information about flights, hotels, and rental cars using
2
Skyscanner API.
Create a simple Spring Application and inject the literal values by setter injection. So, create
3
a simple class Employee having three attributes Id, Name, and Designation. Create setter
methods for these attributes and a simple method to print the details of the student.
Create a simple payroll service that manages the employees of a company. Store employee
4
objects in a database, and access them (via something called JPA)
5 Create a simple payroll service that manages the employees of a company. Perform the
following LIKE queries using query methods with the keywords Containing, Contains,
IsContaining, StartsWith and EndsWith
6 Create a simple payroll service that manages the employees of a company. Perform the
following LIKE queries using query methods with the keywords NotContains, NotContaining
and NotLike
7 Create a Spring Boot application with Student entity and Student JPA repository. Use Spring
Rest Controller API to perform CRUD operations on Student data
8 Build a simple Rest API application called Donors. This application manages blood donors
information and allows its users to Add a new donor, update existing donor information, view
existing donors and delete a donor information from the application
9 Develop a Spring Boot REST API for managing personal finances, allowing users to track
their income, expenses, and budget goals. Implement a one-to-many relationship between
users and transactions, enabling users to view their transaction history and financial
summaries.
10 Create a Spring Boot REST API for smart home automation that allows users to control
various IoT devices in their home. Implement a one-to-many relationship between users and
devices, enabling users to manage multiple devices and perform actions such as turning them
on/off or adjusting settings remotely.
11 Develop a Spring Boot REST API for managing personal finances, allowing users to track their
income, expenses, and budget goals. Implement a one-to-many relationship between users
and transactions, enabling users to view their transaction history and financial summaries.
12 Develop a Spring Boot REST API for managing assets and tracking their ownership details.
Implement a bidirectional one-to-one relationship between assets and their respective
owners, enabling users to view asset information along with the details of the owner and
vice versa.
SRIKRISHNACOLLEGEOFENGINEERINGANDTECHNOLOGY
COIMBATORE –641008

(AN AUTONOMOUS INSTITUTION,


AFFILIATED TO ANNAUNIVERSITY, CHENNAI)
COIMBATORE–641008

DEPARTMENT OF INFORMATION TECHNOLOGY

21CS403 – WEB FRAMEWORKS LABORATORY

ODD SEMESTER: 2022-2023

Components EX1 EX2 EX3 EX4 EX5 EX6 EX7 EX8 EX9 EX10 EX11 EX12

Aim & Algorithm


(20 marks)

Program with Proper


Syntax and Structure
(30 Marks)
Compilation and
Debugging
(30 Marks)
Documentation
(10Marks)
Viva
(10Marks)

TOTAL

Consolidated Marks(100) _

Faculty Signature __
Ex.no: 1 Developing a News API Web Application with Pagination and Sorting
Date: Functionalities

AIM:
To create a web application that fetches the object from the NewsAPI based on specific categories
or keywords. The application should allow users to search for news articles using JPQL (Java Persistence
Query Language), implement pagination and sorting functionalities for efficient article retrieval, and ensure
transactional behavior when interacting with the NewsAPI.

Algorithm:
1. Create ApiController class to handle API requests.
2. Develop NewsService class to interact with the NewsAPI.
3. Implement READ operations for accessing news articles.
4. Configure endpoints for retrieving news articles based on categories, sources, pagination, and sorting.
5. Fetch news articles using the NewsAPI by making HTTP requests.

Program:
1. ApiController.java:
@RestController
@RequestMapping("/api")
public class ApiController {

@Autowired
private NewsService newsService;

@GetMapping("/news/source/{source}")
public ResponseEntity<?> getNewsBySource(@PathVariable String source) {
List<Article> articles = newsService.getNewsBySource(source);
return ResponseEntity.ok().body(articles);
}

@GetMapping("/country/{country}/category/{category}")
public ResponseEntity<?> getNewsByCountryAndCategory(@PathVariable String country, @PathVariable String
category) {
List<Article> articles = newsService.getNewsByCountryAndCategory(country, category);
return ResponseEntity.ok().body(articles);
}

@GetMapping("/country/{country}/category/{category}/{pageNumber}/{pageSize}/{sortField}")
public ResponseEntity<?> getNewsByCountryAndCategoryWithPaginationAndSorting(
@PathVariable String country,
@PathVariable String category,
@PathVariable int pageNumber,
@PathVariable int pageSize,
@PathVariable String sortField
){
Page<Article> articlesPage = newsService.getNewsByCountryAndCategoryWithPaginationAndSorting(
country, category, pageNumber, pageSize, sortField);
return ResponseEntity.ok().body(articlesPage);
}
}

1
2. NewsService.java:
@Service
public class NewsService {

@Value("${newsapi.apikey}")
private String apiKey;

private final RestTemplate restTemplate = new RestTemplate();

public List<Article> getNewsBySource(String source) {


String url = "https://newsapi.org/v2/top-headlines?sources=" + source + "&apiKey=" + apiKey;
ResponseEntity<NewsResponse> responseEntity = restTemplate.getForEntity(url, NewsResponse.class);
return responseEntity.getBody().getArticles();
}

public List<Article> getNewsByCountryAndCategory(String country, String category) {


String url = "https://newsapi.org/v2/top-headlines?country=" + country + "&category=" + category + "&apiKey="
+ apiKey;
ResponseEntity<NewsResponse> responseEntity = restTemplate.getForEntity(url, NewsResponse.class);
return responseEntity.getBody().getArticles();
}

public Page<Article> getNewsByCountryAndCategoryWithPaginationAndSorting(


String country, String category, int pageNumber, int pageSize, String sortField) {
String url = "https://newsapi.org/v2/top-headlines?country=" + country + "&category=" + category
+ "&page=" + pageNumber + "&pageSize=" + pageSize + "&sortBy=" + sortField + "&apiKey=" + apiKey;
ResponseEntity<NewsResponse> responseEntity = restTemplate.getForEntity(url, NewsResponse.class);
List<Article> articles = responseEntity.getBody().getArticles();
return new PageImpl<>(articles, PageRequest.of(pageNumber, pageSize), articles.size());
}
}

3. Article.java:
@Data
public class Article {
private String author;
private String title;
private String description;
private String url;
private String urlToImage;
private String publishedAt;
private String content;
}

4. NewsResponse.java:
@Data
public class NewsResponse {
private String status;
private int totalResults;
private List<Article> articles;
}

5. Make sure to configure your application.properties file to include the NewsAPI key:
newsapi.apikey=YOUR_API_KEY

2
Output:

Result :
The program compiled and executed successfully.

3
Ex.no: 2
Date:
Chuck Norris Joke Fetcher Web Application

AIM:
The aim of this web application is to fetch Chuck Norris jokes from the Chuck Norris API based on specific
categories or keywords. It should provide users with the ability to search for jokes using JPQL (Java
Persistence Query Language), implement pagination and sorting functionalities for efficient joke retrieval,
and ensure transactional behavior when interacting with the Chuck Norris API.

Algorithm:
1. Start a new Spring Boot project.
2. Create an "ApiController.java" file in the "Controller" folder to handle API requests.
3. Develop a "JokeService.java" file in the "Service" folder to interact with the Chuck Norris API and
implement reading operations for fetching jokes.
4. Integrate Chuck Norris API (https://api.chucknorris.io) to fetch jokes.
5. Define API endpoints:
• Fetch all categories: /api/jokes/categories
• Fetch joke by category: /api/jokes/random?category={category}
• Free text search: /api/jokes/search?query={query}
• Fetch by ID: /api/jokes/randomById?query={id}
• Fetch Exclude: /api/jokes/random?exclude={category1,category2}
• Fetch Include: /api/jokes/random?include={category1,category2}
6. Add pagination and sorting for efficient joke retrieval.
7. Thoroughly test the application, covering different scenarios including invalid inputs.
8. Document API endpoints and their usage.
9. Deploy the application to a production environment, ensuring proper configuration.

Program:
1. Define Controller class:
@RestController
@RequestMapping("/api/jokes")
public class ApiController {
@Autowired
private JokeService jokeService;
@GetMapping("/categories")
public List<String> getCategories() {
return jokeService.getCategories();
}
@GetMapping("/random")
public Joke getByCategory(@RequestParam String[] category) {
return jokeService.getRandomJoke(category);
}

@GetMapping("/randomById")

4
public Joke getById(@RequestParam String query) {
return jokeService.getRandomJokeById(query);
}
@GetMapping("/randomExclude")
public Joke exclude(@RequestParam String[] exclude) {
return jokeService.getRandomJokeExclude(exclude);
}
@GetMapping("/randomInclude")
public Joke include(@RequestParam String[] include) {
return jokeService.getRandomJokeInclude(include);
}
}
2. Define Service class :
@Service
public class JokeService {
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.chucknorris.io/jokes";
public List<String> getCategories() {
String[] categories = restTemplate.getForObject(url+"/categories",
String[].class);
return Arrays.asList(categories);
}
public Joke getRandomJoke(String[] categories) {
String s = String.join(",", categories);
System.out.println(s);
return restTemplate.getForObject(url+"/random?category="+s, Joke.class);
}
public Joke getRandomJokeById(String id){
return restTemplate.getForObject(url + "/random?query=" + id, Joke.class);
}
public Joke getRandomJokeExclude(String[] categories)
{
String s = String.join(",", categories);
System.out.println(s);
return restTemplate.getForObject(url+"/random?exclude="+s, Joke.class);
}
public Joke getRandomJokeInclude(String[] categories)
{
String s = String.join(",", categories);
return restTemplate.getForObject(url+"/random?include="+s, Joke.class);
} }
3. Create Joke Class to handle the object:

5
@Component
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Joke {
private String[] categories;
private String created_at;
private String icon_url;
private String id;
private String updated_at;
private String url;
private String value;
}

Output:

Result :
The program compiled and executed successfully.

6
Ex.no: 3 Employee Management System with Spring Boot:
Date: Setter Injection and RESTful API

AIM:
The aim of this Web Application is to create a simple Spring Application and inject the literal values by
setter injection. So, create a simple class Employee having three attributes ID, Name, and Designation.
Create setter methods for these attributes and a simple method to print the details of the employee.

Algorithm:
1. Create a new Spring Boot project with OpenJDK 11.
2. Set up the folder structure:
3. Create "Controller", "Models", "Repository", and "Service" folders inside the "src" directory.
4. In the "Models" folder, create an "Employee.java" file with attributes: id (int), name (String), and
designation (String). Implement setter methods for these attributes.
5. In the "Repository" folder, create an "EmployeeRepo.java" file to manage CRUD operations for the
Employee entity.
6. In the "Service" folder, create an "EmployeeService.java" file. Implement business logic for getting
employee details and other functionalities.
7. In the "Controller" folder, create an "ApiController.java" file. Implement RESTful API endpoints for
interacting with employee data:
• POST "/" --> true/false
• GET "/{id}" --> List of employee objects
• GET "/" --> List of employee objects
• GET "/employees/groupBy" --> Returns grouped employee data by designation, salary;
• GET "/employees/findByDesignation?value={value}" --> Returns employee data filtered
• GET "/employees/salaryRange?minSalary={minSalary}&maxSalary={maxSalary}" --> Returns
employee data within the specified salary range
8. Configure “ application.properties” file with the provided database connection and Hibernate
configurations.
9. Test each API endpoint using tools like Postman to ensure functionality.
10. Deploy the application to a server environment, ensuring proper configuration.

Program:
1. Define Controller class:
@RestController
public class ApiController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/")
public Boolean saveEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}
@GetMapping("/")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();

7
}
@GetMapping("/{id}")
public Employee getEmployee(@PathVariable int id) {
return employeeService.getEmployye(id);
}
@GetMapping("/employees/groupBy")
public List<Employee> groupBy() {
return employeeService.groupBy();
}
@GetMapping("/employees/findByDesignation")
public Employee findBy(@RequestParam String value) {
return employeeService.findByDesignation(value);
}
@GetMapping("/employees/salaryRange")
public List<Employee> getEmployeesBetween(@RequestParam int minSalary,
@RequestParam int maxSalary) {
return employeeService.getEmployeesBetween(minSalary, maxSalary);
}
}
2. Define Service class :
@Service
public class EmployeeService {
@Autowired
private EmployeeRepo employeeRepo;
public boolean saveEmployee(Employee employee){
try{
employeeRepo.save(employee);
return true;
}
catch(Exception e) {
return false;
}
}
public List<Employee> getAllEmployees(){
return employeeRepo.findAll();
}
public Employee getEmployye (int id){
return employeeRepo.findById(id).orElse(null);
}
public List<Employee> groupBy(){
return employeeRepo.groupBy();
}

8
public Employee findByDesignation(String value){
return employeeRepo.findByDesignation(value);
}
public List<Employee> getEmployeesBetween(int min, int max){
return employeeRepo.getEmployeesBetween(min, max);
}
}
3. Create Repository interface to implement JPQL Queries:

@Repository
public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
@Query(value = "Select * from employee group by designation,salary,id",
nativeQuery = true)
public List<Employee> groupBy();
@Query("Select e from Employee e where e.designation = ?1")
public Employee findByDesignation(String value);
@Query(value = "Select * from employee where salary between ?1 and ?2",
nativeQuery = true)
public List<Employee> getEmployeesBetween(int min, int max);
}
4. Create a Model class:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
@Id
private int id;
private String name;
private String designation;
private int salary;
}

9
Output:

10
Result :
The program compiled and executed successfully.

11
Ex.no: 4 Employee Payroll Management System with Spring Boot: JPA, CRUD
Date: Operations, and RESTful API

AIM:
The Aim of the application is to develop a basic Employee Payroll Management System using Spring Boot.
This system will allow users to perform CRUD operations on employee records and retrieve specific
employee information through RESTful API endpoints.

Algorithm:
1. Begin by setting up a new Spring Boot project.
2. Create the project structure as Inside the "src" directory, establish the following folders: "Controller",
"Models", "Service", and "Repository".
3. Implement API endpoints in the "ApiController.java" file:
a. POST "/" to add a new employee record to the database.
b. GET "/{id}" to retrieve employee information by id.
c. GET "/" to fetch the list of all employees.
d. GET "/employee/first-three-characters-of-first-name" to return the first three characters of the
first name of all employees.
e. GET "/employees/hired/{hire_date}" to fetch employees hired on a specified date.
4. Configure the application.properties file with database connection settings provided.
5. Test API endpoints using tools like Postman to ensure functionality.
6. Run the application using 'mvn spring-boot:run' command.
7. Monitor application performance and handle any encountered issues.
8. Document API endpoints for future reference.
9. The Employee Payroll Management System is now operational, providing basic functionalities to
manage employee records.

Program:
1. Define Controller class:
@RestController
@RequestMapping("/")
public class ApiController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/")
public boolean addEmployee(@RequestBody Employee employee) {
return employeeService.addEmployee(employee);
}
@GetMapping("/{id}")
public Employee getEmployeeById(@PathVariable("id") int id) {
return employeeService.getEmployeeById(id);
}

@GetMapping("/")

12
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/employees/first-three-characters-of-first-name")
public List<String> getFirstThreeCharactersOfFirstName() {
return employeeService.getFirstThreeCharactersOfFirstName();
}
@GetMapping("/employees/hired/{hireDate}")
public List<Employee> getEmployeesHiredOnDate(@PathVariable("hireDate")
LocalDate hireDate) {
return employeeService.getEmployeesHiredOnDate(hireDate);
}
}
2. Define Service class :
@Service
public class EmployeeService {
@Autowired
private EmployeeRepo employeeRepo;
public boolean addEmployee(Employee employee) {
try{
employeeRepo.save(employee);
return true;
}
catch(Exception e){
return false;
}
}
public Employee getEmployeeById(int id) {
return employeeRepo.findById(id).orElse(null);
}
public List<Employee> getAllEmployees() {
return employeeRepo.findAll();
}
public List<String> getFirstThreeCharactersOfFirstName() {
List<Employee> employees = employeeRepo.findAll();
return employees.stream()
.map(employee -> employee.getName().substring(0,
Math.min(employee.getName().length(), 3)))
.collect(Collectors.toList());
}
public List<Employee> getEmployeesHiredOnDate(LocalDate hireDate) {
return employeeRepo.findByHireDate(hireDate);

13
}
}
3. Create a Repository to handle the connectivity:
@Repository
public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
List<Employee> findByHireDate(LocalDate hire_date);
}

4. Create a Model class with Entity Annotation:


@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Employee
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String address;
private String phoneNumber;
private String email;
private String jobTitle;
private String department;
private double salary;
private LocalDate hireDate;
}

Output:

14
Result :
The program compiled and executed successfully.

15
Ex.no: 5 Employee Payroll Management System Wit Spring Boot: LIKE Queries
Date: and RESTful API OVERVIEW.

Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee data by
storing it in a database and providing CRUD operations via RESTful API endpoints.

Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.

Program:
1.Define controller class

@RestController
public class ApiController {
@Autowired
public EmployeeService employeeService;
@PostMapping("/")
public Boolean postData(@RequestBody Employee employee) {
return employeeService.postData(employee);
}
@GetMapping("/getstart/{name}")
public List<Employee> getStartWith(@PathVariable String name){
return employeeService.getByStartWith(name);
}
@GetMapping("/getends/{name}")
public List<Employee> getEndsWith(@PathVariable String name){
return employeeService.getByEndsWith(name);
}
@GetMapping("/getcontains/{name}")
public List<Employee> getContains(@PathVariable String name){
return employeeService.getByContains(name);
}
@GetMapping("/getcontaining/{name}")
public List<Employee> getContaining(@PathVariable String name){
return employeeService.getByContaining(name);
}
@GetMapping("/getIscontaining/{name}")
public List<Employee> getIsContaining(@PathVariable String name){
return employeeService.getByIsContaining(name);
}
}

16
2.Model class
public class Employee {
@Id
private int id;
private String name;
private String designation;
public Employee(int id, String name, String designation) {
this.id = id;
this.name = name;
this.designation = designation;
}
}
3.Service Class

@Service
public class EmployeeService {
@Autowired
public EmployeeRepo employeeRepo;

public boolean postData(Employee employee){


try{
employeeRepo.save(employee);
return true;
}
catch(Exception e){
return false;
}
}

public List<Employee> getByStartWith(String name){


return employeeRepo.findAllByNameStartsWith(name);
}
public List<Employee> getByEndsWith(String name) {
return employeeRepo.findAllByNameEndsWith(name);
}
public List<Employee> getByContains(String name){
return employeeRepo.findAllByNameContains(name);
}
public List<Employee> getByContaining(String name) {
return employeeRepo.findAllByNameContaining(name);
}
public List<Employee> getByIsContaining(String name){
return employeeRepo.findAllByNameIsContaining(name);
}
}
4 .Repository Class
@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
public List<Employee> findAllByNameContaining(String name);
public List<Employee> findAllByNameIsContaining(String name);
public List<Employee> findAllByNameContains(String name);
public List<Employee> findAllByNameStartsWith(String name);
public List<Employee> findAllByNameEndsWith(String name);
}

17
Output:

18
Result:
The program compiled and executed successfully.

19
Ex.no: 6 Employee Payroll Management System with Spring Boot:
Date: NOT LIKE Queries and RESTful API

Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee
data by storing it in a database and providing CRUD operations via RESTful API endpoints.

Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@Autowired
public EmployeeService employeeService;

@PostMapping("/")
public Boolean postData(@RequestBody Employee employee) {
return employeeService.postData(employee);
}

@GetMapping("/getnotcontains/{name}")
public List<Employee> getNotContains(@PathVariable String name) {
return employeeService.getNotContains(name);
}

@GetMapping("/getnotcontaining/{name}")
public List<Employee> getNotContaining(@PathVariable String name) {
return employeeService.getNotContaining(name);
}
@GetMapping("/getnotLike/{name}")
public List<Employee> getNotLike(@PathVariable String name) {
return employeeService.getNotLike(name);
}

2.Model class

public class Employee {


@Id
private int id;
private String name;

20
private String designation;
public Employee(int id, String name, String designation) {
this.id = id;
this.name = name;
this.designation = designation;
}
}

3.Service Class

@Service
public class EmployeeService {
@Autowired
public EmployeeRepo employeeRepo;

public boolean postData(Employee employee) {


try{
employeeRepo.save(employee);
return true;
} catch(Exception e) {
return false;
}
}

public List<Employee> getNotContains( String name) {


return employeeRepo.findAllByNameNotContains(name);
}
public List<Employee> getNotContaining( String name) {
return employeeRepo.findAllByNameNotContaining(name);
}
public List<Employee> getNotLike( String name) {
return employeeRepo.findAllByNameNotLike(name);
}
}

4 .Repository Class

@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
public List<Employee> findAllByNameNotLike(String name);
public List<Employee> findAllByNameNotContains(String name);
public List<Employee> findAllByNameNotContaining(String name);
}

21
Output:

Result:
The program compiled and executed successfully.

22
Ex.no: 7 Employee Payroll Management System with Spring Boot:
Date: NOT LIKE Queries and RESTful API

Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee
data by storing it in a database and providing CRUD operations via RESTful API endpoints.

Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@Autowired
public StudentService studentService;

@PostMapping("/")
public boolean postStudent(@RequestBody Student student){
return studentService.PostData(student);
}
@PutMapping("/put/{id}")
public Student putStudent(@RequestBody Student student,@PathVariable int id){
return studentService.putData(id, student);
}
@GetMapping("/get")
public List<Student> getAll(){
return studentService.getAll();
}
@GetMapping("/get/id/{id}")
public Student getById(@PathVariable int id) {
return studentService.getById(id);
}
@DeleteMapping("/del/{id}")
public void deleteById(@PathVariable int id){
studentService.delData(id);
}
@GetMapping("/get/field/{field}")
public List<Student> getBySort(@PathVariable String field)
{
return studentService.getBySort(field);
}

23
@GetMapping("/get/{min}/{max}")
public List<Student> getByBetween(@PathVariable int min,@PathVariable int max) {
return studentService.getByBetween(min, max);
}

2.Model class

@Data
@Entity
public class Employee {
@Id
private int id;
private String Name;
private int Age;
private String Address;
private String Department;
}
3.Service Class

@Service
public class EmployeeService {

@Autowired
public StudentRepo studentRepo;

public boolean PostData(Student student){


try {
studentRepo.save(student);
return true;
}
catch(Exception e) {
return false;
}
}

public List<Student> getAll(){


return studentRepo.findAll();
}

public Student getById(int id){


return studentRepo.findById(id).orElse(null);
}

public Student putData(int id,Student student){


if (getById(id) != null){
return studentRepo.save(student);
} else{
return null;
}
}
public void delData(int id){
studentRepo.deleteById(id);
}

24
public List<Student> getBySort(String field){
return studentRepo.findAll(Sort.by(Sort.Direction.ASC, field));
}
public List<Student> getByBetween(int minage,int maxage){
return studentRepo.findAllByAgeBetween(minage, maxage);
}
}

4 .Repository Class

@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
@Query("SELECT s FROM Student s WHERE s.Age BETWEEN ?1 AND ?2")
public List<Student> findAllByAgeBetween(int age1,int age2);
}

Output:

25
Result:
The program compiled and executed successfully.

26
Ex.no: 8 Employee Payroll Management System with Spring Boot:
Date: NOT LIKE Queries and RESTful API

Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee
data by storing it in a database and providing CRUD operations via RESTful API endpoints.

Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@Autowired
public DonorService donorService;

@PostMapping("/")
public boolean postStudent(@RequestBody Donor donor) {
return donorService.PostData(donor);
}

@PutMapping("/put/{id}")
public Donor putStudent(@RequestBody Donor donor,@PathVariable int id) {
return donorService.putData(id, donor);
}

@GetMapping("/get")
public List<Donor> getAll() {
return donorService.getAll();
}

@GetMapping("/get/id/{id}")
public Donor getById(@PathVariable int id) {
return donorService.getById(id);
}

@DeleteMapping("/del/{id}")
public void deleteById(@PathVariable int id) {

27
donorService.delData(id);
}

@GetMapping("/get/field/{field}")
public List<Donor> getBySort(@PathVariable String field) {
return donorService.getBySort(field);
}

@GetMapping("/get/{min}/{max}")
public List<Donor> getByBetween(@PathVariable int min,@PathVariable int max) {
return donorService.getByBetween(min, max);
}

2.Model class
@Data
@Entity
public class Employee {
@ Id
private int id;
private String Name;
private int Age;
private String Address;
private String Bloodgroup;
}

3.Service Class
@Autowired
public DonorRepo donorRepo;

public boolean PostData(Donor donor) {


try {
donorRepo.save(donor);
return true;
}
catch(Exception e) {
return false;
}
}

public List<Donor> getAll() {


return donorRepo.findAll();
}

public Donor getById(int id) {


return donorRepo.findById(id).orElse(null);
}

public Donor putData(int id,Donor donor) {

28
if (getById(id) != null) {
return donorRepo.save(donor);
}
return null;
}

public void delData(int id) {


donorRepo.deleteById(id);
}

public List<Donor> getBySort(String field) {


return donorRepo.findAll(Sort.by(Sort.Direction.ASC, field));
}

public List<Donor> getByBetween(int minage,int maxage) {


return donorRepo.findAllByAgeBetween(minage, maxage);
}

4 .Repository Class
@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
@Query("SELECT d FROM Donor d WHERE d.Age BETWEEN ?1 AND ?2")
public List<Donor> findAllByAgeBetween(int age1,int age2);
}

Output:

29
Result:
The program compiled and executed successfully.

30
Ex.no: 9
Date:
Personal Finance Management System

AIM:
To develop a Spring Boot REST API for managing personal finances, allowing users to track their income,
expenses, and budget goals. Implement a one-to-many relationship between users and transactions,
enabling users to view their transaction history and financial summaries.

Algorithm:
1. Define User entity with attributes: id, username, email.
2. Define Transaction entity with attributes: id, type, amount, description.
3. Implement one-to-many mapping between User and Transaction entities.
4. Create UserRepository and TransactionRepository interfaces using Spring Data JPA.
5. Develop FinanceService class to handle business logic.
6. Create FinanceController class to handle API requests.
7. Implement RESTful API endpoints for user and transaction management.

Program:
1. Define User entity:

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String email;

// Getters & Setters


}

2. Define Transaction entity:

@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String type;
private double amount;
private String description;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
3. Create UserRepository and TransactionRepository interfaces:

31
public interface UserRepository extends JpaRepository<User, Integer> {}

public interface TransactionRepository extends JpaRepository<Transaction, Integer>


{
List<Transaction> findByUserId(int userId);
}

4. Implement FinanceService class:

@Service
public class FinanceService {

@Autowired
private UserRepo userRepo;

@Autowired
private TransactionRepo transactionRepo;

public ResponseEntity<User> createUser(User user) {


return new ResponseEntity<>(userRepo.save(user), HttpStatus.CREATED);
}

public ResponseEntity<User> getUserById(int id) {


return ResponseEntity.ok(userRepo.findById(id).orElse(null));
}

public ResponseEntity<Void> deleteUser(int id) {


userRepo.deleteById(id);
return ResponseEntity.noContent().build();
}

public ResponseEntity<User> updateUser(int id, User userDetails) {


Optional<User> existingUser = userRepo.findById(id);

if (existingUser.isEmpty()) {
return ResponseEntity.notFound().build();
}

User user = existingUser.get();


user.setUsername(userDetails.getUsername());
user.setEmail(userDetails.getEmail());

return ResponseEntity.ok(userRepo.save(user));
}

public ResponseEntity<Transaction> createTransaction(Transaction transaction) {


return new ResponseEntity<>(transactionRepo.save(transaction),
HttpStatus.CREATED);

32
}

public ResponseEntity<Transaction> getTransactionById(int id) {


return ResponseEntity.ok(transactionRepo.findById(id).orElse(null));
}

public ResponseEntity<List<Transaction>> getTransactionsByUserId(int userId) {


return ResponseEntity.ok(transactionRepo.findByUserId(userId));
}

public ResponseEntity<Void> deleteTransaction(int id) {


transactionRepo.deleteById(id);
return ResponseEntity.noContent().build();
}

public ResponseEntity<Transaction> updateTransaction(int id, Transaction


transactionDetails) {
Optional<Transaction> existingTransaction = transactionRepo.findById(id);

if (existingTransaction.isEmpty()) {
return ResponseEntity.notFound().build();
}

Transaction transaction = existingTransaction.get();


transaction.setType(transactionDetails.getType());
transaction.setAmount(transactionDetails.getAmount());
transaction.setDescription(transactionDetails.getDescription());
return ResponseEntity.ok(transactionRepo.save(transaction));
}
}

5. Create FinanceController class:

@RestController
@RequestMapping("/api")
public class FinanceController {

@Autowired
private FinanceService financeService;

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
return financeService.createUser(user);
}

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable int id) {

33
return financeService.getUserById(id);
}

@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User
user) {
return financeService.updateUser(id, user);
}

@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable int id) {
return financeService.deleteUser(id);
}

@PostMapping("/transactions")
public ResponseEntity<Transaction> createTransaction(@RequestBody Transaction
transaction) {
return financeService.createTransaction(transaction);
}

@GetMapping("/transactions/{id}")
public ResponseEntity<Transaction> getTransactionById(@PathVariable int id) {
return financeService.getTransactionById(id);
}

@GetMapping("/transactions/user/{userId}")
public ResponseEntity<List<Transaction>> getTransactionsByUserId(@PathVariable int
userId) {
return financeService.getTransactionsByUserId(userId);
}

@PutMapping("/transactions/{id}")
public ResponseEntity<Transaction> updateTransaction(@PathVariable int id,
@RequestBody Transaction transaction) {
return financeService.updateTransaction(id, transaction);
}

@DeleteMapping("/transactions/{id}")
public ResponseEntity<Void> deleteTransaction(@PathVariable int id) {
financeService.deleteTransaction(id);
return ResponseEntity.noContent().build();
}
}

34
Output:

35
Result:
The program compiled and executed successfully.

36
Ex.no: 10
Date:
Smart Home Automation API with Device Control

AIM:
To create a Spring Boot REST API for smart home automation that allows users to control various IoT
devices in their home. Implement a one-to-many relationship between users and devices, enabling users to
manage multiple devices and perform actions such as turning them on/off or adjusting settings remotely.

Algorithm:
1. Create User entity with attributes: id, name, email.
2. Create Device entity with attributes: id, name, type, status, settings.
3. Implement one-to-many mapping between User and Device entities.
4. Create UserRepository and DeviceRepository interfaces using Spring Data JPA.
5. Develop HomeController class to handle API requests.
6. Implement RESTful API endpoints for user and device management.

Program:
1. Define User entity:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String email;

// Getters and setters


}

2. Define Device entity:


@Entity
public class Device {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String type;
private boolean status;
@ElementCollection
private Map<String, String> settings;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

// Getters and setters


}

3. Create UserRepository and DeviceRepository interfaces:


public interface UserRepository extends JpaRepository<User, Integer> {}

37
public interface DeviceRepository extends JpaRepository<Device, Integer> {
List<Device> findByUserId(int userId);
}

4. Develop HomeController class:

package com.practicals.ex_10.controller;

@RestController
@RequestMapping("/api")
public class HomeController {

@Autowired
private UserRepo userRepo;

@Autowired
private DeviceRepo deviceRepo;

// User Endpoints

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
return new ResponseEntity<>(userRepo.save(user), HttpStatus.CREATED);
}

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable int id) {
return ResponseEntity.ok(userRepo.findById(id).orElse(null));
}

@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userRepo.findAll());
}

@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User
user) {
Optional<User> existingUser = userRepo.findById(id);

if (!existingUser.isPresent()) {
return ResponseEntity.notFound().build();
}

User updatedUser = existingUser.get();


updatedUser.setName(user.getName());
updatedUser.setEmail(user.getEmail());

38
userRepo.save(updatedUser);

return ResponseEntity.ok(updatedUser);
}

@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable int id) {
userRepo.deleteById(id);
return ResponseEntity.noContent().build();
}

// Device Endpoints

@PostMapping("/devices")
public ResponseEntity<Device> createDevice(@RequestBody Device device) {
return new ResponseEntity<>(deviceRepo.save(device), HttpStatus.CREATED);
}

@GetMapping("/devices/{id}")
public ResponseEntity<Device> getDeviceById(@PathVariable int id) {
return ResponseEntity.ok(deviceRepo.findById(id).orElse(null));
}

@GetMapping("/devices")
public ResponseEntity<List<Device>> getAllDevices() {
return ResponseEntity.ok(deviceRepo.findAll());
}

@PutMapping("/devices/{id}")
public ResponseEntity<Device> updateDevice(@PathVariable int id, @RequestBody
Device device) {
Optional<Device> existingDevice = deviceRepo.findById(id);

if (!existingDevice.isPresent()) {
return ResponseEntity.notFound().build();
}

Device updatedDevice = existingDevice.get();


updatedDevice.setName(device.getName());
updatedDevice.setStatus(device.isStatus());
updatedDevice.setSettings(device.getSettings());
deviceRepo.save(updatedDevice);

return ResponseEntity.ok(updatedDevice);
}

39
@DeleteMapping("/devices/{id}")
public ResponseEntity<Void> deleteDevice(@PathVariable int id) {
deviceRepo.deleteById(id);
return ResponseEntity.noContent().build();
}

@PutMapping("/devices/{id}/toggle")
public ResponseEntity<Device> toggleDeviceStatus(@PathVariable int id) {
Optional<Device> existingDevice = deviceRepo.findById(id);

if (!existingDevice.isPresent()) {
return ResponseEntity.notFound().build();
}

Device updatedDevice = existingDevice.get();


updatedDevice.setStatus(!updatedDevice.isStatus());
deviceRepo.save(updatedDevice);

return ResponseEntity.ok(updatedDevice);
}

@PutMapping("/devices/{id}/settings")
public ResponseEntity<Device> updateDeviceSettings(@PathVariable int id,
@RequestBody Map<String, String> settings) {
Optional<Device> existingDevice = deviceRepo.findById(id);

if (!existingDevice.isPresent()) {
return ResponseEntity.notFound().build();
}

Device updatedDevice = existingDevice.get();


updatedDevice.setSettings(settings);
deviceRepo.save(updatedDevice);

return ResponseEntity.ok(updatedDevice);
}

@GetMapping("/devices/user/{userId}")
public ResponseEntity<List<Device>> getDevicesByUserId(@PathVariable int userId) {
return ResponseEntity.ok(deviceRepo.findByUserId(userId));
}

40
Output:

41
42
Result:
The program compiled and executed successfully.

43
Ex.no: 11
Date:
Library Membership Management API

AIM:
To develop a Spring Boot REST API for managing library memberships. Each library member is
associated with a unique membership card, and each membership card is linked to only one member.
Users should be able to create, retrieve, update, and delete member and membership card information
through the API.

Algorithm:
1. Create Member entity with attributes: id, name, email.
2. Create MembershipCard entity with attributes: id, cardNumber, expirationDate.
3. Implement one-to-one mapping between Member and MembershipCard entities.
4. Create MemberRepository and MembershipCardRepository interfaces using Spring Data JPA.
5. Develop LibraryMembershipController class to handle API requests.
6. Implement RESTful API endpoints for member and membership card management.

Program:
1. Define Member entity:
@Entity
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String email;

@OneToOne(mappedBy = "member", cascade = CascadeType.ALL)


private MembershipCard membershipCard;

// Getters and setters


}

2. Define MembershipCard entity:


@Entity
public class MembershipCard {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String cardNumber;
private LocalDate expirationDate;

@OneToOne
@JoinColumn(name = "member_id")
private Member member;

// Getters and setters


}

3. Create MemberRepository and MembershipCardRepository interfaces:

44
public interface MemberRepository extends JpaRepository<Member, Integer> {
}

public interface MembershipCardRepository extends JpaRepository<MembershipCard,


Integer> {
}

4. Develop LibraryMembershipController class:

@RestController
@RequestMapping("/api")
public class LibraryMembershipController {

@Autowired
private MemberRepo memberRepo;

@Autowired
private MembershipCardRepo membershipCardRepo;

@PostMapping("/members")
public ResponseEntity<Member> createMember(@RequestBody Member member) {
return new ResponseEntity<>(memberRepo.save(member), HttpStatus.CREATED);
}

@GetMapping("/members/{id}")
public ResponseEntity<Member> getMemberById(@PathVariable int id) {
return ResponseEntity.ok(memberRepo.findById(id).orElse(null));
}

@PutMapping("/members/{id}")
public ResponseEntity<Member> updateMember(@PathVariable int id, @RequestBody
Member member) {
Optional<Member> existingMember = memberRepo.findById(id);

if (!existingMember.isPresent()) {
return ResponseEntity.notFound().build();
}

Member updatedMember = existingMember.get();

updatedMember.setName(member.getName());
updatedMember.setEmail(member.getEmail());
memberRepo.save(updatedMember);

return ResponseEntity.ok(updatedMember);
}

@DeleteMapping("/members/{id}")

45
public ResponseEntity<Void> deleteMember(@PathVariable int id) {
memberRepo.deleteById(id);
return ResponseEntity.noContent().build();
}

@PostMapping("/membership-cards")
public ResponseEntity<MembershipCard> createMembershipCard(@RequestBody
MembershipCard membershipCard) {
MembershipCard createdCard = membershipCardRepo.save(membershipCard);
return new ResponseEntity<>(createdCard, HttpStatus.CREATED);
}

@GetMapping("/membership-cards/{id}")
public ResponseEntity<MembershipCard> getMembershipCardById(@PathVariable int id)
{
MembershipCard card = membershipCardRepo.findById(id).orElse(null);
return ResponseEntity.ok().body(card);
}

@PutMapping("/membership-cards/{id}")
public ResponseEntity<MembershipCard> updateMembershipCard(@PathVariable int id,
@RequestBody MembershipCard membershipCard) {
Optional<MembershipCard> existingCard = membershipCardRepo.findById(id);

if (!existingCard.isPresent()) {
return ResponseEntity.notFound().build();
}

MembershipCard updatedCard = existingCard.get();


updatedCard.setCardNumber(membershipCard.getCardNumber());
updatedCard.setExpirationDate(membershipCard.getExpirationDate());
membershipCardRepo.save(updatedCard);

return ResponseEntity.ok(updatedCard);
}

@DeleteMapping("/membership-cards/{id}")
public ResponseEntity<Void> deleteMembershipCard(@PathVariable int id) {
membershipCardRepo.deleteById(id);
return ResponseEntity.noContent().build();
}

46
Output:

47
Result:
The program compiled and executed successfully.

48
Ex.no: 12
Date:
Asset Tracking System with Ownership Details

AIM:
To develop a Spring Boot REST API for managing assets and tracking their ownership
details. Implement a bidirectional one-to-one relationship between assets and their
respective owners, enabling users to view asset information along with the details of the
owner and vice versa.

Algorithm:
1. 1.Define owner entity with attributes id,name,email,address.
2. 2.Define asset entity with attributes id,name,description,value.
3. 3.Implement one to one relation between owner and asset.
4. 4.create OwnerRepository and AssetRepository interfaces.
5. 5.Develop AssetService for business logics.
6. 6.create AssetController to handle API requests.

Program:
1. Define owner entity:
@Entity
@Setter
@Getter
@NoArgsConstructor
public class Owner {
@Id
private int id;
private String name;
private String email;
private String address;

@JsonBackReference
@OneToOne(mappedBy = "owner",cascade = CascadeType.ALL)
private Asset asset;

2. Define asset entity


@Entity
@Setter
@Getter
@NoArgsConstructor
public class Asset {
@Id
private int id;
private String name;
private String description;
private double value;

49
@JsonManagedReference
@OneToOne(cascade = CascadeType.ALL)
private Owner owner;
}

3. Create OwnerRepository and AssetRepository interfaces:


@Repository
public interface AssetRepository extends JpaRepository<Asset,Integer>{
}

@Repository
public interface OwnerRepository extends JpaRepository<Owner,Integer>{
}

4. Develop AssetService class


@Service
public class AssetService {
@Autowired
private AssetRepository assetRepository;

@Autowired
private OwnerRepository ownerRepository;

public boolean saveAsset(Asset asset) {


try {
assetRepository.save(asset);
} catch(Exception e) {
return false;
}
return true;
}

public boolean updateAsset(int id,Asset asset) {


if(getAssetById(id)==null) {
return false;
}
try {
assetRepository.save(asset);
} catch(Exception e) {
return false;
}
return true;
}
public boolean deleteAsset(int id)
{
if(getAssetById(id)==null) return false;
assetRepository.deleteById(id);
return true;
}

public Asset getAssetById(int id) {


return assetRepository.findById(id).orElse(null);
}

50
public boolean saveOwner(Owner owner) {
try {
ownerRepository.save(owner);
} catch(Exception e) {
return false;
}
return true;
}

public boolean updateOwner(int id,Owner owner) {


if(getOwnerById(id)==null) return false;
try {
ownerRepository.save(owner);
} catch(Exception e) {
return false;
}
return true;
}

public boolean deleteOwner(int id) {


if(getOwnerById(id)==null) return false;
ownerRepository.deleteById(id);
return true;
}

public Owner getOwnerById(int id) {


return ownerRepository.findById(id).orElse(null);
}
}

5.create AssetController class:


@RestController
public class AssetController {
public AssetService assetService;
public AssetController(AssetService assetService) {
this.assetService = assetService;
}

@PostMapping("/assets")
public ResponseEntity<Asset> postMethodName(@RequestBody Asset asset) {
if(assetService.saveAsset(asset)) {
return new ResponseEntity<>(asset,HttpStatus.CREATED);
}
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}

@GetMapping("/assets/{id}")
public ResponseEntity<Asset> getAsset(@PathVariable("id") int id) {
Asset asset = assetService.getAssetById(id);
if(asset==null) {
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(asset,HttpStatus.OK);
}

51
@PutMapping("/assets/{id}")
public ResponseEntity<Asset> putAsset(@PathVariable int id, @RequestBody Asset asset) {
if(assetService.updateAsset(id,asset) == true) {
return new ResponseEntity<>(asset,HttpStatus.OK);
}
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}

@DeleteMapping("/assets/{id}")
public ResponseEntity<Asset> deleteAsset(@PathVariable("id") int id) {
if(assetService.deleteAsset(id)==true) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

@PostMapping("/owners")
public ResponseEntity<Owner> postMethod(@RequestBody Owner owner) {
if(assetService.saveOwner(owner)) {
return new ResponseEntity<>(owner,HttpStatus.CREATED);
}
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}

@GetMapping("/owners/{id}")
public ResponseEntity<Owner> getOwner(@PathVariable("id") int id) {
Owner owner = assetService.getOwnerById(id);
if(owner==null) {
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(owner,HttpStatus.OK);
}

@PutMapping("/owners/{id}")
public ResponseEntity<Owner> putAsset(@PathVariable int id, @RequestBody Owner owner) {
if (assetService.updateOwner(id,owner) == true) {
return new ResponseEntity<>(owner,HttpStatus.OK);
}
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
@DeleteMapping("/owners/{id}")
public ResponseEntity<Asset> deleteOwner(@PathVariable("id") int id) {
if(assetService.deleteOwner(id)==true) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

52
Output:

Result:
The program compiled and executed successfully.

53

You might also like