Skip to content

Commit

Permalink
refactoring booking endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Schwarz committed Oct 1, 2021
1 parent 150d57a commit 65b40f1
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import eu.europa.ec.dgc.booking.dto.BookingResponse;
import eu.europa.ec.dgc.booking.dto.DevDccStatus;
import eu.europa.ec.dgc.booking.entity.BookingEntity;
import eu.europa.ec.dgc.booking.exception.BookingNotFoundException;
import eu.europa.ec.dgc.booking.service.BookingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
Expand Down Expand Up @@ -81,7 +82,14 @@ public BookingResponse booking(
log.debug("Incoming POST request to '{}' with content '{}', optional dccStatus '{}' and sessionId '{}'",
PATH, booking, dccStatus, sessionId);
bookingService.create(sessionId, booking, dccStatus);
return converter.convert(bookingService.getBySessionId(sessionId), BookingResponse.class);

try {
return converter.convert(bookingService
.getBySessionId(sessionId), BookingResponse.class);
} catch (BookingNotFoundException e) {
return converter.convert(bookingService
.getByReference(booking.getBookingReference()), BookingResponse.class);
}
}

/**
Expand All @@ -101,7 +109,8 @@ public BookingResponse booking(
@ResponseStatus(code = HttpStatus.OK)
@PostMapping(path = PATH_REPLACE,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public BookingResponse replace(@Valid @RequestBody final BookingReplaceRequest request, final HttpSession session) {
public BookingResponse replace(
@Valid @RequestBody final BookingReplaceRequest request, final HttpSession session) {
final String sessionId = session.getId();
log.debug("Incoming POST request to '{}' with content '{}' and sessionId '{}'",
PATH_REPLACE, request, sessionId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public class BookingH2Entity {
@Column(name = "session_id", columnDefinition = "varchar(255)", nullable = false, updatable = false)
private String sessionId;

@Column(name = "reference", columnDefinition = "varchar(255)")
private String reference;

@Column(name = "booking", columnDefinition = "varchar(2147483647)")
private String bookingJson;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@
package eu.europa.ec.dgc.booking.repository;

import eu.europa.ec.dgc.booking.entity.BookingH2Entity;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookingH2Repository extends JpaRepository<BookingH2Entity, String> {

List<BookingH2Entity> findByReference(final String reference);

void deleteByReference(final String reference);
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
@Repository
public interface PassengersH2Repository extends JpaRepository<PassengersH2Entity, UUID> {

void deleteAllBySessionId(String sessionId);
void deleteAllBySessionId(final String sessionId);

boolean existsBySessionId(String sessionId);
boolean existsBySessionId(final String sessionId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import eu.europa.ec.dgc.booking.exception.BookingNotFoundException;
import eu.europa.ec.dgc.booking.repository.BookingH2Repository;
import eu.europa.ec.dgc.booking.repository.PassengersH2Repository;
import java.util.Optional;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -50,8 +51,8 @@ public class BookingPersistenceService {
* @param sessionId Session ID
* @return {@link BookingEntity}
*/
public BookingEntity getBySessionId(String sessionId) {
BookingH2Entity entity = this.bookingRepository.findById(sessionId)
public BookingEntity getBySessionId(final String sessionId) {
final BookingH2Entity entity = this.bookingRepository.findById(sessionId)
.orElseThrow(BookingNotFoundException::new);
return this.fromJson(entity.getBookingJson());
}
Expand All @@ -62,8 +63,8 @@ public BookingEntity getBySessionId(String sessionId) {
* @param passengerId Passenger ID as string
* @return {@link BookingEntity}
*/
public BookingEntity getByPassengerId(String passengerId) {
return getByPassengerId(UUID.fromString(passengerId));
public BookingEntity getByPassengerId(final String passengerId) {
return this.getByPassengerId(UUID.fromString(passengerId));
}

/**
Expand All @@ -77,6 +78,18 @@ public BookingEntity getByPassengerId(final UUID passengerId) {
return this.getBySessionId(sessionId);
}

/**
* Returns booking by reference.
*
* @param reference {@link String}
* @return {@link BookingEntity}
*/
public Optional<BookingEntity> getByReference(final String reference) {
return this.bookingRepository.findByReference(reference).stream()
.findFirst()
.map(booking -> this.fromJson(booking.getBookingJson()));
}

/**
* Returns SessionID by passenger ID.
*
Expand All @@ -94,7 +107,7 @@ public String getSessionIdByPassengerId(final String passengerId) {
* @return Session ID
*/
public String getSessionIdByPassengerId(final UUID passengerId) {
final PassengersH2Entity entity = passengersRepository.findById(passengerId)
final PassengersH2Entity entity = this.passengersRepository.findById(passengerId)
.orElseThrow(() -> new BookingNotFoundException(
String.format("Booking not found by passenger ID '%s'", passengerId)));
return entity.getSessionId();
Expand All @@ -106,46 +119,50 @@ public String getSessionIdByPassengerId(final UUID passengerId) {
* @param sessionId Session ID
* @param booking Booking
*/
public void save(String sessionId, BookingEntity booking) {
public void save(final String sessionId, final BookingEntity booking) {
this.cleanBySessionId(sessionId);

BookingH2Entity entity = new BookingH2Entity();
final BookingH2Entity entity = new BookingH2Entity();
entity.setSessionId(sessionId);
entity.setReference(booking.getReference());
entity.setBookingJson(this.toJson(booking));
bookingRepository.save(entity);
this.bookingRepository.save(entity);

// save passengers IDs
booking.getPassengers().stream().map(passenger -> {
PassengersH2Entity passEntity = new PassengersH2Entity();
final PassengersH2Entity passEntity = new PassengersH2Entity();
passEntity.setId(passenger.getId());
passEntity.setSessionId(sessionId);
return passEntity;
}).forEach(passengersRepository::save);
}

private void cleanBySessionId(String sessionId) {
if (bookingRepository.existsById(sessionId)) {
bookingRepository.deleteById(sessionId);
public void deleteByReference(final String reference) {
this.bookingRepository.deleteByReference(reference);
}

private void cleanBySessionId(final String sessionId) {
if (this.bookingRepository.existsById(sessionId)) {
this.bookingRepository.deleteById(sessionId);
}
if (passengersRepository.existsBySessionId(sessionId)) {
passengersRepository.deleteAllBySessionId(sessionId);
if (this.passengersRepository.existsBySessionId(sessionId)) {
this.passengersRepository.deleteAllBySessionId(sessionId);
}
}

private BookingEntity fromJson(String data) {
private BookingEntity fromJson(final String data) {
try {
return mapper.readValue(data, BookingEntity.class);
return this.mapper.readValue(data, BookingEntity.class);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}

private String toJson(BookingEntity data) {
private String toJson(final BookingEntity data) {
try {
return mapper.writeValueAsString(data);
return this.mapper.writeValueAsString(data);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}

}
65 changes: 45 additions & 20 deletions src/main/java/eu/europa/ec/dgc/booking/service/BookingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,16 @@
import eu.europa.ec.dgc.booking.exception.NotImplementedException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class BookingService {
Expand Down Expand Up @@ -65,7 +68,7 @@ public class BookingService {
*
* @return {@link BookingEntity}
*/
public BookingEntity getBySessionId(String sessionId) {
public BookingEntity getBySessionId(final String sessionId) {
return this.persistence.getBySessionId(sessionId);
}

Expand All @@ -75,10 +78,22 @@ public BookingEntity getBySessionId(String sessionId) {
* @param passengerId Passenger ID
* @return {@link BookingEntity}
*/
public BookingEntity getByPassengerId(String passengerId) {
public BookingEntity getByPassengerId(final String passengerId) {
return this.persistence.getByPassengerId(passengerId);
}

/**
* Return BookingEntity by reference.
*
* @param reference {@link String}
* @return {@link BookingEntity}
*/
public BookingEntity getByReference(final String reference) {
return this.persistence.getByReference(reference)
.orElseThrow(() -> new BookingNotFoundException(
String.format("Booking not found by reference '%s'", reference)));
}

/**
* Return current BookingEntity if passenger ID is found and limits the content to the passenger with the ID.
*
Expand All @@ -105,27 +120,36 @@ public BookingEntity getOnlyPassengerId(final String passengerId, final String s
* Create and write BookingEntity to session. if an entry already exists, it will be deleted.
*
* @param sessionId current Session ID
* @param bookingRequest data from the frontend
* @param request data from the frontend
* @param dccStatus status manipulation for test purposes
*/
public void create(String sessionId, BookingRequest bookingRequest, DevDccStatus dccStatus) {
BookingEntity bookingEntity = new BookingEntity();
bookingEntity.setReference(bookingRequest.getBookingReference());
bookingEntity.addPassenger(PassengerEntity.build(bookingRequest));

int passengersMin = dccStatus == DevDccStatus.MIX ? 1 : passengersGeneratorMin;
Integer numberToGenerate = new Random().nextInt(passengersGeneratorMax - passengersMin) + passengersMin;
for (int i = 0; i < numberToGenerate; i++) {
if (passengersRandom) {
bookingEntity.addPassenger(PassengerEntity.random());
} else {
bookingEntity.addPassenger(PassengerEntity.immutable(i));
public void create(final String sessionId, final BookingRequest request, final DevDccStatus dccStatus) {
final Optional<BookingEntity> entity = this.persistence.getByReference(request.getBookingReference());
final boolean isPreset = entity.isPresent()
&& request.getBookingReference() != null
&& request.getBookingReference().startsWith("preset");
if (!isPreset) {
log.info("Create new BookingEntity for reference '{}'", request.getBookingReference());
final BookingEntity bookingEntity = new BookingEntity();
bookingEntity.setReference(request.getBookingReference());
bookingEntity.addPassenger(PassengerEntity.build(request));

int passengersMin = dccStatus == DevDccStatus.MIX ? 1 : this.passengersGeneratorMin;
Integer numberToGenerate = new Random().nextInt(this.passengersGeneratorMax - passengersMin)
+ passengersMin;
for (int i = 0; i < numberToGenerate; i++) {
if (this.passengersRandom) {
bookingEntity.addPassenger(PassengerEntity.random());
} else {
bookingEntity.addPassenger(PassengerEntity.immutable(i));
}
}
}

this.updatePassengersDccStatus(dccStatus, bookingEntity);

persistence.save(sessionId, bookingEntity);
this.updatePassengersDccStatus(dccStatus, bookingEntity);
this.persistence.save(sessionId, bookingEntity);
} else {
log.info("Use existing BookingEntity by reference '{}'", request.getBookingReference());
}
}

/**
Expand All @@ -137,7 +161,8 @@ public void create(String sessionId, BookingRequest bookingRequest, DevDccStatus
*/
public BookingEntity replace(final String sessionId, final BookingReplaceRequest request) {
final BookingEntity entity = this.converter.convert(request, BookingEntity.class);
persistence.save(sessionId, entity);
this.persistence.deleteByReference(request.getReference());
this.persistence.save(sessionId, entity);
return entity;
}

Expand Down
1 change: 1 addition & 0 deletions src/main/resources/data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ CREATE TABLE passengers (

CREATE TABLE bookings (
session_id VARCHAR(255) PRIMARY KEY,
reference VARCHAR(255) DEFAULT NULL,
booking VARCHAR(2147483647) DEFAULT NULL
);

0 comments on commit 65b40f1

Please sign in to comment.