Clean up Transaction Script

This commit is contained in:
Ilkka Seppälä
2020-08-11 17:17:25 +03:00
parent d091e369ec
commit 1683fbdf9c
12 changed files with 40 additions and 27 deletions

View File

@ -0,0 +1,145 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.transactionscript;
import java.util.List;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Transaction Script (TS) is one of the simplest domain logic pattern.
* It needs less work to implement than other domain logic patterns and therefore
* its perfect fit for smaller applications that don't need big architecture behind them.
*
* <p>In this example we will use the TS pattern to implement booking and cancellation
* methods for a Hotel management App. The main method will initialise an instance of
* {@link Hotel} and add rooms to it. After that it will book and cancel a couple of rooms
* and that will be printed by the logger.</p>
*
* <p>The thing we have to note here is that all the operations related to booking or cancelling
* a room like checking the database if the room exists, checking the booking status or the
* room, calculating refund price are all clubbed inside a single transaction script method.</p>
*/
public class App {
private static final String H2_DB_URL = "jdbc:h2:~/test";
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point.
* Initialises an instance of Hotel and adds rooms to it.
* Carries out booking and cancel booking transactions.
* @param args command line arguments
* @throws Exception if any error occurs
*/
public static void main(String[] args) throws Exception {
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
final var dao = new HotelDaoImpl(dataSource);
// Add rooms
addRooms(dao);
// Print room booking status
getRoomStatus(dao);
var hotel = new Hotel(dao);
// Book rooms
hotel.bookRoom(1);
hotel.bookRoom(2);
hotel.bookRoom(3);
hotel.bookRoom(4);
hotel.bookRoom(5);
hotel.bookRoom(6);
// Cancel booking for a few rooms
hotel.cancelRoomBooking(1);
hotel.cancelRoomBooking(3);
hotel.cancelRoomBooking(5);
getRoomStatus(dao);
deleteSchema(dataSource);
}
private static void getRoomStatus(HotelDaoImpl dao) throws Exception {
try (var customerStream = dao.getAll()) {
customerStream.forEach((customer) -> LOGGER.info(customer.toString()));
}
}
private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
}
}
private static void createSchema(DataSource dataSource) throws Exception {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL);
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
/**
* Get database.
*
* @return h2 datasource
*/
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setUrl(H2_DB_URL);
return dataSource;
}
private static void addRooms(HotelDaoImpl hotelDao) throws Exception {
for (var room : generateSampleRooms()) {
hotelDao.add(room);
}
}
/**
* Generate rooms.
*
* @return list of rooms
*/
private static List<Room> generateSampleRooms() {
final var room1 = new Room(1, "Single", 50, false);
final var room2 = new Room(2, "Double", 80, false);
final var room3 = new Room(3, "Queen", 120, false);
final var room4 = new Room(4, "King", 150, false);
final var room5 = new Room(5, "Single", 50, false);
final var room6 = new Room(6, "Double", 80, false);
return List.of(room1, room2, room3, room4, room5, room6);
}
}

View File

@ -0,0 +1,87 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.transactionscript;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Hotel {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
private final HotelDaoImpl hotelDao;
public Hotel(HotelDaoImpl hotelDao) {
this.hotelDao = hotelDao;
}
/**
* Book a room.
*
* @param roomNumber room to book
* @throws Exception if any error
*/
public void bookRoom(int roomNumber) throws Exception {
var room = hotelDao.getById(roomNumber);
if (room.isEmpty()) {
throw new Exception("Room number: " + roomNumber + " does not exist");
} else {
if (room.get().isBooked()) {
throw new Exception("Room already booked!");
} else {
var updateRoomBooking = room.get();
updateRoomBooking.setBooked(true);
hotelDao.update(updateRoomBooking);
}
}
}
/**
* Cancel a room booking.
*
* @param roomNumber room to cancel booking
* @throws Exception if any error
*/
public void cancelRoomBooking(int roomNumber) throws Exception {
var room = hotelDao.getById(roomNumber);
if (room.isEmpty()) {
throw new Exception("Room number: " + roomNumber + " does not exist");
} else {
if (room.get().isBooked()) {
var updateRoomBooking = room.get();
updateRoomBooking.setBooked(false);
int refundAmount = updateRoomBooking.getPrice();
hotelDao.update(updateRoomBooking);
LOGGER.info("Booking cancelled for room number: " + roomNumber);
LOGGER.info(refundAmount + " is refunded");
} else {
throw new Exception("No booking for the room exists");
}
}
}
}

View File

@ -0,0 +1,40 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.transactionscript;
import java.util.Optional;
import java.util.stream.Stream;
public interface HotelDao {
Stream<Room> getAll() throws Exception;
Optional<Room> getById(int id) throws Exception;
Boolean add(Room room) throws Exception;
Boolean update(Room room) throws Exception;
Boolean delete(Room room) throws Exception;
}

View File

@ -0,0 +1,172 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.transactionscript;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HotelDaoImpl implements HotelDao {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
private final DataSource dataSource;
public HotelDaoImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Stream<Room> getAll() throws Exception {
try {
var connection = getConnection();
var statement = connection.prepareStatement("SELECT * FROM ROOMS");
var resultSet = statement.executeQuery(); // NOSONAR
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Room>(Long.MAX_VALUE,
Spliterator.ORDERED) {
@Override
public boolean tryAdvance(Consumer<? super Room> action) {
try {
if (!resultSet.next()) {
return false;
}
action.accept(createRoom(resultSet));
return true;
} catch (Exception e) {
throw new RuntimeException(e); // NOSONAR
}
}
}, false).onClose(() -> {
try {
mutedClose(connection, statement, resultSet);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
});
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
@Override
public Optional<Room> getById(int id) throws Exception {
ResultSet resultSet = null;
try (var connection = getConnection();
var statement = connection.prepareStatement("SELECT * FROM ROOMS WHERE ID = ?")) {
statement.setInt(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(createRoom(resultSet));
} else {
return Optional.empty();
}
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
} finally {
if (resultSet != null) {
resultSet.close();
}
}
}
@Override
public Boolean add(Room room) throws Exception {
if (getById(room.getId()).isPresent()) {
return false;
}
try (var connection = getConnection();
var statement = connection.prepareStatement("INSERT INTO ROOMS VALUES (?,?,?,?)")) {
statement.setInt(1, room.getId());
statement.setString(2, room.getRoomType());
statement.setInt(3, room.getPrice());
statement.setBoolean(4, room.isBooked());
statement.execute();
return true;
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
@Override
public Boolean update(Room room) throws Exception {
try (var connection = getConnection();
var statement =
connection
.prepareStatement("UPDATE ROOMS SET ROOM_TYPE = ?, PRICE = ?, BOOKED = ?"
+ " WHERE ID = ?")) {
statement.setString(1, room.getRoomType());
statement.setInt(2, room.getPrice());
statement.setBoolean(3, room.isBooked());
statement.setInt(4, room.getId());
return statement.executeUpdate() > 0;
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
@Override
public Boolean delete(Room room) throws Exception {
try (var connection = getConnection();
var statement = connection.prepareStatement("DELETE FROM ROOMS WHERE ID = ?")) {
statement.setInt(1, room.getId());
return statement.executeUpdate() > 0;
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
private Connection getConnection() throws Exception {
return dataSource.getConnection();
}
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet)
throws Exception {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
private Room createRoom(ResultSet resultSet) throws Exception {
return new Room(resultSet.getInt("ID"),
resultSet.getString("ROOM_TYPE"),
resultSet.getInt("PRICE"),
resultSet.getBoolean("BOOKED"));
}
}

View File

@ -0,0 +1,123 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.transactionscript;
/**
* A room POJO that represents the data that will be read from the data source.
*/
public class Room {
private int id;
private String roomType;
private int price;
private boolean booked;
/**
* Create an instance of room.
* @param id room id
* @param roomType room type
* @param price room price
* @param booked room booking status
*/
public Room(int id, String roomType, int price, boolean booked) {
this.id = id;
this.roomType = roomType;
this.price = price;
this.booked = booked;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isBooked() {
return booked;
}
public void setBooked(boolean booked) {
this.booked = booked;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Room room = (Room) o;
if (id != room.id) {
return false;
}
if (price != room.price) {
return false;
}
if (booked != room.booked) {
return false;
}
return roomType.equals(room.roomType);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + roomType.hashCode();
result = 31 * result + price;
result = 31 * result + (booked ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Room{"
+ "id=" + id
+ ", roomType=" + roomType
+ ", price=" + price
+ ", booked=" + booked
+ '}';
}
}

View File

@ -0,0 +1,38 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.transactionscript;
/**
* Customer Schema SQL Class.
*/
public final class RoomSchemaSql {
public static final String CREATE_SCHEMA_SQL =
"CREATE TABLE ROOMS (ID NUMBER, ROOM_TYPE VARCHAR(100), PRICE INT(100), BOOKED VARCHAR(100))";
public static final String DELETE_SCHEMA_SQL = "DROP TABLE ROOMS IF EXISTS";
private RoomSchemaSql() {
}
}