# java-final-final **Repository Path**: bpyhome/java-final-final ## Basic Information - **Project Name**: java-final-final - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: 2023901701 - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-12-09 - **Last Updated**: 2025-12-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Restaurant Reservation API ๐Ÿฝ๏ธ **Course:** Java Programming (OOP) - Spring Boot **Instructor:** Prof. Baptiste Dupuis **Author:** Ben **Student ID:** 2023901701 **Deadline:** Sunday 7 December 11:42 PM --- ## ๐Ÿ“– Project Description A production-grade RESTful API for managing restaurant reservations built with **Spring Boot 3.4.0** and **Java 21**. This system enables restaurants to manage their tables and track bookings, while allowing customers to browse restaurants, check availability, and make reservations online. ## โœจ Features ### Core Functionality (Required) - **Restaurant Management**: View restaurants and their details with table information - **Customer Management**: Register customers with user authentication and view profiles - **Reservation Management**: Create, view, update, and cancel reservations - **Business Rules Enforcement**: - โœ… No double-booking (same table, overlapping time) - โœ… Capacity validation (guests โ‰ค table capacity) - โœ… Opening hours respected (configurable per restaurant) - โœ… No past reservations - โœ… Proper status transitions (PENDING โ†’ CONFIRMED โ†’ COMPLETED/CANCELLED) ### ๐ŸŒŸ Bonus Features Implemented #### 1. JWT Authentication & Authorization โœ… - User registration and login with secure password hashing - JWT token-based authentication - Protected endpoints (only authenticated users can make reservations) - Role-based access control (ADMIN vs USER) - Security context management for authorization checks #### 2. Unit Tests (JUnit 5 + Mockito) โœ… - Comprehensive service layer tests (12+ test cases) - Mock-based testing with Mockito - Success and error scenarios covered - Business rule validation tests - Security context testing #### 3. Review System โœ… - Customers can leave reviews for restaurants - Rating system (1-5 stars) with comments - Only customers with completed reservations can review - One review per reservation (prevents duplicate reviews) - View reviews by restaurant or customer #### 4. Swagger/OpenAPI Documentation โœ… - Interactive API documentation at `/swagger-ui.html` - Complete endpoint descriptions and schemas - Try-it-out functionality for testing APIs - Auto-generated from code annotations - Professional API documentation for developers ### Technical Features - Clean architecture with Controller โ†’ Service โ†’ Repository layers - DTO pattern (entities never exposed directly) - Custom exception handling with proper HTTP status codes - Bean Validation for input validation - H2 in-memory database with sample data - Centralized validation logic with `ReservationValidator` - Security utilities for authentication checks ## How to Run ### Prerequisites - Java 21 - Maven 3.9+ ### Running the Application ```bash # Navigate to project directory cd reservation-api # Run with Maven wrapper ./mvnw spring-boot:run # Or with Maven mvn spring-boot:run ``` The API will be available at: **http://localhost:8080** ### Accessing H2 Console URL: **http://localhost:8080/h2-console** - JDBC URL: `jdbc:h2:mem:restaurantdb` - Username: `sa` - Password: (leave blank) ### Accessing Swagger UI (API Documentation) URL: **http://localhost:8080/swagger-ui.html** - Interactive API documentation - Try-it-out functionality for all endpoints - Complete request/response schemas - Authentication support for protected endpoints ## ๐Ÿ”Œ API Endpoints ### Authentication | Method | Endpoint | Description | Auth Required | |--------|-------------------|--------------------------|---------------| | POST | `/api/auth/register` | Register new user | No | | POST | `/api/auth/login` | Login and get JWT | No | ### Restaurants | Method | Endpoint | Description | Auth Required | |--------|-------------------------|--------------------------|---------------| | GET | `/api/restaurants` | Get all restaurants | No | | GET | `/api/restaurants/{id}` | Get restaurant by ID | No | | POST | `/api/restaurants` | Create new restaurant | Yes (ADMIN) | ### Customers | Method | Endpoint | Description | Auth Required | |--------|-----------------------|----------------------|---------------| | POST | `/api/customers` | Register new customer| Yes | | GET | `/api/customers/{id}` | Get customer by ID | Yes (Owner/Admin) | ### Reservations | Method | Endpoint | Description | Auth Required | |--------|-------------------------------------|------------------------------|---------------| | POST | `/api/reservations` | Create new reservation | Yes | | GET | `/api/reservations/{id}` | Get reservation by ID | Yes (Owner/Admin) | | PUT | `/api/reservations/{id}` | Update reservation | Yes (Owner/Admin) | | DELETE | `/api/reservations/{id}` | Cancel reservation | Yes (Owner/Admin) | | PUT | `/api/reservations/{id}/complete` | Mark reservation as complete | Yes (Owner/Admin) | | GET | `/api/reservations/customer/{id}` | Get customer's reservations | Yes (Owner/Admin) | ### Reviews | Method | Endpoint | Description | Auth Required | |--------|-----------------------------------|------------------------------|---------------| | POST | `/api/reviews` | Create review for completed reservation | Yes | | GET | `/api/reviews/{id}` | Get review by ID | No | | GET | `/api/reviews/restaurant/{id}` | Get all reviews for restaurant | No | | GET | `/api/reviews/customer/{id}` | Get customer's reviews | Yes (Owner/Admin) | ## Sample Data The application initializes with: - 1 Restaurant: "The Golden Fork" - Address: 123 Main Street, Shanghai - Hours: 11:00 - 22:00 - 5 Tables with varying capacities (2, 4, 6, 8, 8 seats) - 2 Sample Customers: - John Doe (john.doe@example.com) - Jane Smith (jane.smith@example.com) ## Design Decisions ### Entity Relationships - **Restaurant** (1) โ†’ (N) **RestaurantTable**: One restaurant has many tables - **RestaurantTable** (1) โ†’ (N) **Reservation**: One table can have many reservations - **Customer** (1) โ†’ (N) **Reservation**: One customer can have many reservations ### Time Slot Management - Reservations use a 2-hour duration window - Conflict detection checks for overlapping time slots - Only PENDING and CONFIRMED reservations block time slots ### Status Flow ``` PENDING โ†’ CONFIRMED โ†’ COMPLETED โ†“ CANCELLED ``` ### Exception Handling - **404 Not Found**: Resource doesn't exist - **400 Bad Request**: Validation errors, past reservations, capacity exceeded - **409 Conflict**: Double-booking, duplicate email, invalid status transitions - **500 Internal Server Error**: Unexpected errors ## ๐Ÿงช Testing ### Unit Tests (JUnit 5 + Mockito) **You must run the tests in order, or the later tests will fail because they rely on data created by earlier tests.** The project includes comprehensive unit tests for the service layer: **Test Coverage:** - `ReservationServiceTest.java` - 12 test cases covering: - โœ… Successful reservation creation - โœ… Business rule validations (double-booking, capacity, time restrictions) - โœ… Exception handling (ResourceNotFoundException, ValidationException, ConflictException) - โœ… Authorization checks (owner vs admin access) - โœ… Status transition validations - โœ… Edge cases and error scenarios **Running Tests:** ```bash # Run all tests mvn test # Run specific test class mvn test -Dtest=ReservationServiceTest # Run with coverage report mvn clean test jacoco:report ``` **Test Results:** ``` Tests run: 15, Failures: 0, Errors: 0, Skipped: 0 - ReservationApiApplicationTests: 1 test (context loads) - ReservationServiceTest: 12 tests (service layer) - TimeSlotTest: 2 tests (time slot logic) ``` ### API Tests (REST Client) Use the provided test files with REST Client (VS Code extension): **Test Files:** - `api-tests.http` - Main API functionality tests - `rbac-tests.http` - Role-based access control tests **Test Coverage:** - โœ… Happy path scenarios (successful operations) - โœ… Error scenarios (validation failures, business rule violations) - โœ… Edge cases (double-booking, capacity limits, time restrictions) - โœ… Authentication and authorization flows - โœ… RBAC (Role-Based Access Control) scenarios **Test Categories:** 1. **Authentication Tests** - Registration, login, JWT validation 2. **Restaurant Tests** - CRUD operations, data validation 3. **Reservation Tests** - Create, update, cancel, complete 4. **Business Rule Tests** - Double-booking prevention, capacity checks, time validations 5. **Authorization Tests** - Owner access, admin privileges, access denial ## ๐Ÿ“ Project Structure ``` src/main/java/com/restaurant/reservationapi/ โ”œโ”€โ”€ config/ โ”‚ โ”œโ”€โ”€ DataInitializer.java โ”‚ โ”œโ”€โ”€ OpenAPIConfig.java โ”‚ โ””โ”€โ”€ SecurityConfig.java โ”œโ”€โ”€ constants/ โ”‚ โ”œโ”€โ”€ ReservationConstants.java โ”‚ โ””โ”€โ”€ SecurityConstants.java โ”œโ”€โ”€ controller/ โ”‚ โ”œโ”€โ”€ AuthController.java โ”‚ โ”œโ”€โ”€ CustomerController.java โ”‚ โ”œโ”€โ”€ ReservationController.java โ”‚ โ”œโ”€โ”€ RestaurantController.java โ”‚ โ””โ”€โ”€ ReviewController.java โ”œโ”€โ”€ dto/ โ”‚ โ”œโ”€โ”€ request/ โ”‚ โ”‚ โ”œโ”€โ”€ CreateCustomerRequest.java โ”‚ โ”‚ โ”œโ”€โ”€ CreateReservationRequest.java โ”‚ โ”‚ โ”œโ”€โ”€ CreateRestaurantRequest.java โ”‚ โ”‚ โ”œโ”€โ”€ CreateReviewRequest.java โ”‚ โ”‚ โ”œโ”€โ”€ CreateTableRequest.java โ”‚ โ”‚ โ”œโ”€โ”€ LoginRequest.java โ”‚ โ”‚ โ””โ”€โ”€ RegisterRequest.java โ”‚ โ””โ”€โ”€ response/ โ”‚ โ”œโ”€โ”€ AuthResponse.java โ”‚ โ”œโ”€โ”€ AvailabilityResponse.java โ”‚ โ”œโ”€โ”€ CustomerResponse.java โ”‚ โ”œโ”€โ”€ ReservationResponse.java โ”‚ โ”œโ”€โ”€ RestaurantDetailResponse.java โ”‚ โ”œโ”€โ”€ RestaurantResponse.java โ”‚ โ”œโ”€โ”€ ReviewResponse.java โ”‚ โ””โ”€โ”€ TableResponse.java โ”œโ”€โ”€ exception/ โ”‚ โ”œโ”€โ”€ BusinessException.java โ”‚ โ”œโ”€โ”€ ConflictException.java โ”‚ โ”œโ”€โ”€ ErrorResponse.java โ”‚ โ”œโ”€โ”€ GlobalExceptionHandler.java โ”‚ โ”œโ”€โ”€ ResourceNotFoundException.java โ”‚ โ””โ”€โ”€ ValidationException.java โ”œโ”€โ”€ model/ โ”‚ โ”œโ”€โ”€ Customer.java โ”‚ โ”œโ”€โ”€ Reservation.java โ”‚ โ”œโ”€โ”€ ReservationStatus.java โ”‚ โ”œโ”€โ”€ Restaurant.java โ”‚ โ”œโ”€โ”€ RestaurantTable.java โ”‚ โ”œโ”€โ”€ Review.java โ”‚ โ”œโ”€โ”€ Role.java โ”‚ โ””โ”€โ”€ User.java โ”œโ”€โ”€ repository/ โ”‚ โ”œโ”€โ”€ CustomerRepository.java โ”‚ โ”œโ”€โ”€ ReservationRepository.java โ”‚ โ”œโ”€โ”€ RestaurantRepository.java โ”‚ โ”œโ”€โ”€ RestaurantTableRepository.java โ”‚ โ”œโ”€โ”€ ReviewRepository.java โ”‚ โ””โ”€โ”€ UserRepository.java โ”œโ”€โ”€ security/ โ”‚ โ”œโ”€โ”€ JwtAuthenticationFilter.java โ”‚ โ”œโ”€โ”€ JwtTokenProvider.java โ”‚ โ”œโ”€โ”€ SecurityUtils.java โ”‚ โ””โ”€โ”€ UserDetailsServiceImpl.java โ”œโ”€โ”€ service/ โ”‚ โ”œโ”€โ”€ AuthService.java โ”‚ โ”œโ”€โ”€ CustomerService.java โ”‚ โ”œโ”€โ”€ ReservationService.java โ”‚ โ”œโ”€โ”€ RestaurantService.java โ”‚ โ””โ”€โ”€ ReviewService.java โ”œโ”€โ”€ validator/ โ”‚ โ””โ”€โ”€ ReservationValidator.java โ””โ”€โ”€ ReservationApiApplication.java src/test/java/com/restaurant/reservationapi/ โ”œโ”€โ”€ service/ โ”‚ โ”œโ”€โ”€ ReservationServiceTest.java โ”‚ โ””โ”€โ”€ TimeSlotTest.java โ””โ”€โ”€ ReservationApiApplicationTests.java ``` ## ๐ŸŽจ Clean Code Principles Applied ### 1. Naming Conventions โœ… - **Classes**: PascalCase (`ReservationService`, `JwtTokenProvider`) - **Methods/Variables**: camelCase (`findByRestaurantId`, `validateReservationTime`) - **Constants**: UPPER_SNAKE_CASE (`RESERVATION_DURATION_HOURS`, `JWT_EXPIRATION`) - **Packages**: lowercase (`com.restaurant.reservationapi.service`) ### 2. Method Length โœ… - **Most methods**: โ‰ค 20 lines (optimal) - **Complex methods**: โ‰ค 25 lines (acceptable) - **Maximum**: 35 lines (only for justified cases like complex validation) - **Refactoring applied**: Long methods split into smaller, focused helper methods ### 3. Single Responsibility Principle โœ… - Each class has one clear purpose - Controllers: HTTP handling only - Services: Business logic only - Repositories: Data access only - Validators: Validation logic only ### 4. DRY Principle (Don't Repeat Yourself) โœ… - No code duplication - Shared validation logic extracted to `ReservationValidator` - Common security checks in `SecurityUtils` - Reusable constants in `ReservationConstants` ### 5. Proper Encapsulation โœ… - All entity fields are private - DTOs used for API communication (entities never exposed) - Getters/setters only where needed - Immutable DTOs where possible ### 6. Meaningful Names โœ… - Self-documenting code - Examples: - `validateReservationTime()` not `validate()` - `checkForConflicts()` not `check()` - `findConflictingReservations()` not `find()` ### 7. No Magic Numbers โœ… - All constants defined: - `RESERVATION_DURATION_HOURS = 2` - `JWT_EXPIRATION = 86400000` (24 hours) - Opening/closing times stored in database ### 8. Separation of Concerns โœ… - Clear layer boundaries - Business logic isolated from HTTP concerns - Validation logic centralized - Security logic separated ## ๐Ÿ’ก Challenges & Solutions ### Challenge 1: Conflict Detection Algorithm **Problem**: How to prevent double-booking of tables with overlapping time slots? **Solution**: Implemented interval overlap detection using custom JPQL query: - Query checks if new reservation's time range overlaps with existing reservations - Uses `DATEADD` function to calculate reservation end time (start + 2 hours) - Only considers PENDING and CONFIRMED reservations (CANCELLED/COMPLETED don't block) - Formula: `(newStart < existingEnd) AND (newEnd > existingStart)` ### Challenge 2: JWT Authentication Integration **Problem**: How to secure endpoints while maintaining clean architecture? **Solution**: - Created `JwtAuthenticationFilter` to intercept requests and validate tokens - Implemented `SecurityUtils` for centralized authorization checks - Used Spring Security's `SecurityContextHolder` for authentication state - Separated authentication logic from business logic ### Challenge 3: Validation Logic Duplication **Problem**: Reservation validation logic was duplicated between create and update operations. **Solution**: - Extracted validation logic into dedicated `ReservationValidator` component - Created reusable validation methods: `validateNewReservation()` and `validateReservationUpdate()` - Reduced code duplication and improved maintainability - Made validation logic testable in isolation ### Challenge 4: Time Zone and Midnight Crossing **Problem**: Reservations spanning across midnight caused validation issues. **Solution**: - Added explicit midnight crossing check: `if (endTime.isBefore(startTime))` - Enforced business rule: reservations must complete on the same day - Used `LocalTime` for time-of-day comparisons - Clear error messages for users ### Challenge 5: Authorization Granularity **Problem**: Need different access levels (owner vs admin) for reservations. **Solution**: - Implemented `checkOwnershipOrAdmin()` helper method - Admins can access all reservations - Regular users can only access their own reservations - Consistent authorization checks across all operations --- ## ๐Ÿ“Š Project Compliance with Requirements ### Core Requirements (100% Complete) #### โœ… Functional Requirements - โœ… Restaurant Management (view all, view details, check availability) - โœ… Reservation Management (create, view, update, cancel, complete) - โœ… Customer Management (register, view profile) #### โœ… Business Rules Enforcement - โœ… No double-booking (interval overlap detection) - โœ… Capacity check (guests โ‰ค table capacity) - โœ… Opening hours validation (configurable per restaurant) - โœ… No past reservations (time validation) - โœ… Cancellation rules (status-based validation) #### โœ… Technical Requirements - โœ… Spring Boot 3.4.0 with Java 21 - โœ… Spring Data JPA for persistence - โœ… H2 Database (in-memory) - โœ… Spring Validation (Bean Validation) - โœ… Proper exception handling (@RestControllerAdvice) - โœ… Controller โ†’ Service โ†’ Repository layers - โœ… DTO pattern (entities never exposed) - โœ… Custom exceptions for business errors #### โœ… Clean Code Requirements - โœ… Naming conventions (PascalCase, camelCase, UPPER_SNAKE_CASE) - โœ… Methods under 25 lines (most under 20) - โœ… No magic numbers (constants used) - โœ… No code duplication (DRY principle) - โœ… Meaningful names (self-documenting) - โœ… Single Responsibility Principle - โœ… Proper encapsulation #### โœ… API Design - โœ… RESTful conventions - โœ… Proper HTTP methods and status codes - โœ… JSON request/response format - โœ… Meaningful error messages - โœ… Proper validation feedback ### Bonus Features (Implemented) #### โœ… Unit Tests (JUnit 5) - โœ… Service layer tests (12+ test cases) - โœ… Mockito for mocking repositories - โœ… Success and error cases covered - โœ… Business rule validation tests #### โœ… JWT Authentication - โœ… User registration and login - โœ… Protected endpoints - โœ… Role-based access (ADMIN vs USER) - โœ… Token-based authentication #### โœ… Review System - โœ… Reviews can be created for completed reservations - โœ… Only completed reservations can be reviewed - โœ… Rating system (1-5 stars) with comments - โœ… One review per reservation validation - โœ… View reviews by restaurant or customer #### โœ… Swagger/OpenAPI Documentation - โœ… Interactive API documentation - โœ… Complete endpoint descriptions - โœ… Interactive API documentation - โœ… Complete endpoint descriptions - โœ… Request/response schemas - โœ… Try-it-out functionality ### Testing Coverage #### โœ… API Tests (rbac-tests.http) - โœ… Happy path scenarios - โœ… Error scenarios - โœ… Business rule violations - โœ… Validation errors - โœ… 48+ comprehensive test cases --- ## ๐Ÿ“ Development Process ### Git Workflow - **Branch**: `2023901701` (student ID) - **Commits**: 10+ meaningful commits with descriptive messages - **Commit Language**: All in English - **Development**: Incremental progress visible through commits ### Documentation - โœ… Comprehensive README.md - โœ… API endpoints documented - โœ… Design decisions explained - โœ… Challenges and solutions documented - โœ… Clean code principles applied --- ## ๐ŸŽ“ Learning Outcomes This project demonstrates proficiency in: 1. **Spring Boot Framework**: Configuration, dependency injection, auto-configuration 2. **Spring Data JPA**: Entity relationships, custom queries, repository pattern 3. **RESTful API Design**: HTTP methods, status codes, resource naming 4. **Security**: JWT authentication, authorization, password hashing 5. **Testing**: Unit testing, mocking, test-driven development 6. **Clean Code**: SOLID principles, naming conventions, code organization 7. **Problem Solving**: Complex business logic, validation, conflict detection 8. **Git**: Version control, branching, commit best practices --- **Project Status**: โœ… Complete and ready for evaluation