提交 e0fb2d01 编写于 作者: A Ashish Trivedi

#1321 Added comments and refactored code

上级 c4b1b89f
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-design-patterns</artifactId>
......@@ -15,14 +15,14 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package com.ashishtrivedi16.transactionscript;
import com.ashishtrivedi16.transactionscript.db.HotelDAOImpl;
import com.ashishtrivedi16.transactionscript.db.HotelDaoImpl;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
public class Hotel {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionScriptApp.class);
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionScriptApp.class);
private HotelDAOImpl hotelDAO;
private HotelDaoImpl hotelDao;
public Hotel(HotelDAOImpl hotelDAO) {
this.hotelDAO = hotelDAO;
}
public Hotel(HotelDaoImpl hotelDao) {
this.hotelDao = hotelDao;
}
public void bookRoom(int roomNumber) throws Exception {
/*
TODO
-> Check if room is available
-> Book the room
-> Commit transaction
*/
Optional<Room> room = hotelDAO.getById(roomNumber);
if (!room.isPresent()) {
LOGGER.info(roomNumber + " does not exist");
} else {
if (room.get().isBooked()) {
LOGGER.info("Room already booked!");
} else {
Room updateRoomBooking = room.get();
updateRoomBooking.setBooked(true);
hotelDAO.update(updateRoomBooking);
}
}
/**
* Book a room.
*
* @param roomNumber room to book
* @throws Exception if any error
*/
public void bookRoom(int roomNumber) throws Exception {
Optional<Room> room = hotelDao.getById(roomNumber);
if (room.isEmpty()) {
LOGGER.info(roomNumber + " does not exist");
} else {
if (room.get().isBooked()) {
LOGGER.info("Room already booked!");
} else {
Room 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 {
Optional<Room> room = hotelDao.getById(roomNumber);
public void cancelRoomBooking(int roomNumber) {
/*
if (room.isEmpty()) {
LOGGER.info("Room number: " + roomNumber + " does not exist");
} else {
if (room.get().isBooked()) {
Room updateRoomBooking = room.get();
updateRoomBooking.setBooked(false);
int refundAmount = updateRoomBooking.getPrice();
hotelDao.update(updateRoomBooking);
TODO
-> Check if room is booked
-> Calculate refund price
-> Cancel the room booking
-> Commit transaction
*/
LOGGER.info("Booking cancelled for room number: " + roomNumber);
LOGGER.info(refundAmount + " is refunded");
} else {
LOGGER.info("No booking for the room exists");
}
}
}
}
package com.ashishtrivedi16.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;
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;
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;
}
public String getRoomType() {
return roomType;
if (o == null || getClass() != o.getClass()) {
return false;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
Room room = (Room) o;
public int getPrice() {
return price;
if (id != room.id) {
return false;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isBooked() {
return booked;
if (price != room.price) {
return false;
}
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 == 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 +
'}';
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
+ '}';
}
}
package com.ashishtrivedi16.transactionscript;
import com.ashishtrivedi16.transactionscript.db.CustomException;
import com.ashishtrivedi16.transactionscript.db.HotelDAOImpl;
import com.ashishtrivedi16.transactionscript.db.HotelDaoImpl;
import com.ashishtrivedi16.transactionscript.db.RoomSchemaSql;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.h2.jdbc.JdbcSQLException;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.Logger;
......@@ -15,76 +13,96 @@ import org.slf4j.LoggerFactory;
public class TransactionScriptApp {
private static final String H2_DB_URL = "jdbc:h2:~/test";
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionScriptApp.class);
private static final String ALL_ROOMS = "customerDao.getAllRooms(): ";
private static final String H2_DB_URL = "jdbc:h2:~/test";
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionScriptApp.class);
private static final String ALL_ROOMS = "customerDao.getAllRooms(): ";
public static void main(String[] args) throws Exception {
/**
* Program entry point.
*
* @param args command line arguments
* @throws Exception if any error occurs
*/
public static void main(String[] args) throws Exception {
/*
TODO
-> Create in memory database and some sample tables for demo
*/
final var dataSource = createDataSource();
createSchema(dataSource);
final var DAO = new HotelDAOImpl(dataSource);
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
final var dao = new HotelDaoImpl(dataSource);
addRooms(dao);
addRooms(DAO);
try (var customerStream = DAO.getAll()) {
customerStream.forEach((customer) -> LOGGER.info(customer.toString()));
}
getRoomStatus(dao);
Hotel hotel = new Hotel(DAO);
Hotel hotel = new Hotel(dao);
hotel.bookRoom(1);
hotel.bookRoom(2);
hotel.bookRoom(3);
hotel.bookRoom(4);
hotel.bookRoom(5);
hotel.bookRoom(6);
hotel.bookRoom(1);
hotel.bookRoom(2);
hotel.bookRoom(3);
hotel.bookRoom(4);
hotel.bookRoom(5);
hotel.bookRoom(6);
hotel.cancelRoomBooking(3);
hotel.cancelRoomBooking(4);
hotel.cancelRoomBooking(1);
hotel.cancelRoomBooking(3);
hotel.cancelRoomBooking(5);
deleteSchema(dataSource);
getRoomStatus(dao);
}
deleteSchema(dataSource);
private static void deleteSchema(DataSource dataSource) throws 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 (JdbcSQLException e) {
throw new CustomException(e.getMessage(), e);
}
private static void getRoomStatus(HotelDaoImpl dao) throws Exception {
try (var customerStream = dao.getAll()) {
customerStream.forEach((customer) -> LOGGER.info(customer.toString()));
}
}
public static DataSource createDataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setUrl(H2_DB_URL);
return dataSource;
private static void deleteSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
}
private static void addRooms(HotelDAOImpl hotelDAO) throws Exception {
for (var room : generateSampleRooms()) {
hotelDAO.add(room);
}
}
private static void createSchema(DataSource dataSource) throws Exception {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL);
} catch (JdbcSQLException e) {
throw new CustomException(e.getMessage(), e);
}
public 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);
}
/**
* Get database.
*
* @return h2 datasource
*/
public static DataSource createDataSource() {
JdbcDataSource 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
*/
public 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);
}
}
package com.ashishtrivedi16.transactionscript.db;
import com.ashishtrivedi16.transactionscript.Room;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
public class HotelDAOImpl implements HotelDAO {
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");
ResultSet 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 (SQLException e) {
throw new RuntimeException(e); // NOSONAR
}
}
}, false).onClose(() -> {
try {
mutedClose(connection, statement, resultSet);
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (SQLException e) {
throw new CustomException(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 (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
} 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 (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
@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.setInt(1, room.getId());
statement.setString(2, room.getRoomType());
statement.setBoolean(3, room.isBooked());
statement.setInt(4, room.getId());
return statement.executeUpdate() > 0;
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
@Override
public Boolean delete(Room room) throws Exception {
try (var connection = getConnection();
var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
statement.setInt(1, room.getId());
return statement.executeUpdate() > 0;
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) throws Exception {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
throw new CustomException(e.getMessage(), e);
}
}
private Room createRoom(ResultSet resultSet) throws SQLException {
return new Room(resultSet.getInt("ID"),
resultSet.getString("ROOM_TYPE"),
resultSet.getInt("PRICE"),
resultSet.getBoolean("BOOKED"));
}
}
......@@ -5,15 +5,15 @@ import com.ashishtrivedi16.transactionscript.Room;
import java.util.Optional;
import java.util.stream.Stream;
public interface HotelDAO {
public interface HotelDao {
public Stream<Room> getAll() throws Exception;
Stream<Room> getAll() throws Exception;
public Optional<Room> getById(int id) throws Exception;
Optional<Room> getById(int id) throws Exception;
public Boolean add(Room room) throws Exception;
Boolean add(Room room) throws Exception;
public Boolean update(Room room) throws Exception;
Boolean update(Room room) throws Exception;
public Boolean delete(Room room) throws Exception;
Boolean delete(Room room) throws Exception;
}
package com.ashishtrivedi16.transactionscript.db;
import com.ashishtrivedi16.transactionscript.Room;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
public class HotelDaoImpl implements HotelDao {
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");
ResultSet 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 (SQLException e) {
throw new RuntimeException(e); // NOSONAR
}
}
}, false).onClose(() -> {
try {
mutedClose(connection, statement, resultSet);
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (SQLException e) {
throw new CustomException(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 (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
} 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 (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
@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 (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
@Override
public Boolean delete(Room room) throws Exception {
try (var connection = getConnection();
var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
statement.setInt(1, room.getId());
return statement.executeUpdate() > 0;
} catch (SQLException ex) {
throw new CustomException(ex.getMessage(), ex);
}
}
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet)
throws Exception {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
throw new CustomException(e.getMessage(), e);
}
}
private Room createRoom(ResultSet resultSet) throws SQLException {
return new Room(resultSet.getInt("ID"),
resultSet.getString("ROOM_TYPE"),
resultSet.getInt("PRICE"),
resultSet.getBoolean("BOOKED"));
}
}
......@@ -28,12 +28,11 @@ package com.ashishtrivedi16.transactionscript.db;
*/
public final class RoomSchemaSql {
private 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";
public static final String DELETE_SCHEMA_SQL = "DROP TABLE ROOMS";
private RoomSchemaSql() {
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册