Add library-management module: console app evolved into a Spring Boot 4 REST API
Stage 2 console classes and the shared LoanPolicy, then a Spring Boot 4.1.2 + JPA API (H2, @Version optimistic locking, problem+json errors). Tests write output/ transcripts while asserting the same numbers; scripts regenerate everything. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4DPL6dtpFg4U4LHc2
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import com.ankurm.library.api.Exceptions.*;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ProblemDetail;
|
||||
import org.springframework.orm.ObjectOptimisticLockingFailureException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** Turns exceptions into RFC 9457 problem+json bodies instead of stack traces. */
|
||||
@RestControllerAdvice
|
||||
class ApiExceptionHandler {
|
||||
|
||||
/** 400: names each bad field. Without this the 400 has an empty body in MockMvc. */
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
ProblemDetail invalid(MethodArgumentNotValidException e) {
|
||||
Map<String, String> errors = new TreeMap<>();
|
||||
e.getBindingResult().getFieldErrors().forEach(f -> errors.putIfAbsent(f.getField(), f.getDefaultMessage()));
|
||||
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "request body failed validation");
|
||||
problem.setProperty("errors", errors);
|
||||
return problem;
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
ProblemDetail notFound(NotFoundException e) {
|
||||
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
ProblemDetail conflict(ConflictException e) {
|
||||
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(RuleViolationException.class)
|
||||
ProblemDetail rule(RuleViolationException e) {
|
||||
return ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, e.getMessage());
|
||||
}
|
||||
|
||||
/** Two people changed the same Book row at once; the loser is told to retry. */
|
||||
@ExceptionHandler(ObjectOptimisticLockingFailureException.class)
|
||||
ProblemDetail raced(ObjectOptimisticLockingFailureException e) {
|
||||
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
|
||||
"someone else changed this book at the same moment, please retry");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
/**
|
||||
* A title in the catalogue with a count of copies. The {@code @Version} column is what stops two
|
||||
* people borrowing the last copy at the same moment: see BorrowRaceTest.
|
||||
*/
|
||||
@Entity
|
||||
public class Book {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String isbn;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String title;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String author;
|
||||
|
||||
private int totalCopies;
|
||||
private int availableCopies;
|
||||
|
||||
@Version
|
||||
private long version;
|
||||
|
||||
protected Book() {
|
||||
}
|
||||
|
||||
public Book(String isbn, String title, String author, int copies) {
|
||||
this.isbn = isbn;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.totalCopies = copies;
|
||||
this.availableCopies = copies;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public String getIsbn() { return isbn; }
|
||||
public String getTitle() { return title; }
|
||||
public String getAuthor() { return author; }
|
||||
public int getTotalCopies() { return totalCopies; }
|
||||
public int getAvailableCopies() { return availableCopies; }
|
||||
public long getVersion() { return version; }
|
||||
|
||||
void checkOut() { availableCopies--; }
|
||||
void checkIn() { availableCopies++; }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** Request and response shapes. Entities never leave the service layer. */
|
||||
public final class Dtos {
|
||||
|
||||
private Dtos() {
|
||||
}
|
||||
|
||||
public record BookRequest(@NotBlank String isbn, @NotBlank String title, @NotBlank String author,
|
||||
@Min(1) int copies) {
|
||||
}
|
||||
|
||||
public record BookView(Long id, String isbn, String title, String author, int totalCopies,
|
||||
int availableCopies) {
|
||||
static BookView of(Book b) {
|
||||
return new BookView(b.getId(), b.getIsbn(), b.getTitle(), b.getAuthor(), b.getTotalCopies(),
|
||||
b.getAvailableCopies());
|
||||
}
|
||||
}
|
||||
|
||||
public record MemberRequest(@NotBlank String name, @NotBlank @Email String email) {
|
||||
}
|
||||
|
||||
public record MemberView(Long id, String name, String email) {
|
||||
static MemberView of(Member m) {
|
||||
return new MemberView(m.getId(), m.getName(), m.getEmail());
|
||||
}
|
||||
}
|
||||
|
||||
public record BorrowRequest(@NotNull Long memberId, @NotNull Long bookId) {
|
||||
}
|
||||
|
||||
/** returnedOn is optional: omit it to return "today", supply it to back-date a return. */
|
||||
public record ReturnRequest(LocalDate returnedOn) {
|
||||
}
|
||||
|
||||
public record LoanView(Long id, String bookTitle, String memberName, LocalDate borrowedOn, LocalDate dueOn,
|
||||
LocalDate returnedOn, int fine) {
|
||||
static LoanView of(Loan l) {
|
||||
return new LoanView(l.getId(), l.getBook().getTitle(), l.getMember().getName(), l.getBorrowedOn(),
|
||||
l.getDueOn(), l.getReturnedOn(), l.getFine());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
/** Business-rule failures, each mapped to an HTTP status in ApiExceptionHandler. */
|
||||
public final class Exceptions {
|
||||
|
||||
private Exceptions() {
|
||||
}
|
||||
|
||||
/** 404: the thing the caller named does not exist. */
|
||||
public static class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 409: the request is fine, but the current state of the library says no. */
|
||||
public static class ConflictException extends RuntimeException {
|
||||
public ConflictException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 422: the member is not allowed to do this under the lending rules. */
|
||||
public static class RuleViolationException extends RuntimeException {
|
||||
public RuleViolationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
/** Stage 3 entry point: {@code mvn spring-boot:run} serves the REST API on port 8080. */
|
||||
@SpringBootApplication
|
||||
public class LibraryApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LibraryApplication.class, args);
|
||||
}
|
||||
|
||||
/** Injected rather than calling LocalDate.now() so tests can control "today". */
|
||||
@Bean
|
||||
Clock clock() {
|
||||
return Clock.systemDefaultZone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import com.ankurm.library.api.Dtos.*;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class LibraryController {
|
||||
|
||||
private final LoanService service;
|
||||
|
||||
LibraryController(LoanService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@PostMapping("/books")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
BookView addBook(@Valid @RequestBody BookRequest request) {
|
||||
return service.addBook(request);
|
||||
}
|
||||
|
||||
@GetMapping("/books")
|
||||
List<BookView> books() {
|
||||
return service.listBooks();
|
||||
}
|
||||
|
||||
@PostMapping("/members")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
MemberView addMember(@Valid @RequestBody MemberRequest request) {
|
||||
return service.addMember(request);
|
||||
}
|
||||
|
||||
@PostMapping("/loans")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
LoanView borrow(@Valid @RequestBody BorrowRequest request) {
|
||||
return service.borrow(request);
|
||||
}
|
||||
|
||||
@PostMapping("/loans/{id}/return")
|
||||
LoanView giveBack(@PathVariable Long id, @RequestBody(required = false) ReturnRequest request) {
|
||||
return service.giveBack(id, request == null ? null : request.returnedOn());
|
||||
}
|
||||
|
||||
@GetMapping("/loans")
|
||||
List<LoanView> loans() {
|
||||
return service.listLoans();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** One member borrowing one copy of one book. Both associations are LAZY on purpose. */
|
||||
@Entity
|
||||
public class Loan {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
private Book book;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
private Member member;
|
||||
|
||||
private LocalDate borrowedOn;
|
||||
private LocalDate dueOn;
|
||||
private LocalDate returnedOn;
|
||||
private int fine;
|
||||
|
||||
protected Loan() {
|
||||
}
|
||||
|
||||
public Loan(Book book, Member member, LocalDate borrowedOn, LocalDate dueOn) {
|
||||
this.book = book;
|
||||
this.member = member;
|
||||
this.borrowedOn = borrowedOn;
|
||||
this.dueOn = dueOn;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public Book getBook() { return book; }
|
||||
public Member getMember() { return member; }
|
||||
public LocalDate getBorrowedOn() { return borrowedOn; }
|
||||
public LocalDate getDueOn() { return dueOn; }
|
||||
public LocalDate getReturnedOn() { return returnedOn; }
|
||||
public int getFine() { return fine; }
|
||||
|
||||
void markReturned(LocalDate on, int fine) {
|
||||
this.returnedOn = on;
|
||||
this.fine = fine;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import com.ankurm.library.api.Dtos.*;
|
||||
import com.ankurm.library.api.Exceptions.*;
|
||||
import com.ankurm.library.core.LoanPolicy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/** The same four operations as the console Library, now on top of a database. */
|
||||
@Service
|
||||
public class LoanService {
|
||||
|
||||
private final BookRepository books;
|
||||
private final MemberRepository members;
|
||||
private final LoanRepository loans;
|
||||
private final Clock clock;
|
||||
|
||||
LoanService(BookRepository books, MemberRepository members, LoanRepository loans, Clock clock) {
|
||||
this.books = books;
|
||||
this.members = members;
|
||||
this.loans = loans;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookView addBook(BookRequest r) {
|
||||
if (books.existsByIsbn(r.isbn())) {
|
||||
throw new ConflictException("ISBN " + r.isbn() + " already exists");
|
||||
}
|
||||
return BookView.of(books.save(new Book(r.isbn(), r.title(), r.author(), r.copies())));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MemberView addMember(MemberRequest r) {
|
||||
if (members.existsByEmail(r.email())) {
|
||||
throw new ConflictException("email " + r.email() + " is already registered");
|
||||
}
|
||||
return MemberView.of(members.save(new Member(r.name(), r.email())));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookView> listBooks() {
|
||||
return books.findAll().stream().map(BookView::of).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LoanView borrow(BorrowRequest r) {
|
||||
Member member = members.findById(r.memberId())
|
||||
.orElseThrow(() -> new NotFoundException("no member with id " + r.memberId()));
|
||||
Book book = books.findById(r.bookId())
|
||||
.orElseThrow(() -> new NotFoundException("no book with id " + r.bookId()));
|
||||
if (book.getAvailableCopies() == 0) {
|
||||
throw new ConflictException("no copies of '" + book.getTitle() + "' are available");
|
||||
}
|
||||
if (loans.existsByMemberIdAndBookIdAndReturnedOnIsNull(member.getId(), book.getId())) {
|
||||
throw new RuleViolationException(member.getName() + " already has '" + book.getTitle() + "' on loan");
|
||||
}
|
||||
long active = loans.countByMemberIdAndReturnedOnIsNull(member.getId());
|
||||
if (!LoanPolicy.mayBorrow((int) active)) {
|
||||
throw new RuleViolationException(member.getName() + " already has " + active
|
||||
+ " active loans (max " + LoanPolicy.MAX_ACTIVE_LOANS + ")");
|
||||
}
|
||||
LocalDate today = LocalDate.now(clock);
|
||||
book.checkOut(); // dirty checking turns this into UPDATE book ... WHERE id=? AND version=?
|
||||
return LoanView.of(loans.save(new Loan(book, member, today, LoanPolicy.dueOn(today))));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LoanView giveBack(Long loanId, LocalDate returnedOn) {
|
||||
Loan loan = loans.findById(loanId).orElseThrow(() -> new NotFoundException("no loan with id " + loanId));
|
||||
if (loan.getReturnedOn() != null) {
|
||||
throw new ConflictException("loan " + loanId + " was already returned on " + loan.getReturnedOn());
|
||||
}
|
||||
LocalDate on = returnedOn != null ? returnedOn : LocalDate.now(clock);
|
||||
if (on.isBefore(loan.getBorrowedOn())) {
|
||||
throw new RuleViolationException("cannot return on " + on + ", before it was borrowed on "
|
||||
+ loan.getBorrowedOn());
|
||||
}
|
||||
loan.getBook().checkIn();
|
||||
loan.markReturned(on, LoanPolicy.fine(loan.getDueOn(), on));
|
||||
return LoanView.of(loan);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<LoanView> listLoans() {
|
||||
return loans.findAllWithDetails().stream().map(LoanView::of).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Member {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
|
||||
protected Member() {
|
||||
}
|
||||
|
||||
public Member(String name, String email) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public String getName() { return name; }
|
||||
public String getEmail() { return email; }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ankurm.library.api;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
interface BookRepository extends JpaRepository<Book, Long> {
|
||||
boolean existsByIsbn(String isbn);
|
||||
}
|
||||
|
||||
interface MemberRepository extends JpaRepository<Member, Long> {
|
||||
boolean existsByEmail(String email);
|
||||
}
|
||||
|
||||
interface LoanRepository extends JpaRepository<Loan, Long> {
|
||||
|
||||
long countByMemberIdAndReturnedOnIsNull(Long memberId);
|
||||
|
||||
boolean existsByMemberIdAndBookIdAndReturnedOnIsNull(Long memberId, Long bookId);
|
||||
|
||||
/** The innocent-looking version: loans only, book and member are lazy proxies. */
|
||||
List<Loan> findAllByOrderByIdAsc();
|
||||
|
||||
/** The same list in one SQL statement: JOIN FETCH pulls book and member in with each loan. */
|
||||
@Query("select l from Loan l join fetch l.book join fetch l.member order by l.id")
|
||||
List<Loan> findAllWithDetails();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.ankurm.library.console;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Stage 2 entry point. Reads one command per line from stdin, so a demo run is reproducible:
|
||||
* {@code java -cp target/classes com.ankurm.library.console.ConsoleApp < scripts/demo-input.txt}
|
||||
*
|
||||
* <pre>
|
||||
* add-book isbn|title|author|copies
|
||||
* add-member name
|
||||
* borrow isbn memberId [yyyy-mm-dd]
|
||||
* return loanId [yyyy-mm-dd]
|
||||
* report
|
||||
* quit
|
||||
* </pre>
|
||||
*/
|
||||
public class ConsoleApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Library library = new Library();
|
||||
Scanner in = new Scanner(System.in);
|
||||
while (in.hasNextLine()) {
|
||||
String line = in.nextLine().trim();
|
||||
if (line.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
System.out.println("> " + line);
|
||||
String[] cmd = line.split(" ", 2);
|
||||
String rest = cmd.length > 1 ? cmd[1] : "";
|
||||
try {
|
||||
switch (cmd[0]) {
|
||||
case "add-book" -> {
|
||||
String[] p = rest.split("\\|");
|
||||
System.out.println(library.addBook(p[0], p[1], p[2], Integer.parseInt(p[3])));
|
||||
}
|
||||
case "add-member" -> System.out.println(library.addMember(rest));
|
||||
case "borrow" -> {
|
||||
String[] p = rest.split(" ");
|
||||
System.out.println(library.borrow(p[0], Integer.parseInt(p[1]), dateOrToday(p, 2)));
|
||||
}
|
||||
case "return" -> {
|
||||
String[] p = rest.split(" ");
|
||||
System.out.println(library.giveBack(Integer.parseInt(p[0]), dateOrToday(p, 1)));
|
||||
}
|
||||
case "report" -> library.report().forEach(System.out::println);
|
||||
case "quit" -> {
|
||||
return;
|
||||
}
|
||||
default -> System.out.println("ERROR: unknown command '" + cmd[0] + "'");
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
System.out.println("ERROR: bad input (" + e.getClass().getSimpleName() + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate dateOrToday(String[] parts, int index) {
|
||||
return parts.length > index ? LocalDate.parse(parts[index]) : LocalDate.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.ankurm.library.console;
|
||||
|
||||
import com.ankurm.library.core.LoanPolicy;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Stage 2: the console app's domain, split out of the single-file version.
|
||||
* Everything lives in memory in plain collections; the rules come from {@link LoanPolicy}.
|
||||
*/
|
||||
public class Library {
|
||||
|
||||
public static class Book {
|
||||
final String isbn;
|
||||
final String title;
|
||||
final String author;
|
||||
int availableCopies;
|
||||
|
||||
Book(String isbn, String title, String author, int copies) {
|
||||
this.isbn = isbn;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.availableCopies = copies;
|
||||
}
|
||||
}
|
||||
|
||||
public record Member(int id, String name) {
|
||||
}
|
||||
|
||||
public static class Loan {
|
||||
final int id;
|
||||
final Book book;
|
||||
final Member member;
|
||||
final LocalDate borrowedOn;
|
||||
final LocalDate dueOn;
|
||||
LocalDate returnedOn;
|
||||
|
||||
Loan(int id, Book book, Member member, LocalDate borrowedOn) {
|
||||
this.id = id;
|
||||
this.book = book;
|
||||
this.member = member;
|
||||
this.borrowedOn = borrowedOn;
|
||||
this.dueOn = LoanPolicy.dueOn(borrowedOn);
|
||||
}
|
||||
|
||||
boolean active() {
|
||||
return returnedOn == null;
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<String, Book> books = new LinkedHashMap<>();
|
||||
private final Map<Integer, Member> members = new LinkedHashMap<>();
|
||||
private final List<Loan> loans = new ArrayList<>();
|
||||
|
||||
public String addBook(String isbn, String title, String author, int copies) {
|
||||
if (books.containsKey(isbn)) {
|
||||
return "ERROR: ISBN " + isbn + " already exists";
|
||||
}
|
||||
books.put(isbn, new Book(isbn, title, author, copies));
|
||||
return "Added book: " + title + " (" + copies + (copies == 1 ? " copy)" : " copies)");
|
||||
}
|
||||
|
||||
public String addMember(String name) {
|
||||
int id = members.size() + 1;
|
||||
members.put(id, new Member(id, name));
|
||||
return "Added member #" + id + ": " + name;
|
||||
}
|
||||
|
||||
public String borrow(String isbn, int memberId, LocalDate on) {
|
||||
Book book = books.get(isbn);
|
||||
Member member = members.get(memberId);
|
||||
if (book == null) {
|
||||
return "ERROR: no such book " + isbn;
|
||||
}
|
||||
if (member == null) {
|
||||
return "ERROR: no such member #" + memberId;
|
||||
}
|
||||
if (book.availableCopies == 0) {
|
||||
return "ERROR: no copies of '" + book.title + "' are available";
|
||||
}
|
||||
long active = loans.stream().filter(l -> l.active() && l.member.equals(member)).count();
|
||||
if (!LoanPolicy.mayBorrow((int) active)) {
|
||||
return "ERROR: " + member.name() + " already has " + active + " active loans (max "
|
||||
+ LoanPolicy.MAX_ACTIVE_LOANS + ")";
|
||||
}
|
||||
Loan loan = new Loan(loans.size() + 1, book, member, on);
|
||||
loans.add(loan);
|
||||
book.availableCopies--;
|
||||
return "Loan #" + loan.id + ": " + member.name() + " borrowed '" + book.title + "', due " + loan.dueOn;
|
||||
}
|
||||
|
||||
public String giveBack(int loanId, LocalDate on) {
|
||||
if (loanId < 1 || loanId > loans.size()) {
|
||||
return "ERROR: no such loan #" + loanId;
|
||||
}
|
||||
Loan loan = loans.get(loanId - 1);
|
||||
if (!loan.active()) {
|
||||
return "ERROR: loan #" + loanId + " was already returned on " + loan.returnedOn;
|
||||
}
|
||||
loan.returnedOn = on;
|
||||
loan.book.availableCopies++;
|
||||
int fine = LoanPolicy.fine(loan.dueOn, on);
|
||||
return "Loan #" + loanId + " returned on " + on + (fine > 0 ? ", fine Rs " + fine : ", no fine");
|
||||
}
|
||||
|
||||
public List<String> report() {
|
||||
List<String> lines = new ArrayList<>();
|
||||
books.values().forEach(b -> lines.add(" " + b.title + " by " + b.author + ": " + b.availableCopies
|
||||
+ " available"));
|
||||
loans.stream().filter(Loan::active).forEach(l -> lines.add(" ON LOAN #" + l.id + ": '" + l.book.title
|
||||
+ "' -> " + l.member.name() + ", due " + l.dueOn));
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ankurm.library.core;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
/**
|
||||
* The library's lending rules, as pure functions with no framework in sight.
|
||||
*
|
||||
* <p>This is the one class that survives the move from the console app to the Spring Boot API
|
||||
* completely unchanged. Both {@code console.Library} and {@code api.LoanService} call it.
|
||||
*/
|
||||
public final class LoanPolicy {
|
||||
|
||||
public static final int LOAN_DAYS = 14;
|
||||
public static final int MAX_ACTIVE_LOANS = 3;
|
||||
public static final int FINE_PER_DAY = 2; // rupees
|
||||
|
||||
private LoanPolicy() {
|
||||
}
|
||||
|
||||
public static LocalDate dueOn(LocalDate borrowedOn) {
|
||||
return borrowedOn.plusDays(LOAN_DAYS);
|
||||
}
|
||||
|
||||
/** Fine in rupees: zero on or before the due date, then FINE_PER_DAY for each day late. */
|
||||
public static int fine(LocalDate dueOn, LocalDate returnedOn) {
|
||||
long daysLate = ChronoUnit.DAYS.between(dueOn, returnedOn);
|
||||
return daysLate > 0 ? (int) daysLate * FINE_PER_DAY : 0;
|
||||
}
|
||||
|
||||
public static boolean mayBorrow(int activeLoans) {
|
||||
return activeLoans < MAX_ACTIVE_LOANS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
spring.application.name=library-management
|
||||
spring.datasource.url=jdbc:h2:mem:library;DB_CLOSE_DELAY=-1
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
||||
Reference in New Issue
Block a user