diff --git a/build.gradle b/build.gradle index 57267157c..a2b19928d 100644 --- a/build.gradle +++ b/build.gradle @@ -14,8 +14,12 @@ repositories { dependencies { implementation 'org.springframework.boot:spring-boot-starter' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'io.rest-assured:rest-assured:5.3.1' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + runtimeOnly 'com.h2database:h2' } test { diff --git a/src/main/java/roomescape/HomeController.java b/src/main/java/roomescape/HomeController.java new file mode 100644 index 000000000..e61379f36 --- /dev/null +++ b/src/main/java/roomescape/HomeController.java @@ -0,0 +1,13 @@ +package roomescape; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HomeController { + + @GetMapping("/") + public String home() { + return "home"; + } +} \ No newline at end of file diff --git a/src/main/java/roomescape/Reservation.java b/src/main/java/roomescape/Reservation.java new file mode 100644 index 000000000..2f6f28111 --- /dev/null +++ b/src/main/java/roomescape/Reservation.java @@ -0,0 +1,46 @@ +package roomescape; + + +public class Reservation{ + private Long id; + private String name; + private String date; + private String time; + public Reservation(){ + + } + public Reservation(Long id,String name,String date,String time){ + this.id = id; + this.name = name; + this.date = date; + this.time = time; + } + + public Reservation(String name,String date,String time){ + this.name = name; + this.date = date; + this.time = time; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDate() { + return date; + } + + public String getTime() { + return time; + } + + public static Reservation toEntity(Reservation reservation,Long id){ + return new Reservation(id,reservation.name,reservation.date,reservation.time); + } + + +} \ No newline at end of file diff --git a/src/main/java/roomescape/ReservationController.java b/src/main/java/roomescape/ReservationController.java new file mode 100644 index 000000000..e6153459d --- /dev/null +++ b/src/main/java/roomescape/ReservationController.java @@ -0,0 +1,103 @@ +package roomescape; + +import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.sql.PreparedStatement; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; + +import static org.apache.logging.log4j.util.Strings.isBlank; + +@Controller +public class ReservationController { + + private JdbcTemplate jdbcTemplate; + public ReservationController(JdbcTemplate jdbcTemplate){ + this.jdbcTemplate = jdbcTemplate; + } + + // render + @GetMapping("/reservation") + public String reservationPage() { + return "reservation"; + } + + // RowMapper + private final RowMapper rowMapper = (resultSet, rowNum) -> + new Reservation( + resultSet.getLong("id"), + resultSet.getString("name"), + resultSet.getString("date"), + resultSet.getString("time") + ); + + + // Read + @GetMapping("/reservations") + @ResponseBody + public List findAllReservations() { + String sql = "select id,name,date,time from reservation"; + return jdbcTemplate.query(sql,rowMapper); + } + + // Create + @PostMapping("/reservations") + public ResponseEntity add_reservation(@RequestBody Reservation reservation){ + // handle exception -> any required field empty + if(isBlank(reservation.getName()) || isBlank(reservation.getDate()) || isBlank(reservation.getTime())){ + throw new BadRequestReservationException(); + } + + String sql = "insert into reservation (name,date,time) values (?,?,?)"; + // Create keyHolder + KeyHolder keyHolder = new GeneratedKeyHolder(); + + jdbcTemplate.update( + connection -> { + PreparedStatement ps = connection.prepareStatement(sql,new String[]{"id"}); + ps.setString(1,reservation.getName()); + ps.setString(2,reservation.getDate()); + ps.setString(3,reservation.getTime()); + return ps; + }, + keyHolder + ); + // Generated id + Long id = keyHolder.getKey().longValue(); + + return ResponseEntity.created( + URI.create("/reservations/" + id) + ).build(); + } + + // Delete + @DeleteMapping("/reservations/{id}") + public ResponseEntity cancel_reservation(@PathVariable Long id){ + String sql = "delete from reservation where id = ?"; + int deleted = jdbcTemplate.update(sql,id); + + // handle exception + if (deleted == 0) { + throw new NotFoundReservationException(); + } + return ResponseEntity.noContent().build(); + } + + // Exception Handler + public class NotFoundReservationException extends RuntimeException {} + public class BadRequestReservationException extends RuntimeException {} + @ExceptionHandler({BadRequestReservationException.class, NotFoundReservationException.class}) + public ResponseEntity handleBadRequest(RuntimeException e){ + return ResponseEntity.badRequest().build(); + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e69de29bb..da7e2520a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -0,0 +1,6 @@ +# enable h2-console +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +# in-memory db named "database" +spring.datasource.url=jdbc:h2:mem:database \ No newline at end of file diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 000000000..8d9ab2754 --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,8 @@ +CREATE TABLE reservation +( + id BIGINT NOT NULL AUTO_INCREMENT, + name VARCHAR(255) NOT NULL, + date VARCHAR(255) NOT NULL, + time VARCHAR(255) NOT NULL, + PRIMARY KEY (id) +); diff --git a/src/test/java/roomescape/MissionStepTest.java b/src/test/java/roomescape/MissionStepTest.java index cf4efbe91..93baa69db 100644 --- a/src/test/java/roomescape/MissionStepTest.java +++ b/src/test/java/roomescape/MissionStepTest.java @@ -1,10 +1,22 @@ package roomescape; import io.restassured.RestAssured; +import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; +import java.sql.Connection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.springframework.jdbc.core.JdbcTemplate; +import java.sql.SQLException; +import static org.assertj.core.api.Assertions.assertThat; + +import static org.hamcrest.Matchers.is; + @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class MissionStepTest { @@ -16,4 +28,132 @@ public class MissionStepTest { .then().log().all() .statusCode(200); } + + @Test + void 이단계() { + RestAssured.given().log().all() + .when().get("/reservation") + .then().log().all() + .statusCode(200); + + RestAssured.given().log().all() + .when().get("/reservations") + .then().log().all() + .statusCode(200) + .body("size()", is(3)); + } + + @Test + void 삼단계() { + Map params = new HashMap<>(); + params.put("name", "브라운"); + params.put("date", "2023-08-05"); + params.put("time", "15:40"); + + RestAssured.given().log().all() + .contentType(ContentType.JSON) + .body(params) + .when().post("/reservations") + .then().log().all() + .statusCode(201) + .header("Location", "/reservations/1") + .body("id", is(1)); + + RestAssured.given().log().all() + .when().get("/reservations") + .then().log().all() + .statusCode(200) + .body("size()", is(1)); + + RestAssured.given().log().all() + .when().delete("/reservations/1") + .then().log().all() + .statusCode(204); + + RestAssured.given().log().all() + .when().get("/reservations") + .then().log().all() + .statusCode(200) + .body("size()", is(0)); + } + + @Test + void 사단계() { + Map params = new HashMap<>(); + params.put("name", "브라운"); + params.put("date", ""); + params.put("time", ""); + + // 필요한 인자가 없는 경우 + RestAssured.given().log().all() + .contentType(ContentType.JSON) + .body(params) + .when().post("/reservations") + .then().log().all() + .statusCode(400); + + // 삭제할 예약이 없는 경우 + RestAssured.given().log().all() + .when().delete("/reservations/1") + .then().log().all() + .statusCode(400); + } + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Test + void 오단계() { + try (Connection connection = jdbcTemplate.getDataSource().getConnection()) { + assertThat(connection).isNotNull(); + assertThat(connection.getCatalog()).isEqualTo("DATABASE"); + assertThat(connection.getMetaData().getTables(null, null, "RESERVATION", null).next()).isTrue(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Test + void 육단계() { + jdbcTemplate.update("INSERT INTO reservation (name, date, time) VALUES (?, ?, ?)", "브라운", "2023-08-05", "15:40"); + + List reservations = RestAssured.given().log().all() + .when().get("/reservations") + .then().log().all() + .statusCode(200).extract() + .jsonPath().getList(".", Reservation.class); + + Integer count = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class); + + assertThat(reservations.size()).isEqualTo(count); + } + + @Test + void 칠단계() { + Map params = new HashMap<>(); + params.put("name", "브라운"); + params.put("date", "2023-08-05"); + params.put("time", "10:00"); + + RestAssured.given().log().all() + .contentType(ContentType.JSON) + .body(params) + .when().post("/reservations") + .then().log().all() + .statusCode(201) + .header("Location", "/reservations/1"); + + Integer count = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class); + assertThat(count).isEqualTo(1); + + RestAssured.given().log().all() + .when().delete("/reservations/1") + .then().log().all() + .statusCode(204); + + Integer countAfterDelete = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class); + assertThat(countAfterDelete).isEqualTo(0); + } + + }