package exercice2; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; @Named( value = "listePersonnels" ) @ApplicationScoped public class PersonnelsService implements Serializable { public PersonnelsService() { personnels = new HashMap<>(); System.out.println( "TEST: Création PersonnelsService" ); } @PostConstruct public void init() { System.out.println( "TEST: PostConstruct PersonnelsService" ); for ( int i = 0; i < 20; i++ ) { personnels.put( i + 1, new Personnel( i + 1, "LeNom-" + ( i + 1 ), "LePrénom-" + ( i + 1 ) ) ); } } public Personnel findById( int id ) { return personnels.get( id ); } public List< Personnel > findAll() { List< Personnel > result = new ArrayList<>(); personnels.values().forEach( p -> { result.add( p ); } ); return result; } public void create( Personnel personnel ) throws Exception { Personnel p = personnels.get( personnel.getId() ); if ( p == null ) { int max = personnels.keySet().stream().max( Integer::compare ).get(); personnel.setId( max + 1 ); System.out.println( "Création personnel n° " + personnel.getId() ); personnels.put( personnel.getId(), personnel ); } else { throw new Exception( "Ajout impossible: Tentative de doublon sur la clé." ); } } public void update( Personnel personnel ) throws Exception { Personnel p = personnels.get( personnel.getId() ); if ( p!= null ) { personnels.put( personnel.getId(), personnel ); System.out.println( "Mise à jour du personnel n° " + personnel.getId() ); } else { throw new Exception( "Mise à jour impossible: clé non trouvée." ); } } public void remove( int id ) throws Exception { Personnel p = personnels.get( id ); if ( p != null ) { personnels.remove( id ); } else { throw new Exception("Suppression impossibe: clé non trouvée" ); } } private final Map< Integer, Personnel > personnels; }