diff --git a/src/main/java/org/springframework/samples/petclinic/records/RecordsTransferController.java b/src/main/java/org/springframework/samples/petclinic/records/RecordsTransferController.java index ab193cfdc..95d4b7b8f 100644 --- a/src/main/java/org/springframework/samples/petclinic/records/RecordsTransferController.java +++ b/src/main/java/org/springframework/samples/petclinic/records/RecordsTransferController.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.UUID; import javax.sql.DataSource; @@ -12,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; @Controller class RecordsTransferController { @@ -27,20 +27,33 @@ class RecordsTransferController { } @PostMapping("/records-transfers") - public NewRecordModel newRecordsTransfer(@RequestBody InputStream body) throws IOException, SQLException { + public NewRecordModel newRecordsTransfer(@RequestParam final String patientId, @RequestBody final InputStream body) + throws IOException, SQLException { + validatePatientId(patientId); final var id = saveToRecordsSystem(body); return new NewRecordModel(id); } - private String saveToRecordsSystem(final InputStream is) throws IOException, SQLException { + /** + * @param patientId id of the patient + * @throws SQLException when there is a problem with the database + * @throws IllegalArgumentException when the patient does not exist + */ + private void validatePatientId(final String patientId) throws SQLException { + final var connection = dataSource.getConnection(); + final var statement = connection.prepareStatement("SELECT * FROM patients WHERE id = ?"); + statement.setString(1, patientId); + final var rs = statement.executeQuery(); + if (!rs.next()) { + throw new IllegalArgumentException("Patient with id " + patientId + " does not exist"); + } + } + + private String saveToRecordsSystem(final InputStream is) throws IOException { final var id = UUID.randomUUID().toString(); final var path = recordsDir.resolve("record-" + id + ".json"); Files.copy(is, path); - final var connection = dataSource.getConnection(); - final PreparedStatement statement = connection.prepareStatement("INSERT INTO records (path) VALUES ?"); - statement.setString(1, path.toString()); - statement.executeUpdate(); - return id; + return path.toString(); } }