Exemple16_BibliothequeRetourTélécharger Exemple d'une collection polymorphe dont la classe abstraite implémente aussi une interface Traitement des erreurs de decodage grâce aux exceptions. compil.bat mkdir bin del /f /s /q bin\*.class cd src javac -d ../bin -classpath "." *.java pause data Biblio.txt LIVRE;2012-02-0001;Livre de SF, appartenant au cycle de Trantor;Face aux feux du soleil;Isaac Asimov/IA;Robert Lafont;roman;0 LIVRE;2012-02-0011;revue d'astronomie;Ciel et espace;Alain Cirou/Redaction;AFAP;magazine;0 FILM;2012-02-0002;serie americaine;Friends Saison 1;;Comedie;;coffret FILM;2012-02-0003;;Les visiteurs 3;Jean-Marie Poire;Comedie;Jean Reno/Christian Clavier; JEU;2012-02-0004;Jeu de voiture;Karting III;PC;11 BiblioErreur.txt MUSIQUE;2012-02-0001;Livre de SF, appartenant au cycle de Trantor;Face aux feux du soleil;Isaac Asimov/IA;Robert Lafont;roman;0 LIVRE;2012-02-0011;revue d'astronomie;Ciel et espace;Alain Cirou/Redaction;AFAP;magazine;xx FILM;;serie americaine;Friends Saison 1;;Comedie;;coffret FILM;2012-02-0003;;Les visiteurs 3;Jean-Marie Poire;Comedie;Jean Reno/Christian Clavier; JEU;2012-02-0004;Jeu de voiture;Karting III;PC;yy run.bat cd bin java -classpath "." Exemple16 Biblio.txt pause runErreurDecodage.bat cd bin java -classpath "." Exemple16 BiblioErreur.txt pause runFichierInconnu.bat cd bin java -classpath "." Exemple16 Toto.txt pause runPasArgument.bat cd bin java -classpath "." Exemple16 pause src Exemple16.java //Exemple du cours sur l'heritage // import java.util.*; import fr.cnam.projet.*; // Programme principal // public class Exemple16 { public static void main(String... args) { try{ String nomFichier=null; try{ nomFichier = args[0]; }catch(Exception ex) { System.out.println("Pas de nom de fichier en entree"); System.exit(0); } Bibliotheque biblio = new Bibliotheque(nomFichier); // Une classe qui n'herite pas de la classe abstraite MultiMedia MediaPrete m = new MediaPrete("un livre de Oui-oui"); m.setDateEmprunt(avant(40)); biblio.ajouter(m); System.out.println("========================================="); System.out.println("TOUS LES MEDIAS ============\n"); System.out.println(biblio.getTousLesMedias()); System.out.println("========================================="); System.out.println("LE CATALOGUE ============\n"); System.out.println("------------ Les livres ------------"); System.out.println(biblio.getCatalogue("fr.cnam.projet.Livre")); System.out.println("------------ Les films ------------"); System.out.println(biblio.getCatalogue("fr.cnam.projet.Film")); System.out.println("------------ Les jeux ------------"); System.out.println(biblio.getCatalogue("fr.cnam.projet.Jeu")); System.out.println("========================================="); System.out.println("LES MEDIAS A RENDRE ============\n"); // Pour tester les emprunts biblio.get(0).setDateEmprunt(avant(80)); biblio.get(1).setDateEmprunt(avant(20)); biblio.get(2).setDateEmprunt(avant(40)); biblio.get(3).setDateEmprunt(avant(8)); biblio.get(4).setDateEmprunt(avant(20)); System.out.println(biblio.getMediaEmpruntDepasse()); System.out.println("========================================="); System.out.println("LES MEDIAS A RENDRE ============\n"); // Pour tester les emprunts biblio.get(0).setDateEmprunt(avant(10)); biblio.get(1).setDateEmprunt(avant(10)); biblio.get(2).setDateEmprunt(avant(10)); biblio.get(3).setDateEmprunt(avant(10)); biblio.get(4).setDateEmprunt(avant(10)); System.out.println(biblio.getMediaEmpruntDepasse()); }catch(Exception ex) { System.out.println("Exemple16 : " + ex.getMessage()); } } static Calendar avant(int jours) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.setTimeInMillis( System.currentTimeMillis()-(long)jours*86400000); return(cal); } } fr cnam projet Bibliotheque.java package fr.cnam.projet; import java.util.*; import fr.cnam.util.*; // Classe de gestion d'un bibliotheque de media // public class Bibliotheque { // La collection polymorphe de media private ArrayList<Media> elements; // Constructeur public Bibliotheque(String nomFichier) throws Exception { elements = new ArrayList<Media>(); initialiser(nomFichier); } // Ajouter un media a la collection public void ajouter(Media media) { elements.add(media); } // get element // public Media get(int i){return elements.get(i);} //nb element public int getNb(){return elements.size();} // Tous les medias (pour affichage) public String getTousLesMedias() { String res=""; for(Media m:elements) { res=res+"-----------------\n"; res=res+m.toString(); } return res; } // Tous les medias d'un type de media // public String getCatalogue(String typeMedia) { String res=""; for(Media m:elements) if (m.getClass().getName().equals(typeMedia)) res=res+m.formatCourt()+"\n"; return res; } // Les medias qui doivent etre rendus public String getMediaEmpruntDepasse() { String res=""; for(Media m:elements) { if ( m.getDateEmprunt() != null) { long d = m.getDateEmprunt().getTimeInMillis()/86400000; long now = System.currentTimeMillis()/86400000; if (now-d > m.getDureeEmprunt()) { res=res+m; res=res+"\n------------------\n"; } } } return res; } // Pour ne pas etre oblige de creer des lignes fastidieuses // dans le main pour creer des livres, films et jeux // on lit un fichier texte qui contient pour chaque ligne // un media // private void initialiser(String nomFichier) throws Exception { String[] lignes=null; try{ lignes = Terminal.lireFichierTexte("../data/"+nomFichier); }catch(Exception ex){ throw new Exception("Le fichier "+nomFichier+" n'existe pas dans data"); } String erreurDecodage =""; try{ int numeroLigne=1; for(String ligne : lignes) { String[] type = ligne.split("[;]"); if (type[0].equals("LIVRE")) { Livre l = new Livre(); try{ l.decoder(ligne); ajouter(l); }catch(Exception ex){ erreurDecodage+=numeroLigne + " : "+ex.getMessage()+"\n"; } } else if (type[0].equals("FILM")) { Film f = new Film(); try{ f.decoder(ligne); ajouter(f); }catch(Exception ex){ erreurDecodage+=numeroLigne + " : "+ex.getMessage()+"\n"; } } else if (type[0].equals("JEU")) { Jeu j = new Jeu(); try{ j.decoder(ligne); ajouter(j); }catch(Exception ex){ erreurDecodage+=numeroLigne + " : "+ex.getMessage()+"\n"; } } else { erreurDecodage+=numeroLigne + " : "+ "type inconnu : " +type[0]+"\n"; } numeroLigne++; }//for if (!erreurDecodage.equals("")) throw new Exception("initialiser:\n"+erreurDecodage); }catch(Exception ex) { throw new Exception("initialiser:\n"+ex); // Si erreur imprevue } } } Film.java package fr.cnam.projet; // La classe Film qui hérite de la classe MultiMedia // import java.util.*; public class Film extends MultiMedia { private String realisateur; private String[] acteurs; private String genre; private boolean coffret; //Constructeur par defaut public Film(){} // Le constructeur complet qui prend en entrée les attributs de la // classe Film mais aussi les attributs de la classe héritée // public Film(String ident,String description,String titre, String realisateur, String genre) { super(ident,description,titre); this.realisateur = realisateur; this.acteurs = new String[0]; this.genre = genre; this.coffret = false; } // Méthode qui retourne en chaine un livre et qui appelle // explicitement la méthode toString de la classe héritée // afin d'avoir les informations complètes du film et de ses // attributs hérités public String toString() { String a=""; for(String s:acteurs) a=a+String.format("%-15s : %s\n","acteur",s); return super.toString() + String.format("%-15s : %s\n","realisateur",realisateur)+ String.format("%-15s : %s\n","genre",genre)+ a + String.format("%-15s : %s\n","coffret",coffret+"") ; } // Duree de l'emprunt d'un film // public int getDureeEmprunt() { if (coffret) return 30; return 7; } // Format court d'un film // public String formatCourt() { return titre + " / " + genre; } // Decodage // public void decoder(String ligne) throws Exception { String[] champs = ligne.split("[;]",8); ident = champs[1]; if (ident.equals("")) throw new Exception("champ ident vide"); description = champs[2]; titre = champs[3]; realisateur = champs[4]; genre = champs[5]; acteurs = decoderActeurs(champs[6]); if (champs[7].equals("coffret")) coffret=true; else coffret=false; } private String[] decoderActeurs(String acteurs) { String[] champs = acteurs.split("[/]"); return champs; } } Jeu.java package fr.cnam.projet; // La classe Film qui hérite de la classe MultiMedia // import java.util.*; public class Jeu extends MultiMedia { private String console; // Type de console (PC,PS2,PS3, ...) private int ageSup; // Limite d'age du jeu // Constructeur par defaut public Jeu(){} // Le constructeur complet qui prend en entrée les attributs de la // classe Jeu mais aussi les attributs de la classe héritée // public Jeu(String ident,String description,String titre, String console, int ageSup) { super(ident,description,titre); this.console = console; this.ageSup = ageSup; } // Méthode qui retourne en chaine un livre et qui appelle // explicitement la méthode toString de la classe héritée // afin d'avoir les informations complètes du film et de ses // attributs hérités public String toString() { return super.toString() + String.format("%-15s : %s\n","console",console)+ String.format("%-15s : %s\n","ageSup",ageSup+""); } // Duree d'emprunt d'un jeu // public int getDureeEmprunt() { return 15; } // Format court d'un jeu // public String formatCourt() { return titre + " / " + console + " / " + ageSup +"ans"; } // Decodage // public void decoder(String ligne) throws Exception { String[] champs = ligne.split("[;]",6); ident = champs[1]; if (ident.equals("")) throw new Exception("champ ident vide"); description = champs[2]; titre = champs[3]; console = champs[4]; ageSup = Integer.parseInt(champs[5]); } } Livre.java package fr.cnam.projet; // La classe Livre qui hérite de la classe MultiMedia // public class Livre extends MultiMedia { private String[] auteurs; private String edition; private String genre; private int tome; // Constructeur par defaut public Livre(){} // Le constructeur complet qui prend en entrée les attributs de la // classe Livre mais aussi les attributs de la classe héritée // public Livre(String ident,String description,String titre, String[] auteurs, String edition, String genre, int tome) { super(ident,description,titre); this.auteurs = auteurs; this.edition = edition; this.genre = genre; this.tome = tome; } // Méthode qui retourne en chaine un livre et qui appelle // explicitement la méthode toString de la classe héritée // afin d'avoir les informations complètes du livre et de ses // attributs hérités public String toString() { String a=""; for(String s:auteurs) a=a+String.format("%-15s : %s\n","auteur",s); return super.toString() + a + String.format("%-15s : %s\n","edition",edition)+ String.format("%-15s : %s\n","genre",genre)+ String.format("%-15s : %s\n","tome",tome+""); } // Duree de l'emprunt d'un livre // public int getDureeEmprunt() { if (genre.equals("roman")) return 60; if (genre.equals("magazine")) return 15; return 30; } // Format court d'un livre // public String formatCourt() { return titre + " de " + auteurs[0]; } // Decodage // public void decoder(String ligne) throws Exception { String[] champs = ligne.split("[;]",8); ident = champs[1]; if (ident.equals("")) throw new Exception("champ ident vide"); description = champs[2]; titre = champs[3]; auteurs = decoderAuteurs(champs[4]); edition = champs[5]; genre = champs[6]; tome = Integer.parseInt(champs[7]); } private String[] decoderAuteurs(String auteurs) { String[] champs = auteurs.split("[/]"); return champs; } } Media.java package fr.cnam.projet; import java.util.*; public interface Media { public Calendar getDateEmprunt(); public void setDateEmprunt(Calendar d); public int getDureeEmprunt(); public String formatCourt(); public void decoder(String ligne) throws Exception; } MediaPrete.java package fr.cnam.projet; import java.util.*; public class MediaPrete implements Media { private String nom; private Calendar dateEmprunt; public MediaPrete(String nom) { this.nom=nom; } public String toString() { if ( this.dateEmprunt !=null) return nom+"\n"+dateEmprunt.getTime(); else return nom; } public Calendar getDateEmprunt(){return dateEmprunt;} public void setDateEmprunt(Calendar d){dateEmprunt=d;} public int getDureeEmprunt(){return 30;} public String formatCourt(){return nom;} public void decoder(String ligne){} // Pas dans le fichier de stock } MultiMedia.java package fr.cnam.projet; // La classe Media : class commune à tous les médias d'uen médiathèque // import java.util.*; abstract public class MultiMedia implements Media { protected String ident; // Identification unique d'un media protected String description; // Description générale du media protected String titre; // Le titre du media protected int dureeEmprunt; // Duree de l'emprunt en jour protected Calendar dateEmprunt; // date d'emprunt // Constructeur par defaut public MultiMedia(){} // Constructeur du media public MultiMedia(String ident,String description,String titre) { this.ident = ident; this.description = description; this.titre = titre; this.dureeEmprunt = 0; this.dateEmprunt = null; // Par defaut, pas d'emprunt } // Méthode qui retourne en chaine le media // public String toString() { String str = ""; str = str + String.format("%-15s : %s\n","ident",this.ident); str = str + String.format("%-15s : %s\n","description", this.description); str = str + String.format("%-15s : %s\n","titre", this.titre); str = str + String.format("%-15s : %s\n","duree emprunt", this.dureeEmprunt); if ( this.dateEmprunt !=null) str = str + String.format("%-15s : %s\n","date emprunt", this.dateEmprunt.getTime()); return str; } // Getteurs et Setteurs // public Calendar getDateEmprunt(){return dateEmprunt;} public void setDateEmprunt(Calendar d){dateEmprunt=d;} // Les methodes abstraites // // Duree de l'emprunt du media abstract public int getDureeEmprunt(); // Format court pour affichage sur 1 ligne du media abstract public String formatCourt(); // Le decodage d'un media (ligne texte) abstract public void decoder(String ligne) throws Exception; } util