@NotNull
@Future(message = "Estimated leaving time must be in the future")
@Column(name = "estimated_leaving_time", nullable = false)
private LocalDateTime estimatedLeavingTime;
// Static factory method for creation
public static Availability create(UUID leavingUserId, Location location, LocalDateTime estimatedLeavingTime) {
AvailabilityId availabilityId = AvailabilityId.generate();
return new Availability(availabilityId, leavingUserId, location, estimatedLeavingTime);
}
// Business methods
public ReservationRequest createReservationRequest(UUID arrivingUserId, String message) {
// Check if there's already a pending request from this user
boolean hasExistingRequest = reservationRequests.stream()
.anyMatch(request -> request.getArrivingUserId().equals(arrivingUserId)
&& request.getStatus() == RequestStatus.PENDING);
assertStateFalse(hasExistingRequest, "You already have a pending reservation request for this availability.");
// Create a new reservation request
ReservationRequest request = ReservationRequest.create(
arrivingUserId,
this.leavingUserId,
message,
this
);
// Add the request to the collection
this.reservationRequests.add(request);
// Update status if necessary
this.requestReservation(arrivingUserId);
this.publish(new ReservationRequestCreatedEvent(
this.availabilityId.getValue(),
request.getRequestId(),
arrivingUserId,
message
));
return request;
}
public void respondToReservationRequest(UUID requestId, UUID leavingUserId, boolean accepted) {
assertArgumentTrue(this.leavingUserId.equals(leavingUserId),
"You do not have permission to respond to this request");
public void requestReservation(UUID arrivingUserId) {
assertArgumentTrue(this.status.equals(AvailabilityStatus.AVAILABLE),
"Spot is not available for reservation");
assertArgumentNotNull(arrivingUserId, "Arriving user ID cannot be null");
this.setStatus(AvailabilityStatus.REQUEST_PENDING);
}
/**
Reserves this availability for a given arriving user.
@param arrivingUserId the ID of the arriving user
@throws IllegalArgumentException if the spot is not available or the arrivingUserId is null
*/
public void reserve(UUID arrivingUserId) {
this.assertArgumentTrue(this.getStatus().equals(AvailabilityStatus.AVAILABLE),
"Only available spots can be reserved");
this.assertArgumentNotNull(arrivingUserId, "ArrivingUserId cannot be null");
this.setReservedByUserId(arrivingUserId);
this.setStatus(AvailabilityStatus.RESERVED);
}
Makes the availability available again after a reservation request is rejected.
This method ensures that the availability's status is updated appropriately
and any business rules are enforced.
*/
public void makeAvailableAfterRejection() {
assertStateTrue(this.status == AvailabilityStatus.REQUEST_PENDING,
"Availability status must be REQUEST_PENDING to make it available again.");
this.setStatus(AvailabilityStatus.AVAILABLE);
this.setReservedByUserId(null);
}
/**
Confirms that the spot has been taken by the arriving user.
@param arrivingUserId the ID of the arriving user
@throws IllegalArgumentException if the spot is not reserved or reserved by another user
*/
public void confirmTaken(UUID arrivingUserId) {
this.assertArgumentTrue(this.getStatus().equals(AvailabilityStatus.RESERVED),
"Only reserved spots can be confirmed as taken");
this.assertArgumentTrue(this.getReservedByUserId().equals(arrivingUserId),
"This spot is not reserved by the provided user");
this.setStatus(AvailabilityStatus.TAKEN);
It checks for the necessary permissions and updates the status accordingly.
@param userId the ID of the user attempting to cancel
@throws IllegalStateException if the user does not have permission or the availability is already canceled
*/
public void cancel(UUID userId) {
boolean hasPermission = this.leavingUserId.equals(userId);
assertStateTrue(hasPermission, "You do not have permission to cancel this availability");
assertStateFalse(this.status == AvailabilityStatus.CANCELED, "Availability is already canceled");
this.setStatus(AvailabilityStatus.CANCELED);
// Cancel all pending reservation requests
for (ReservationRequest request : reservationRequests) {
if (request.getStatus() == RequestStatus.PENDING) {
request.cancel();
}
}
this.publish(new AvailabilityCanceledEvent(
this.availabilityId.getValue(),
userId
));
}
// Getters and Setters with validation where applicable
/**
Returns the unique identifier of this {@code Availability}.
@return the {@code AvailabilityId}
*/
public AvailabilityId getAvailabilityId() {
return availabilityId;
}
Returns the estimated time when the user will leave the spot.
@return the estimated leaving time
*/
public LocalDateTime getEstimatedLeavingTime() {
return estimatedLeavingTime;
}
private void setEstimatedLeavingTime(LocalDateTime estimatedLeavingTime) {
this.assertArgumentNotNull(estimatedLeavingTime, "Estimated leaving time cannot be null");
this.assertArgumentTrue(estimatedLeavingTime.isAfter(LocalDateTime.now()),
"Estimated leaving time must be in the future");
this.estimatedLeavingTime = estimatedLeavingTime;
}
public List getReservationRequests() {
return Collections.unmodifiableList(reservationRequests);
}
/**
Returns the current status of this availability.
@return the {@code AvailabilityStatus}
*/
public AvailabilityStatus getStatus() {
return status;
}
// equals and hashCode based on 'availabilityId'
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Availability that = (Availability) o;
return availabilityId.equals(that.availabilityId);
}
@Override
public int hashCode() {
return availabilityId.hashCode();
}
Constructs a new {@code Location} with the specified latitude and longitude.
@param latitude the latitude coordinate, must be between -90 and 90 degrees
@param longitude the longitude coordinate, must be between -180 and 180 degrees
@throws IllegalArgumentException if the latitude or longitude are out of valid ranges
*/
public Location(double latitude, double longitude) {
// Validate latitude range
this.assertArgumentRange(latitude, -90.0, 90.0,
"Latitude must be between -90 and 90 degrees");
// Validate longitude range
this.assertArgumentRange(longitude, -180.0, 180.0,
"Longitude must be between -180 and 180 degrees");
Returns the latitude coordinate of this {@code Location}.
@return the latitude value
*/
public double getLatitude() {
return latitude;
}
/**
Returns the longitude coordinate of this {@code Location}.
@return the longitude value
*/
public double getLongitude() {
return longitude;
}
/**
Determines whether this location is equal to another object.
@param o the reference object with which to compare
@return {@code true} if this location is the same as the argument; {@code false} otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
The {@code ReservationRequest} class represents a reservation request in the parking exchange system.
It models the interaction between an arriving user who wants to reserve a parking spot and a leaving user
who is offering the spot. The class includes details such as the users involved, the status of the request,
timestamps of when the request was made and responded to, any messages included with the request, and
the associated parking availability.
*/
@Entity
public class ReservationRequest extends AssertionConcern {
@Id
@GeneratedValue
private UUID requestId;
/**
* Identifier of the user who is arriving and making the reservation request.
*/
@Column(nullable = false)
private UUID arrivingUserId;
/**
* Identifier of the user who is leaving and offering the parking spot.
*/
@Column(nullable = false)
private UUID leavingUserId;
/**
* Current status of the reservation request.
*/
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private RequestStatus status;
/**
* Timestamp when the reservation request was created.
*/
@Column(nullable = false)
private LocalDateTime requestedAt;
/**
* Timestamp when the reservation request was responded to.
*/
private LocalDateTime respondedAt;
/**
* Optional message included with the reservation request.
*/
private String message;
/**
* The associated parking availability related to this request.
*/
@ManyToOne
private Availability availability;
/**
* Protected constructor for JPA use only.
*/
protected ReservationRequest() {
}
/**
* Creates a new reservation request.
*
* @param arrivingUserId the UUID of the arriving user
* @param leavingUserId the UUID of the leaving user
* @param message an optional message for the request
* @param availability the associated parking availability
* @return a new instance of {@code ReservationRequest}
*/
public static ReservationRequest create(UUID arrivingUserId, UUID leavingUserId,
String message, Availability availability) {
return new ReservationRequest(arrivingUserId, leavingUserId, message, availability);
}
/**
* Private constructor to initialize a new reservation request with the provided details.
*
* @param arrivingUserId the UUID of the arriving user
* @param leavingUserId the UUID of the leaving user
* @param message an optional message for the request
* @param availability the associated parking availability
*/
private ReservationRequest(UUID arrivingUserId, UUID leavingUserId,
String message, Availability availability) {
this.setArrivingUserId(arrivingUserId);
this.setLeavingUserId(leavingUserId);
this.setStatus(RequestStatus.PENDING);
this.setRequestedAt(LocalDateTime.now());
this.setMessage(message);
this.setAvailability(availability);
}
// Business methods
/**
* Allows the leaving user to respond to the reservation request, updating the status to accepted or rejected
* and recording the response time.
*
* @param leavingUserId the UUID of the leaving user responding to the request
* @param accepted {@code true} if the request is accepted; {@code false} otherwise
* @throws IllegalArgumentException if the leavingUserId does not match or the request is not pending
*/
public void respond(UUID leavingUserId, boolean accepted) {
assertArgumentTrue(this.leavingUserId.equals(leavingUserId), "You do not have permission to respond to this request");
assertArgumentTrue(this.status.equals(RequestStatus.PENDING), "Request has already been responded to");
this.setRespondedAt(LocalDateTime.now());
this.setStatus(accepted ? RequestStatus.ACCEPTED : RequestStatus.REJECTED);
}
/**
* Allows the arriving user to cancel the reservation request if it's still pending, updating the status
* to canceled and recording the cancellation time.
*
* @throws IllegalArgumentException if the request is not pending
*/
public void cancel() {
assertArgumentTrue(this.status == RequestStatus.PENDING, "Only pending requests can be canceled.");
this.setStatus(RequestStatus.CANCELED);
this.setRespondedAt(LocalDateTime.now());
}
// Getters and Setters with validation
/**
* Returns the unique identifier for the reservation request.
*
* @return the {@code requestId}
*/
public UUID getRequestId() {
return requestId;
}
private void setAvailability(Availability availability) {
this.availability = availability;
}
/**
* Returns the associated availability related to this request.
*
* @return the {@code availability}
*/
public Availability getAvailability() {
return availability;
}
/**
* Returns the UUID of the arriving user.
*
* @return the {@code arrivingUserId}
*/
public UUID getArrivingUserId() {
return arrivingUserId;
}
private void setArrivingUserId(UUID arrivingUserId) {
assertArgumentNotNull(arrivingUserId, "ArrivingUserId cannot be null");
this.arrivingUserId = arrivingUserId;
}
/**
* Returns the UUID of the leaving user.
*
* @return the {@code leavingUserId}
*/
public UUID getLeavingUserId() {
return leavingUserId;
}
private void setLeavingUserId(UUID leavingUserId) {
assertArgumentNotNull(leavingUserId, "LeavingUserId cannot be null");
this.leavingUserId = leavingUserId;
}
/**
* Returns the current status of the reservation request.
*
* @return the {@code status}
*/
public RequestStatus getStatus() {
return status;
}
private void setStatus(RequestStatus status) {
assertArgumentNotNull(status, "Status cannot be null");
this.status = status;
}
/**
* Returns the timestamp when the reservation request was created.
*
* @return the {@code requestedAt} timestamp
*/
public LocalDateTime getRequestedAt() {
return requestedAt;
}
private void setRequestedAt(LocalDateTime requestedAt) {
this.requestedAt = requestedAt;
}
/**
* Returns the timestamp when the reservation request was responded to or canceled.
*
* @return the {@code respondedAt} timestamp
*/
public LocalDateTime getRespondedAt() {
return respondedAt;
}
private void setRespondedAt(LocalDateTime respondedAt) {
this.respondedAt = respondedAt;
}
/**
* Returns the optional message included with the reservation request.
*
* @return the {@code message}
*/
public String getMessage() {
return message;
}
private void setMessage(String message) {
this.message = message;
}
}
Consider the above and consider that i want to add the feature to get the requests such that i can confirm/deny the different requests(otherwise i dont' hae the id)
To enable the feature where the leaving user can retrieve reservation requests made to their parking spot (availability), so they can confirm or deny them, we'll need to make several additions and modifications to your existing codebase. This will allow users to get the list of reservation requests, including the IDs required to respond to them.
Below are the steps to implement this feature:
Add a Method in the Service Interface:
Extend the AvailabilityApplicationService interface to include a method that retrieves reservation requests for a given availability or for a leaving user.
Implement the Method in the Service Implementation:
In AvailabilityApplicationServiceImpl, implement the method to fetch reservation requests and map them to DTOs.
Add Repository Methods:
Ensure the repository layer can fetch the necessary data, possibly by adding new methods to AvailabilityRepository and JpaAvailabilityRepository.
Extend the Controller:
Add new endpoints in AvailabilityController to expose the functionality to clients.
Update the Mapper if Necessary:
Ensure that AvailabilityMapper can map domain models to DTOs appropriately.
Let's walk through each step with code examples.
1. Extend the Service Interface
Add methods to fetch reservation requests either for a specific availability or for all availabilities of a leaving user.
2. Implement the Method in the Service Implementation
Implement the method in AvailabilityApplicationServiceImpl.
Option A: By Availability ID
@Service
public class AvailabilityApplicationServiceImpl implements AvailabilityApplicationService {
// Existing dependencies...
@Override
public List<ReservationRequestResponse> getReservationRequestsForAvailability(AvailabilityId availabilityId) {
Availability availability = availabilityRepository.findByAvailabilityId(availabilityId)
.orElseThrow(() -> new IllegalArgumentException("Availability not found"));
// Ensure the caller has permission (optional)
// ...
// Map the reservation requests to DTOs
return availability.getReservationRequests().stream()
.map(availabilityMapper::toReservationResponse)
.collect(Collectors.toList());
}
// Existing methods...
}
Option B: By Leaving User ID
@Service
public class AvailabilityApplicationServiceImpl implements AvailabilityApplicationService {
// Existing dependencies...
@Override
public List<ReservationRequestResponse> getReservationRequestsForLeavingUser(UUID leavingUserId) {
// Fetch all availabilities posted by the leaving user
List<Availability> availabilities = availabilityRepository.findByLeavingUserId(leavingUserId);
// Collect all pending reservation requests
return availabilities.stream()
.flatMap(availability -> availability.getReservationRequests().stream())
.filter(request -> request.getStatus() == RequestStatus.PENDING)
.map(availabilityMapper::toReservationResponse)
.collect(Collectors.toList());
}
// Existing methods...
}
3. Add Methods to the Repository
Add the necessary methods to AvailabilityRepository and JpaAvailabilityRepository.
In AvailabilityRepository:
public interface AvailabilityRepository {
// Existing methods...
List<Availability> findByLeavingUserId(UUID leavingUserId);
// Add other methods if needed
}
In JpaAvailabilityRepository:
@Repository
public interface JpaAvailabilityRepository extends AvailabilityRepository, JpaRepository<Availability, UUID> {
// Existing methods...
@Override
List<Availability> findByLeavingUserId(UUID leavingUserId);
// Implement any custom queries if necessary
}
4. Extend the Controller
Add new endpoints in AvailabilityController.
Option A: Endpoint to Get Requests for a Specific Availability
@RestController
@RequestMapping("/api/availability")
public class AvailabilityController {
// Existing dependencies and methods...
@GetMapping("/{availabilityId}/requests")
public List<ReservationRequestResponse> getReservationRequests(
@PathVariable UUID availabilityId) {
return availabilityService.getReservationRequestsForAvailability(AvailabilityId.of(availabilityId));
}
// Existing methods...
}
Option B: Endpoint to Get All Requests for a Leaving User
@RestController
@RequestMapping("/api/availability")
public class AvailabilityController {
// Existing dependencies and methods...
@GetMapping("/requests")
public List<ReservationRequestResponse> getReservationRequestsForUser(
@RequestParam UUID leavingUserId) {
return availabilityService.getReservationRequestsForLeavingUser(leavingUserId);
}
// Existing methods...
}
Note: If your application uses authentication, you can retrieve leavingUserId from the authenticated user context instead of passing it as a request parameter.
5. Ensure the Mapper Can Handle the Mapping
Confirm that AvailabilityMapper can map ReservationRequest to ReservationRequestResponse.
You likely already have this method:
public interface AvailabilityMapper {
// Existing methods...
ReservationRequestResponse toReservationResponse(ReservationRequest request);
// Add other mapping methods if needed
}
If required, update AvailabilityMapperImpl accordingly.
6. Security Considerations
Ensure that users cannot access reservation requests they are not authorized to view. Implement security checks in your service or controller to verify that the requesting user has the right to access the data.
For example, in the service method:
@Override
public List<ReservationRequestResponse> getReservationRequestsForAvailability(AvailabilityId availabilityId) {
Availability availability = availabilityRepository.findByAvailabilityId(availabilityId)
.orElseThrow(() -> new IllegalArgumentException("Availability not found"));
// Ensure the user has permission (pseudo-code)
UUID currentUserId = getCurrentUserId(); // Implement this method to get the authenticated user's ID
if (!availability.getLeavingUserId().equals(currentUserId)) {
throw new AccessDeniedException("You do not have permission to view these requests");
}
// Map the reservation requests to DTOs
return availability.getReservationRequests().stream()
.map(availabilityMapper::toReservationResponse)
.collect(Collectors.toList());
}
Replace getCurrentUserId() with your actual method of retrieving the authenticated user's ID based on your security framework (e.g., Spring Security).
7. Update the Frontend or API Clients
Now that the endpoint is available, update your frontend or API clients to call this endpoint to fetch reservation requests. They can now display the requests to the leaving user, allowing them to accept or reject them using the existing respondToReservation endpoint.
Summary
By adding these methods and endpoints, you provide the functionality for the leaving user to retrieve reservation requests made to their parking spots. This enables them to see the request IDs and respond accordingly.
Example Code for Clarity
AvailabilityApplicationService.java
public interface AvailabilityApplicationService {
// Existing methods...
List<ReservationRequestResponse> getReservationRequestsForAvailability(AvailabilityId availabilityId);
// Or, to get all requests for a leaving user
List<ReservationRequestResponse> getReservationRequestsForLeavingUser(UUID leavingUserId);
}
AvailabilityApplicationServiceImpl.java
@Service
public class AvailabilityApplicationServiceImpl implements AvailabilityApplicationService {
// Existing dependencies...
@Override
public List<ReservationRequestResponse> getReservationRequestsForAvailability(AvailabilityId availabilityId) {
Availability availability = availabilityRepository.findByAvailabilityId(availabilityId)
.orElseThrow(() -> new IllegalArgumentException("Availability not found"));
// Permissions check (optional)
// ...
// Map to DTOs
return availability.getReservationRequests().stream()
.map(availabilityMapper::toReservationResponse)
.collect(Collectors.toList());
}
// Or, implement the method to get all requests for a leaving user
@Override
public List<ReservationRequestResponse> getReservationRequestsForLeavingUser(UUID leavingUserId) {
List<Availability> availabilities = availabilityRepository.findByLeavingUserId(leavingUserId);
return availabilities.stream()
.flatMap(availability -> availability.getReservationRequests().stream())
.map(availabilityMapper::toReservationResponse)
.collect(Collectors.toList());
}
// Existing methods...
}
AvailabilityController.java
@RestController
@RequestMapping("/api/availability")
public class AvailabilityController {
// Existing dependencies...
@GetMapping("/{availabilityId}/requests")
public List<ReservationRequestResponse> getReservationRequests(
@PathVariable UUID availabilityId) {
return availabilityService.getReservationRequestsForAvailability(AvailabilityId.of(availabilityId));
}
// Or, to get all requests for a leaving user
@GetMapping("/requests")
public List<ReservationRequestResponse> getReservationRequestsForUser(
@RequestParam UUID leavingUserId) {
return availabilityService.getReservationRequestsForLeavingUser(leavingUserId);
}
// Existing methods...
}
AvailabilityRepository.java
public interface AvailabilityRepository {
// Existing methods...
List<Availability> findByLeavingUserId(UUID leavingUserId);
// Add other methods if needed
}
JpaAvailabilityRepository.java
@Repository
public interface JpaAvailabilityRepository extends AvailabilityRepository, JpaRepository<Availability, UUID> {
// Existing methods...
@Override
List<Availability> findByLeavingUserId(UUID leavingUserId);
// Implement any custom queries if necessary
}
Note: Ensure you handle exceptions and edge cases appropriately, such as when no reservation requests are found or when access is denied.