Ticket Get Qr Code Service Layer
In this lesson, we'll implement the service layer logic to get the QR code image.
QR Code Repository Method
Let's begin by adding a new method to our QR code repository to help us find QR codes by both ticket ID and ticket purchaser ID.
Optional<QrCode> findByTicketIdAndTicketPurchaserId(UUID ticketId, UUID ticketPurchaseId);This method allows us to look up QR codes using both the ticket ID and the ID of the purchaser, ensuring we only return QR codes to their rightful owners.
Service Layer Implementation
Next, we'll implement the method in our QR code service to retrieve the QR code image.
@Override
public byte[] getQrCodeImageForUserAndTicket(UUID userId, UUID ticketId) {
QrCode qrCode = qrCodeRepository.findByTicketIdAndTicketPurchaserId(ticketId, userId)
.orElseThrow(QrCodeNotFoundException::new);
try {
return Base64.getDecoder().decode(qrCode.getValue());
catch(IllegalArgumentException ex) {
log.error("Invalid base64 QR Code for ticket ID: {}", ticketId, ex);
throw new QrCodeNotFoundException();
}
}The method performs two main tasks:
- It retrieves the QR code from the database using both the user ID and ticket ID.
- It decodes the Base64-encoded QR code back into a byte array.
If anything goes wrong during the process - either the QR code isn't found or can't be decoded - we throw appropriate exceptions and log the error.
Summary
- Added
findByTicketIdAndTicketPurchaserIdtoQrCodeRepository - Implemented
getQrCodeImageForUserAndTicketonQrCodeService