@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);
code
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.REQUEST_PENDING),
"Only spots with a reqeust pending 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);
}
/**
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);
code
// 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;
code
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 {
code
@Id
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.setRequestId(UUID.randomUUID());
this.setArrivingUserId(arrivingUserId);
this.setLeavingUserId(leavingUserId);
this.setStatus(RequestStatus.PENDING);
this.setRequestedAt(LocalDateTime.now());
this.setMessage(message);
this.setAvailability(availability);
}
// Business methods
private void setRequestId(UUID requestId){
this.requestId = requestId;
}
/**
* 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;
}
public class RewardCompletedEvent implements DomainEvent {
code
private final UUID rewardId;
private final Instant occurredOn;
private final String moduleName = "reward"; // TODO you should't set this manually
public RewardCompletedEvent(UUID rewardId) {
this.rewardId = rewardId;
this.occurredOn = Instant.now();
}
public UUID getRewardId() {
return rewardId;
}
@Override
public int eventVersion() {
return 0;
}
@Override
public Instant occurredOn() {
return occurredOn;
}
@Override
public String moduleName() {
return moduleName;
}
@Service
public class RewardCalculationServiceImpl implements RewardCalculationService {
code
@Override
public BigDecimal calculateRewardAmount(UUID availabilityId) {
// Implement reward calculation logic
// For example, base amount + demand factor + user reputation
// Placeholder for actual logic
return BigDecimal.valueOf(5.00);
}
How can we manage to make it process the reward when a available spot is confirmed?
Note that you can use the message using the core functionality of our company framework
for example this is used in another application
package org.parkapp.parking.infrastructure;
@Bean(name = "parkingSpotCreatedQueue")
public Queue parkingSpotCreatedQueue() {
return new Queue("org.parkapp.parking.domain.parkingspot.ParkingSpotCreatedEvent", true, false, false);
}
}
create also the configuration file if you can, and explain why you have configured it that way
To manage processing the reward when an available spot is confirmed, we will leverage the messaging capabilities provided by our company's framework using RabbitMQ. Specifically, we'll set up the reward application to listen for the SpotTakenConfirmedEvent published by the parking availability application. When this event is received, the reward application will trigger the RewardApplicationService to process the reward.
Here's how we can achieve this:
1. Create an Event Listener in the Reward Application
First, we'll create a listener in the reward application that listens for the SpotTakenConfirmedEvent. This listener will deserialize the event, extract the necessary information, and invoke the reward processing logic.
We'll create a RabbitMQ configuration in the reward application that declares the necessary exchange, queue, and binding to receive the SpotTakenConfirmedEvent.
java
// RewardRabbitMQConfig.java
package com.parkingexchange.reward.infrastructure.messaging.rabbitmq;
import com.parkingexchange.Modules;
import com.parkingexchange.common.infrastructure.notification.RabbitConfigurationProperties;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RewardRabbitMQConfig {
private final RabbitConfigurationProperties rabbitConfigurationProperties;
private static final String topicExchangeName = Modules.PARKING_MODULE_NAME;
public RewardRabbitMQConfig(RabbitConfigurationProperties rabbitConfigurationProperties) {
this.rabbitConfigurationProperties = rabbitConfigurationProperties;
}
@Bean
public TopicExchange parkingExchange() {
return new TopicExchange(rabbitConfigurationProperties.getExchange(topicExchangeName));
}
@Bean
public Queue spotTakenConfirmedQueue() {
return new Queue("com.parkingexchange.reward.domain.event.SpotTakenConfirmedEvent", true);
}
@Bean
public Binding spotTakenConfirmedBinding(Queue spotTakenConfirmedQueue, TopicExchange parkingExchange) {
return BindingBuilder.bind(spotTakenConfirmedQueue)
.to(parkingExchange)
.with("com.parkingexchange.reward.domain.event.SpotTakenConfirmedEvent");
}
}
Explanation of the Configuration
Exchange (parkingExchange): We declare a TopicExchange named after the parking module. This is where parking-related events are published.
Queue (spotTakenConfirmedQueue): We declare a queue with a name matching the fully qualified class name of the event we're interested in (SpotTakenConfirmedEvent). This naming convention helps in routing messages based on event types.
Binding (spotTakenConfirmedBinding): We bind the queue to the exchange using a routing key that matches the queue name (event class name). This ensures that messages published to the exchange with a routing key matching the event class name are routed to our queue.
In the parking availability application, when the SpotTakenConfirmedEvent is published, it should be sent to the parkingExchange with a routing key that matches the event's fully qualified class name. This ensures the message is routed to the appropriate queue in the reward application.
java
// Within ParkingApplication when publishing the event
public void publishDomainEvents(Availability availability) {
List<DomainEvent> events = availability.domainEvents();
for (DomainEvent event : events) {
domainEventPublisher.publish(event);
}
}
// DomainEventPublisher implementation should publish to 'parkingExchange' using the event class name as the routing key
4. Use Company Framework's Messaging Features
By leveraging the company's messaging framework, we follow established conventions for event publishing and consumption. The framework likely handles the serialization and deserialization of event messages, routing, and other low-level details, allowing us to focus on business logic.
Why Configured This Way
Loose Coupling: By using a messaging system, we decouple the parking and reward applications. This allows each service to evolve independently and scale separately.
Routing Based on Event Types: Using the event's fully qualified class name as the routing key enables fine-grained control over which services receive which events.
Scalability and Flexibility: Topic exchanges in RabbitMQ allow multiple consumers to receive the same message if they are interested in it. This is ideal for event-driven architectures where multiple services may need to react to the same event.
Company Framework Alignment: By following the patterns and configurations used in other applications within the company, such as the provided RabbitmqParkingSpotCreatedEventListener, we maintain consistency and take advantage of any built-in features or tools provided by the framework.
Conclusion
By setting up an event listener in the reward application and configuring RabbitMQ appropriately, we can efficiently process rewards whenever a parking spot is confirmed as taken. This approach aligns with best practices in microservices architecture and leverages the company's existing framework for messaging and event handling.
Note: The code snippets provided are illustrative and may require adjustments based on the actual implementations of EventSerializer, PropertiesSerializer, and other company-specific classes and interfaces.