Skip to content

Gestion d'une bibliothèque et exceptions personnalisées.

Contexte

Vous allez créer un système de gestion de livres pour une bibliothèque et une hiérarchie d’exceptions personnalisées.

Chaque exception peut contenir l’objet fautif (ex. un Book) afin d’afficher ses propriétés dans le message et faciliter le débogage.

Objectifs pédagogiques

  • Concevoir des opérations CRUD et les tester sur deux stockages : mémoire et fichier.
  • Gérer les erreurs avec des exceptions métier explicites, contenant l’objet source.

Partie 1 — Entité Book

Créer la classe Book avec :

  • String id

  • String title

  • String author

  • int publicationYear

Exigences : 1. Constructeur complet + getters/setters. 2. Méthode boolean isValid() (id/titre/auteur non vides, année > 0). 3. Surcharger toString() pour que les messages d’erreur affichent des détails lisibles.


Partie 2 — Exceptions personnalisées (conservent l’objet en erreur)

Créer un package com.example.library.exceptions avec la hiérarchie suivante :

2.1 LibraryException (classe de base)

  • Champ Object sourceObject : l’objet fautif (ex. Book).
  • Accesseurs et surcharge de getMessage() pour concaténer une représentation lisible de l’objet.

Partie 3 — Implémentations

3.1 InMemoryBookRepository

  • Utilise HashMap<String, Book>.
  • Valide (ValidationException), teste les doublons (DuplicateBookException), et l’existence (BookNotFoundException).
  • Ne lève pas StorageException (pas d’E/S).
  • Inclure book dans l’exception lorsque pertinent.

3.2 FileBookRepository

  • Fichier books.txt au format id;title;author;year.
  • Toute erreur E/S est encapsulée en StorageException en passant l’objet pertinent si disponible (ex. le Book à écrire), sinon null.
  • Les CRUD relisent/écrivent le fichier.

Extraits clés :

try {
    // lecture/écriture fichier…
} catch (IOException | NumberFormatException e) {
    throw new StorageException("Lecture du fichier impossible: " + file, null, e);
}


Partie 4 — LibraryService

  • Dépend d’un BookRepository injecté au constructeur.
  • Propage les exceptions sans les masquer (les messages contiennent déjà l’objet fautif si fourni).
void addBook(Book book)
    throws DuplicateBookException, ValidationException, StorageException;
Book findBookById(String id)
    throws BookNotFoundException, StorageException;
List<Book> listAllBooks()
    throws StorageException;
void updateBookInfo(Book book)
    throws BookNotFoundException, ValidationException, StorageException;
void removeBook(String id)
    throws BookNotFoundException, StorageException;

Partie 5 — Tests (LibraryApp)

  • Tester : ajout, listing, recherche, mise à jour, suppression.
  • Provoquer des erreurs : doublon, id inexistant, validation, fichier manquant.
  • Afficher e.getMessage() : il doit inclure l’objet fautif lorsque pertinent grâce au toString() de Book.

Exemple :

try {
    service.addBook(new Book("1", "", "Auteur", 2024)); // titre vide
} catch (ValidationException e) {
    System.err.println(e.getMessage());
    // Exemple de sortie:
    // Erreur de validation : Le titre ne peut pas être vide | Objet concerné : Book{id='1', title='', author='Auteur', publicationYear=2024}
}


Diagramme UML (PlantUML)

N.B: Adapter de paquetage avec celui du cours i.e: org.calma.poo.laboratoireXYZ

Gestion d'une bibliothèque — Repository Pattern + Exceptions avec objet sourceGestion d'une bibliothèque — Repository Pattern + Exceptions avec objet sourcecomexamplelibrarymodelexceptionsreposerviceBook-id : String-title : String-author : String-publicationYear : int+Book(id:String, title:String, author:String, publicationYear:int)+getId() : String+getTitle() : String+getAuthor() : String+getPublicationYear() : int+setId(id:String) : void+setTitle(title:String) : void+setAuthor(author:String) : void+setPublicationYear(year:int) : void+isValid() : boolean+toString() : StringLibraryException-sourceObject : Object+LibraryException(msg:String)+LibraryException(msg:String, source:Object)+LibraryException(msg:String, source:Object, cause:Throwable)+getSourceObject() : Object+getMessage() : StringBookNotFoundExceptionDuplicateBookExceptionValidationExceptionStorageExceptionBookRepository+addBook(book:Book) : void+getBookById(id:String) : Book+getAllBooks() : java.util.List<Book>+updateBook(book:Book) : void+deleteBook(id:String) : voidInMemoryBookRepositoryFileBookRepository-filePath : java.nio.file.Path-readAll() : java.util.List<Book>-writeAll(books:java.util.List<Book>) : voidLibraryService-repo : BookRepository+LibraryService(repo:BookRepository)+addBook(book:Book) : void+findBookById(id:String) : Book+listAllBooks() : java.util.List<Book>+updateBookInfo(book:Book) : void+removeBook(id:String) : voidExceptions déclarées :- addBook : DuplicateBookException,ValidationException,StorageException- getBookById : BookNotFoundException,StorageException- getAllBooks : StorageException- updateBook : BookNotFoundException,ValidationException,StorageException- deleteBook : BookNotFoundException,StorageExceptionContient l'objet source (ex. Book) pour enrichir getMessage().Facilite la journalisation et le débogage.utilise
Gestion d'une bibliothèque — Repository Pattern + Exceptions avec objet sourceGestion d'une bibliothèque — Repository Pattern + Exceptions avec objet sourcecomexamplelibrarymodelexceptionsreposerviceBook-id : String-title : String-author : String-publicationYear : int+Book(id:String, title:String, author:String, publicationYear:int)+getId() : String+getTitle() : String+getAuthor() : String+getPublicationYear() : int+setId(id:String) : void+setTitle(title:String) : void+setAuthor(author:String) : void+setPublicationYear(year:int) : void+isValid() : boolean+toString() : StringLibraryException-sourceObject : Object+LibraryException(msg:String)+LibraryException(msg:String, source:Object)+LibraryException(msg:String, source:Object, cause:Throwable)+getSourceObject() : Object+getMessage() : StringBookNotFoundExceptionDuplicateBookExceptionValidationExceptionStorageExceptionBookRepository+addBook(book:Book) : void+getBookById(id:String) : Book+getAllBooks() : java.util.List<Book>+updateBook(book:Book) : void+deleteBook(id:String) : voidInMemoryBookRepositoryFileBookRepository-filePath : java.nio.file.Path-readAll() : java.util.List<Book>-writeAll(books:java.util.List<Book>) : voidLibraryService-repo : BookRepository+LibraryService(repo:BookRepository)+addBook(book:Book) : void+findBookById(id:String) : Book+listAllBooks() : java.util.List<Book>+updateBookInfo(book:Book) : void+removeBook(id:String) : voidExceptions déclarées :- addBook : DuplicateBookException,ValidationException,StorageException- getBookById : BookNotFoundException,StorageException- getAllBooks : StorageException- updateBook : BookNotFoundException,ValidationException,StorageException- deleteBook : BookNotFoundException,StorageExceptionContient l'objet source (ex. Book) pour enrichir getMessage().Facilite la journalisation et le débogage.utilise