Cab Booking
Cab Booking
-------------------
com.cabbooking
├── CabBookingApplication.java
├── config
│ ├── JwtAuthenticationFilter.java
│ ├── SecurityConfig.java
├── controller
│ ├── UserController.java
│ ├── DriverController.java
│ ├── BookingController.java
│ ├── PaymentController.java
├── dto
│ ├── UserDTO.java
│ ├── BookingDTO.java
├── entity
│ ├── User.java
│ ├── Driver.java
│ ├── Booking.java
│ ├── Payment.java
├── exception
│ ├── CustomException.java
│ ├── GlobalExceptionHandler.java
├── repository
│ ├── UserRepository.java
│ ├── DriverRepository.java
│ ├── BookingRepository.java
│ ├── PaymentRepository.java
├── service
│ ├── UserService.java
│ ├── BookingService.java
│ ├── PaymentService.java
│ ├── impl
│ ├── UserServiceImpl.java
│ ├── BookingServiceImpl.java
│ ├── PaymentServiceImpl.java
└── util
├── JwtUtil.java
CabBookingApplication.java
===========================
@SpringBootApplication
public class CabBookingApplication {
public static void main(String[] args) {
SpringApplication.run(CabBookingApplication.class, args);
}
}
JwtAuthenticationFilter.java
=============================
package com.cabbooking.config;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain chain)
throws ServletException, IOException {
String token = jwtUtil.extractToken(request);
if (token != null && jwtUtil.validateToken(token)) {
SecurityContextHolder.getContext().setAuthentication(jwtUtil.getAuthentication(toke
n));
}
chain.doFilter(request, response);
}
}
SecurityConfig.java
====================
package com.cabbooking.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import
org.springframework.security.config.annotation.authentication.builders.Authenticati
onManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilte
r;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http,
JwtAuthenticationFilter jwtFilter) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtFilter,
UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
UserController.java
===================
package com.cabbooking.controller;
import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public ResponseEntity<User> registerUser(@RequestBody UserDTO userDTO) {
return ResponseEntity.ok(userService.registerUser(userDTO));
}
@GetMapping("/profile")
public ResponseEntity<User> getUserProfile(@RequestParam String email) {
return ResponseEntity.ok(userService.getUserProfile(email));
}
}
DriverController.java
======================
package com.cabbooking.controller;
import com.cabbooking.entity.Driver;
import com.cabbooking.repository.DriverRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/driver")
public class DriverController {
@Autowired
private DriverRepository driverRepository;
@PostMapping("/register")
public ResponseEntity<Driver> registerDriver(@RequestBody Driver driver) {
return ResponseEntity.ok(driverRepository.save(driver));
}
@GetMapping("/{id}")
public ResponseEntity<Driver> getDriver(@PathVariable Long id) {
return ResponseEntity.ok(driverRepository.findById(id).orElseThrow(() ->
new RuntimeException("Driver not found")));
}
}
BookingController.java
======================
package com.cabbooking.controller;
import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/booking")
public class BookingController {
@Autowired
private BookingService bookingService;
@PostMapping("/create")
public ResponseEntity<Booking> createBooking(@RequestBody BookingDTO
bookingDTO) {
return ResponseEntity.ok(bookingService.createBooking(bookingDTO));
}
}
PaymentController.java
=======================
package com.cabbooking.controller;
import com.cabbooking.entity.Payment;
import com.cabbooking.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/payment")
public class PaymentController {
@Autowired
private PaymentService paymentService;
@PostMapping("/process")
public ResponseEntity<Payment> processPayment(@RequestParam Long bookingId,
@RequestParam double amount) {
return ResponseEntity.ok(paymentService.processPayment(bookingId, amount));
}
}
UserDTO.java
=============
package com.cabbooking.dto;
// Default Constructor
public UserDTO() {
}
// Parameterized Constructor
public UserDTO(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
@Override
public String toString() {
return "UserDTO{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
BookingDTO.java
================
package com.gmail.dto;
// Default Constructor
public BookingDTO() {
}
// Parameterized Constructor
public BookingDTO(Long id, String user, String date, String time) {
this.id = id;
this.user = user;
this.date = date;
this.time = time;
}
@Override
public String toString() {
return "BookingDTO{" +
"id=" + id +
", user='" + user + '\'' +
", date='" + date + '\'' +
", time='" + time + '\'' +
'}';
}
}
User.java
============
package com.cabbooking.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public User() {}
@Override
public String toString() {
return "User{id=" + id + ", username='" + username + "', email='" + email +
"', role='" + role + "'}";
}
}
Driver.java
=============
package com.cabbooking.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class Driver {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String contactNumber;
private String vehicleDetails;
public Driver() {}
@Override
public String toString() {
return "Driver{id=" + id + ", name='" + name + "', contactNumber='" +
contactNumber + "', vehicleDetails='" + vehicleDetails + "'}";
}
}
Booking.java
============
package com.cabbooking.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
@Entity
public class Booking {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Driver driver;
@OneToOne
private Payment payment;
public Booking() {}
@Override
public String toString() {
return "Booking{id=" + id + ", driver=" + driver + ", payment=" + payment +
", customerName='" + customerName + "', pickupLocation='" + pickupLocation + "',
dropLocation='" + dropLocation + "', status='" + status + "'}";
}
}
Payment.java
=============
package com.cabbooking.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class Payment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double amount;
private String paymentMethod;
private String paymentStatus;
public Payment() {}
@Override
public String toString() {
return "Payment{id=" + id + ", amount=" + amount + ", paymentMethod='" +
paymentMethod + "', paymentStatus='" + paymentStatus + "'}";
}
}
CustomException.java
======================
package com.cabbooking.exception;
public CustomException() {
super();
}
@Override
public String toString() {
return "CustomException{message='" + message + "', errorCode=" + errorCode
+ "}";
}
}
GlobalExceptionHandler.Java
============================
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("Internal server error: " + ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
UserRepository.java
====================
package com.cabbooking.repository;
import com.cabbooking.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
DriverRepository.java
======================
package com.cabbooking.repository;
import com.cabbooking.entity.Driver;
import org.springframework.data.jpa.repository.JpaRepository;
BookingRepository.java
=======================
package com.cabbooking.repository;
import com.cabbooking.entity.Booking;
import org.springframework.data.jpa.repository.JpaRepository;
PaymentRepository.java
=====================
package com.cabbooking.repository;
import com.cabbooking.entity.Payment;
import org.springframework.data.jpa.repository.JpaRepository;
UserService.java
================
package com.cabbooking.service;
import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
BookingService.java
===================
package com.cabbooking.service;
import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
PaymentService.java
===================
package com.cabbooking.service;
import com.cabbooking.entity.Payment;
UserServiceImpl.java
=====================
package com.cabbooking.service.impl;
import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.UserRepository;
import com.cabbooking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public User registerUser(UserDTO userDTO) {
if (userRepository.findByEmail(userDTO.getEmail()).isPresent()) {
throw new CustomException("Email already exists");
}
User user = new User(userDTO.getName(), userDTO.getEmail(),
passwordEncoder.encode(userDTO.getPassword()), "USER");
return userRepository.save(user);
}
@Override
public User getUserProfile(String email) {
return userRepository.findByEmail(email).orElseThrow(() -> new
CustomException("User not found"));
}
}
BookingServiceImpl.java
=======================
package com.cabbooking.service.impl;
import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.repository.BookingRepository;
import com.cabbooking.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookingServiceImpl implements BookingService {
@Autowired
private BookingRepository bookingRepository;
@Override
public Booking createBooking(BookingDTO bookingDTO) {
Booking booking = new Booking();
booking.setUserId(bookingDTO.getUserId());
booking.setDriverId(bookingDTO.getDriverId());
booking.setPickupLocation(bookingDTO.getPickupLocation());
booking.setDropLocation(bookingDTO.getDropLocation());
booking.setBookingTime(bookingDTO.getBookingTime());
booking.setStatus("Pending");
return bookingRepository.save(booking);
}
}
PaymentService.java
====================
package com.cabbooking.service.impl;
import com.cabbooking.entity.Payment;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.BookingRepository;
import com.cabbooking.repository.PaymentRepository;
import com.cabbooking.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PaymentServiceImpl implements PaymentService {
@Autowired
private PaymentRepository paymentRepository;
@Autowired
private BookingRepository bookingRepository;
@Override
public Payment processPayment(Long bookingId, double amount) {
if (!bookingRepository.existsById(bookingId)) {
throw new CustomException("Booking not found");
}
JwtUtil.java
==============
package com.cabbooking.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
public class JwtUtil {
application.properties
=======================
# Application Configurations
spring.application.name=cab-booking-app
# Server Configuration
server.port=8080
# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/cab_booking_db
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# JPA Properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# JWT Configuration
jwt.secret=your_jwt_secret_key
jwt.expiration=3600000 # in milliseconds (1 hour)
# Logging Configuration
logging.level.org.springframework=INFO
logging.level.com.cabbooking=DEBUG
logging.file.name=logs/cab-booking-app.log
UserControllerTest.java
========================
package com.cabbooking.controller;
import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ExtendWith(MockitoExtension.class)
public class UserControllerTest {
@Mock
private UserService userService;
@InjectMocks
private UserController userController;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
public void testRegisterUser() throws Exception {
UserDTO userDTO = new UserDTO("John", "[email protected]", "password123");
User user = new User(1L, "John", "[email protected]", "password123");
when(userService.registerUser(any(UserDTO.class))).thenReturn(user);
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"John\", \"email\":\"[email protected]\",
\"password\":\"password123\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
@Test
public void testGetUserProfile() throws Exception {
User user = new User(1L, "John", "[email protected]", "password123");
when(userService.getUserProfile("[email protected]")).thenReturn(user);
mockMvc.perform(get("/user/profile").param("email", "[email protected]"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
}
DriverControllerTest.java
=========================
package com.cabbooking.controller;
import com.cabbooking.entity.Driver;
import com.cabbooking.repository.DriverRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ExtendWith(MockitoExtension.class)
public class DriverControllerTest {
@Mock
private DriverRepository driverRepository;
@InjectMocks
private DriverController driverController;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(driverController).build();
}
@Test
public void testRegisterDriver() throws Exception {
Driver driver = new Driver(1L, "Jane", "[email protected]", "car123");
when(driverRepository.save(any(Driver.class))).thenReturn(driver);
mockMvc.perform(post("/driver/register")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Jane\", \"email\":\"[email protected]\",
\"vehicle\":\"car123\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Jane"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
@Test
public void testGetDriver() throws Exception {
Driver driver = new Driver(1L, "Jane", "[email protected]", "car123");
when(driverRepository.findById(1L)).thenReturn(java.util.Optional.of(driver));
mockMvc.perform(get("/driver/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Jane"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
}
BookingControllerTest.java
===========================
package com.cabbooking.controller;
import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.service.BookingService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ExtendWith(MockitoExtension.class)
public class BookingControllerTest {
@Mock
private BookingService bookingService;
@InjectMocks
private BookingController bookingController;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(bookingController).build();
}
@Test
public void testCreateBooking() throws Exception {
BookingDTO bookingDTO = new BookingDTO("John", "Jane", "car123",
"destination1");
Booking booking = new Booking(1L, "John", "Jane", "car123",
"destination1");
when(bookingService.createBooking(any(BookingDTO.class))).thenReturn(booking);
mockMvc.perform(post("/booking/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"user\":\"John\", \"driver\":\"Jane\", \"vehicl
e\":\"car123\", \"destination\":\"destination1\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user").value("John"))
.andExpect(jsonPath("$.driver").value("Jane"))
.andExpect(jsonPath("$.destination").value("destination1"));
}
}
PaymentControllerTest.java
===========================
package com.cabbooking.controller;
import com.cabbooking.entity.Payment;
import com.cabbooking.service.PaymentService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ExtendWith(MockitoExtension.class)
public class PaymentControllerTest {
@Mock
private PaymentService paymentService;
@InjectMocks
private PaymentController paymentController;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(paymentController).build();
}
@Test
public void testProcessPayment() throws Exception {
Payment payment = new Payment(1L, 100.0, "Paid");
when(paymentService.processPayment(1L, 100.0)).thenReturn(payment);
mockMvc.perform(post("/payment/process")
.param("bookingId", "1")
.param("amount", "100.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("Paid"))
.andExpect(jsonPath("$.amount").value(100.0));
}
}
UserServiceImplTest.java
=========================
package com.cabbooking.service.impl;
import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Optional;
@Mock
private UserRepository userRepository;
@Mock
private PasswordEncoder passwordEncoder;
@InjectMocks
private UserServiceImpl userService;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
userDTO = new UserDTO("John Doe", "[email protected]", "password123");
}
@Test
public void testRegisterUser_ShouldReturnSavedUser() {
when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.empty());
when(passwordEncoder.encode(userDTO.getPassword())).thenReturn("encodedPassword");
when(userRepository.save(any(User.class))).thenReturn(new User("John Doe",
"[email protected]", "encodedPassword", "USER"));
assertNotNull(result);
assertEquals("[email protected]", result.getEmail());
verify(userRepository, times(1)).save(any(User.class));
}
@Test
public void testRegisterUser_EmailAlreadyExists_ShouldThrowCustomException() {
when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.of(new
User()));
assertThrows(CustomException.class, () ->
userService.registerUser(userDTO));
}
@Test
public void testGetUserProfile_ShouldReturnUser() {
when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.of(new
User("John Doe", "[email protected]", "encodedPassword", "USER")));
assertNotNull(result);
assertEquals("[email protected]", result.getEmail());
}
@Test
public void testGetUserProfile_UserNotFound_ShouldThrowCustomException() {
when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.empty());
assertThrows(CustomException.class, () ->
userService.getUserProfile(userDTO.getEmail()));
}
}
BookingServiceImplTest.java
============================
package com.cabbooking.service.impl;
import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.repository.BookingRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@Mock
private BookingRepository bookingRepository;
@InjectMocks
private BookingServiceImpl bookingService;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
bookingDTO = new BookingDTO(1L, 2L, "Location A", "Location B", "2024-12-11
10:00:00");
}
@Test
public void testCreateBooking_ShouldReturnSavedBooking() {
when(bookingRepository.save(any(Booking.class))).thenReturn(booking);
assertNotNull(result);
assertEquals("Location A", result.getPickupLocation());
assertEquals("Pending", result.getStatus());
verify(bookingRepository, times(1)).save(any(Booking.class));
}
}
PaymentServiceImplTest.java
============================
package com.cabbooking.service.impl;
import com.cabbooking.entity.Payment;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.BookingRepository;
import com.cabbooking.repository.PaymentRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@Mock
private PaymentRepository paymentRepository;
@Mock
private BookingRepository bookingRepository;
@InjectMocks
private PaymentServiceImpl paymentService;
private Long bookingId;
private double amount;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
bookingId = 1L;
amount = 100.0;
}
@Test
public void testProcessPayment_ShouldReturnProcessedPayment() {
when(bookingRepository.existsById(bookingId)).thenReturn(true);
Payment payment = new Payment();
payment.setBookingId(bookingId);
payment.setAmount(amount);
payment.setStatus("Completed");
when(paymentRepository.save(any(Payment.class))).thenReturn(payment);
assertNotNull(result);
assertEquals("Completed", result.getStatus());
verify(paymentRepository, times(1)).save(any(Payment.class));
}
@Test
public void testProcessPayment_BookingNotFound_ShouldThrowCustomException() {
when(bookingRepository.existsById(bookingId)).thenReturn(false);
assertThrows(CustomException.class, () ->
paymentService.processPayment(bookingId, amount));
}
}
src
├── app
│ ├── auth
│ │ ├── login
│ │ │ ├── login.component.html
│ │ │ ├── login.component.ts
│ │ ├── register
│ │ ├── register.component.html
│ │ ├── register.component.ts
│ ├── user
│ │ ├── booking
│ │ │ ├── booking.component.html
│ │ │ ├── booking.component.ts
│ │ ├── profile
│ │ ├── profile.component.html
│ │ ├── profile.component.ts
│ ├── driver
│ │ ├── manage
│ │ ├── manage.component.html
│ │ ├── manage.component.ts
│ ├── admin
│ │ ├── dashboard
│ │ ├── dashboard.component.html
│ │ ├── dashboard.component.ts
│ ├── services
│ │ ├── auth.service.ts
│ │ ├── booking.service.ts
│ │ ├── user.service.ts
│ │ ├── driver.service.ts
│ ├── app-routing.module.ts
│ ├── app.module.ts
│ ├── app.component.html
│ ├── app.component.ts
app.component.html
==================
<div class="app-container">
<router-outlet></router-outlet>
</div>
app.module.ts
==============
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent,
BookingComponent,
ProfileComponent,
ManageComponent,
DashboardComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
=====================
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Auth Module
============
auth.service.ts
================
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'https://localhost:8080/auth';
getCurrentUser(): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/currentUser`);
}
logout(): Observable<any> {
return this.http.post<any>(`${this.apiUrl}/logout`, {});
}
}
login.component.ts
==================
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
username: string = '';
password: string = '';
onLogin() {
this.authService.login(this.username, this.password).subscribe(
(response) => {
console.log('Login successful');
this.router.navigate(['/home']);
},
(error) => {
console.error('Login failed', error);
}
);
}
}
login.component.html
====================
<div class="login-form">
<h2>Login</h2>
<form (ngSubmit)="onLogin()">
<div>
<label for="username">Username</label>
<input type="text" id="username" [(ngModel)]="username" name="username"
required />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" [(ngModel)]="password" name="password"
required />
</div>
<button type="submit" [disabled]="!username || !password">Login</button>
</form>
</div>
register.component.ts
=====================
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent {
username: string = '';
password: string = '';
email: string = '';
onRegister() {
const user = { username: this.username, password: this.password, email:
this.email };
this.authService.register(user).subscribe(
(response) => {
console.log('Registration successful');
this.router.navigate(['/login']);
},
(error) => {
console.error('Registration failed', error);
}
);
}
}
register.component.html
========================
<div class="register-form">
<h2>Register</h2>
<form (ngSubmit)="onRegister()">
<div>
<label for="username">Username</label>
<input type="text" id="username" [(ngModel)]="username" name="username"
required />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" [(ngModel)]="password" name="password"
required />
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" [(ngModel)]="email" name="email" required />
</div>
<button type="submit" [disabled]="!username || !password ||
!email">Register</button>
</form>
</div>
User Module
===========
booking.component.html
=======================
<div class="booking-form">
<h2>Booking</h2>
<form (ngSubmit)="onBook()">
<div>
<label for="pickup">Pickup Location</label>
<input type="text" id="pickup" [(ngModel)]="pickupLocation"
name="pickupLocation" required />
</div>
<div>
<label for="destination">Destination</label>
<input type="text" id="destination" [(ngModel)]="destination"
name="destination" required />
</div>
<button type="submit" [disabled]="!pickupLocation ||
!destination">Book</button>
</form>
</div>
booking.component.ts
=====================
@Component({
selector: 'app-booking',
templateUrl: './booking.component.html',
styleUrls: ['./booking.component.css']
})
export class BookingComponent {
pickupLocation: string = '';
destination: string = '';
onBook() {
const bookingDetails = { pickupLocation: this.pickupLocation, destination:
this.destination };
this.bookingService.createBooking(bookingDetails).subscribe(
(response) => {
console.log('Booking successful');
this.router.navigate(['/profile']);
},
(error) => {
console.error('Booking failed', error);
}
);
}
}
profile.component.html
======================
<div class="profile-details">
<h2>Your Profile</h2>
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
userDetails: any = {};
ngOnInit() {
this.fetchUserProfile();
}
fetchUserProfile() {
this.userService.getUserProfile().subscribe(
(data) => {
this.userDetails = data;
console.log('User Profile:', data);
},
(error) => {
console.error('Error fetching profile', error);
}
);
}
}
profile.component.css
=====================
.profile-details {
padding: 20px;
max-width: 800px;
margin: auto;
}
.user-profile, .booking-history {
margin-bottom: 20px;
}
h3 {
color: #333;
font-size: 1.2em;
}
table {
width: 100%;
border-collapse: collapse;
}
table th {
background-color: #f4f4f4;
}
p {
font-size: 1em;
}
user.service.ts
==================
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'https://localhost:8080/user';
manage.component.html
=====================
<div class="manage-driver">
<h2>Manage Driver</h2>
<form (ngSubmit)="onManageDriver()">
<div>
<label for="driverId">Driver ID</label>
<input type="text" id="driverId" [(ngModel)]="driverId" name="driverId"
required />
</div>
<div>
<label for="status">Driver Status</label>
<select id="status" [(ngModel)]="status" name="status">
<option value="available">Available</option>
<option value="unavailable">Unavailable</option>
</select>
</div>
<button type="submit">Manage Driver</button>
</form>
</div>
manage.component.ts
===================
@Component({
selector: 'app-manage',
templateUrl: './manage.component.html',
styleUrls: ['./manage.component.css']
})
export class ManageComponent {
driverId: string = '';
status: string = 'available';
onManageDriver() {
const driverDetails = { driverId: this.driverId, status: this.status };
this.driverService.manageDriver(driverDetails).subscribe(
(response) => {
console.log('Driver status updated');
},
(error) => {
console.error('Error updating driver status', error);
}
);
}
}
dashboard.component.html
=========================
<div class="dashboard-container">
<h2>Admin Dashboard</h2>
<div class="statistics">
<div class="stat-card">
<h3>Total Bookings</h3>
<p>{{ totalBookings }}</p>
</div>
<div class="stat-card">
<h3>Active Users</h3>
<p>{{ activeUsers }}</p>
</div>
<div class="stat-card">
<h3>Total Drivers</h3>
<p>{{ totalDrivers }}</p>
</div>
</div>
<div class="recent-bookings">
<h3>Recent Bookings</h3>
<table *ngIf="recentBookings?.length > 0">
<thead>
<tr>
<th>Booking ID</th>
<th>Pickup Location</th>
<th>Destination</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let booking of recentBookings">
<td>{{ booking.bookingId }}</td>
<td>{{ booking.pickupLocation }}</td>
<td>{{ booking.destination }}</td>
<td>{{ booking.status }}</td>
</tr>
</tbody>
</table>
<p *ngIf="recentBookings?.length === 0">No recent bookings available.</p>
</div>
</div>
dashboard.component.ts
=======================
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
totalBookings: number = 0;
activeUsers: number = 0;
totalDrivers: number = 0;
recentBookings: any[] = [];
ngOnInit() {
this.loadDashboardData();
}
loadDashboardData() {
this.adminService.getDashboardData().subscribe(
(data) => {
this.totalBookings = data.totalBookings;
this.activeUsers = data.activeUsers;
this.totalDrivers = data.totalDrivers;
this.recentBookings = data.recentBookings;
},
(error) => {
console.error('Error loading dashboard data', error);
}
);
}
}
dashboard.component.css
=======================
.dashboard-container {
padding: 20px;
max-width: 900px;
margin: auto;
}
h2 {
color: #333;
text-align: center;
}
.statistics {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
.stat-card {
background-color: #f4f4f4;
padding: 15px;
border-radius: 8px;
text-align: center;
width: 30%;
}
.stat-card h3 {
margin-bottom: 10px;
}
.recent-bookings table {
width: 100%;
border-collapse: collapse;
}
.recent-bookings th {
background-color: #f4f4f4;
}
admin.service.ts
=================
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AdminService {
private apiUrl = 'https://localhost:8080/admin';
getDashboardData(): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/dashboard`);
}
}
booking.service.ts
===================
@Injectable({
providedIn: 'root'
})
export class BookingService {
private apiUrl = 'https://localhost:8080/booking';
getAllBookings(): Observable<any[]> {
return this.http.get<any[]>(`${this.apiUrl}/all`);
}
driver.service.ts
==================
getAllDrivers(): Observable<any[]> {
return this.http.get<any[]>(`${this.apiUrl}/all`);
}
app.component.ts
=================
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Cab Booking System';
}