diff --git a/.classpath b/.classpath new file mode 100755 index 0000000..60b915a --- /dev/null +++ b/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.project b/.project new file mode 100755 index 0000000..3387902 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + Forum_TD1&2 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100755 index 0000000..08c4bff --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=11 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=11 diff --git a/bin/forum/Administrateur.class b/bin/forum/Administrateur.class new file mode 100755 index 0000000..04a3d81 Binary files /dev/null and b/bin/forum/Administrateur.class differ diff --git a/bin/forum/Canal.class b/bin/forum/Canal.class new file mode 100755 index 0000000..c225a75 Binary files /dev/null and b/bin/forum/Canal.class differ diff --git a/bin/forum/CanalDeBreve.class b/bin/forum/CanalDeBreve.class new file mode 100755 index 0000000..de00946 Binary files /dev/null and b/bin/forum/CanalDeBreve.class differ diff --git a/bin/forum/CanalParDefaut.class b/bin/forum/CanalParDefaut.class new file mode 100755 index 0000000..701abee Binary files /dev/null and b/bin/forum/CanalParDefaut.class differ diff --git a/bin/forum/Controleur.class b/bin/forum/Controleur.class new file mode 100755 index 0000000..81eb317 Binary files /dev/null and b/bin/forum/Controleur.class differ diff --git a/bin/forum/Forum.class b/bin/forum/Forum.class new file mode 100755 index 0000000..1fed953 Binary files /dev/null and b/bin/forum/Forum.class differ diff --git a/bin/forum/GestionnaireCanal.class b/bin/forum/GestionnaireCanal.class new file mode 100755 index 0000000..d93b1d6 Binary files /dev/null and b/bin/forum/GestionnaireCanal.class differ diff --git a/bin/forum/GestionnaireForum.class b/bin/forum/GestionnaireForum.class new file mode 100755 index 0000000..b5de301 Binary files /dev/null and b/bin/forum/GestionnaireForum.class differ diff --git a/bin/forum/Memoire.class b/bin/forum/Memoire.class new file mode 100755 index 0000000..7c3e718 Binary files /dev/null and b/bin/forum/Memoire.class differ diff --git a/bin/forum/Message.class b/bin/forum/Message.class new file mode 100755 index 0000000..4a4a717 Binary files /dev/null and b/bin/forum/Message.class differ diff --git a/bin/forum/Producteur.class b/bin/forum/Producteur.class new file mode 100755 index 0000000..7602ebf Binary files /dev/null and b/bin/forum/Producteur.class differ diff --git a/bin/forum/UserConsole.class b/bin/forum/UserConsole.class new file mode 100755 index 0000000..c414845 Binary files /dev/null and b/bin/forum/UserConsole.class differ diff --git a/bin/openClosedPrinciples/core/AlreadyBooked.class b/bin/openClosedPrinciples/core/AlreadyBooked.class new file mode 100644 index 0000000..4160e36 Binary files /dev/null and b/bin/openClosedPrinciples/core/AlreadyBooked.class differ diff --git a/bin/openClosedPrinciples/core/AucunItemCorrespondant.class b/bin/openClosedPrinciples/core/AucunItemCorrespondant.class new file mode 100644 index 0000000..9bf3c8a Binary files /dev/null and b/bin/openClosedPrinciples/core/AucunItemCorrespondant.class differ diff --git a/bin/openClosedPrinciples/core/Car.class b/bin/openClosedPrinciples/core/Car.class new file mode 100644 index 0000000..1ea8282 Binary files /dev/null and b/bin/openClosedPrinciples/core/Car.class differ diff --git a/bin/openClosedPrinciples/core/CarRental.class b/bin/openClosedPrinciples/core/CarRental.class new file mode 100644 index 0000000..8d5442f Binary files /dev/null and b/bin/openClosedPrinciples/core/CarRental.class differ diff --git a/bin/openClosedPrinciples/core/CarRentalService.class b/bin/openClosedPrinciples/core/CarRentalService.class new file mode 100644 index 0000000..f331bef Binary files /dev/null and b/bin/openClosedPrinciples/core/CarRentalService.class differ diff --git a/bin/openClosedPrinciples/core/CarRentalServiceTest.class b/bin/openClosedPrinciples/core/CarRentalServiceTest.class new file mode 100644 index 0000000..0681fae Binary files /dev/null and b/bin/openClosedPrinciples/core/CarRentalServiceTest.class differ diff --git a/bin/openClosedPrinciples/core/CarRentalTest.class b/bin/openClosedPrinciples/core/CarRentalTest.class new file mode 100644 index 0000000..f03eb5e Binary files /dev/null and b/bin/openClosedPrinciples/core/CarRentalTest.class differ diff --git a/bin/openClosedPrinciples/core/DateTools.class b/bin/openClosedPrinciples/core/DateTools.class new file mode 100644 index 0000000..c8bad04 Binary files /dev/null and b/bin/openClosedPrinciples/core/DateTools.class differ diff --git a/bin/openClosedPrinciples/core/Description.class b/bin/openClosedPrinciples/core/Description.class new file mode 100644 index 0000000..9f2078d Binary files /dev/null and b/bin/openClosedPrinciples/core/Description.class differ diff --git a/bin/openClosedPrinciples/core/Flight.class b/bin/openClosedPrinciples/core/Flight.class new file mode 100644 index 0000000..fbb02f7 Binary files /dev/null and b/bin/openClosedPrinciples/core/Flight.class differ diff --git a/bin/openClosedPrinciples/core/FlightService.class b/bin/openClosedPrinciples/core/FlightService.class new file mode 100644 index 0000000..352526e Binary files /dev/null and b/bin/openClosedPrinciples/core/FlightService.class differ diff --git a/bin/openClosedPrinciples/core/FlightServiceTest.class b/bin/openClosedPrinciples/core/FlightServiceTest.class new file mode 100644 index 0000000..8e8fc34 Binary files /dev/null and b/bin/openClosedPrinciples/core/FlightServiceTest.class differ diff --git a/bin/openClosedPrinciples/core/FlightTest.class b/bin/openClosedPrinciples/core/FlightTest.class new file mode 100644 index 0000000..768b341 Binary files /dev/null and b/bin/openClosedPrinciples/core/FlightTest.class differ diff --git a/bin/openClosedPrinciples/core/GestionnaireVoyages.class b/bin/openClosedPrinciples/core/GestionnaireVoyages.class new file mode 100644 index 0000000..f038aff Binary files /dev/null and b/bin/openClosedPrinciples/core/GestionnaireVoyages.class differ diff --git a/bin/openClosedPrinciples/core/NotPossibleCarRentalException.class b/bin/openClosedPrinciples/core/NotPossibleCarRentalException.class new file mode 100644 index 0000000..acfad9e Binary files /dev/null and b/bin/openClosedPrinciples/core/NotPossibleCarRentalException.class differ diff --git a/bin/openClosedPrinciples/core/PayingItem.class b/bin/openClosedPrinciples/core/PayingItem.class new file mode 100644 index 0000000..d899994 Binary files /dev/null and b/bin/openClosedPrinciples/core/PayingItem.class differ diff --git a/bin/openClosedPrinciples/core/Service.class b/bin/openClosedPrinciples/core/Service.class new file mode 100644 index 0000000..0e03490 Binary files /dev/null and b/bin/openClosedPrinciples/core/Service.class differ diff --git a/bin/openClosedPrinciples/core/TravelOrganizer.class b/bin/openClosedPrinciples/core/TravelOrganizer.class new file mode 100644 index 0000000..2c33083 Binary files /dev/null and b/bin/openClosedPrinciples/core/TravelOrganizer.class differ diff --git a/bin/openClosedPrinciples/core/Trip.class b/bin/openClosedPrinciples/core/Trip.class new file mode 100644 index 0000000..e251365 Binary files /dev/null and b/bin/openClosedPrinciples/core/Trip.class differ diff --git a/bin/td5/p1/Launch.class b/bin/td5/p1/Launch.class new file mode 100644 index 0000000..1fde4c3 Binary files /dev/null and b/bin/td5/p1/Launch.class differ diff --git a/bin/td5/p1/ModernWeaponFactory.class b/bin/td5/p1/ModernWeaponFactory.class new file mode 100644 index 0000000..7237a49 Binary files /dev/null and b/bin/td5/p1/ModernWeaponFactory.class differ diff --git a/bin/td5/p1/WeaponFactory.class b/bin/td5/p1/WeaponFactory.class new file mode 100644 index 0000000..d25744c Binary files /dev/null and b/bin/td5/p1/WeaponFactory.class differ diff --git a/bin/td5/p1/arme/Arme.class b/bin/td5/p1/arme/Arme.class new file mode 100644 index 0000000..38b457e Binary files /dev/null and b/bin/td5/p1/arme/Arme.class differ diff --git a/bin/td5/p1/arme/Bouclier.class b/bin/td5/p1/arme/Bouclier.class new file mode 100644 index 0000000..c0fabd7 Binary files /dev/null and b/bin/td5/p1/arme/Bouclier.class differ diff --git a/bin/td5/p1/arme/Dague.class b/bin/td5/p1/arme/Dague.class new file mode 100644 index 0000000..db3b43c Binary files /dev/null and b/bin/td5/p1/arme/Dague.class differ diff --git a/bin/td5/p1/arme/Epée.class b/bin/td5/p1/arme/Epée.class new file mode 100644 index 0000000..a7d8b34 Binary files /dev/null and b/bin/td5/p1/arme/Epée.class differ diff --git a/bin/td5/p1/arme/Fusil.class b/bin/td5/p1/arme/Fusil.class new file mode 100644 index 0000000..b0a55e5 Binary files /dev/null and b/bin/td5/p1/arme/Fusil.class differ diff --git a/bin/td5/p1/etat/Faible.class b/bin/td5/p1/etat/Faible.class new file mode 100644 index 0000000..d27777d Binary files /dev/null and b/bin/td5/p1/etat/Faible.class differ diff --git a/bin/td5/p1/etat/Mort.class b/bin/td5/p1/etat/Mort.class new file mode 100644 index 0000000..401ee99 Binary files /dev/null and b/bin/td5/p1/etat/Mort.class differ diff --git a/bin/td5/p1/etat/PlayerState.class b/bin/td5/p1/etat/PlayerState.class new file mode 100644 index 0000000..8f68878 Binary files /dev/null and b/bin/td5/p1/etat/PlayerState.class differ diff --git a/bin/td5/p1/etat/Vivant.class b/bin/td5/p1/etat/Vivant.class new file mode 100644 index 0000000..16b0a6e Binary files /dev/null and b/bin/td5/p1/etat/Vivant.class differ diff --git a/bin/td5/p1/personnage/Humain.class b/bin/td5/p1/personnage/Humain.class new file mode 100644 index 0000000..3ca4023 Binary files /dev/null and b/bin/td5/p1/personnage/Humain.class differ diff --git a/bin/td5/p1/personnage/Orc.class b/bin/td5/p1/personnage/Orc.class new file mode 100644 index 0000000..0a536ee Binary files /dev/null and b/bin/td5/p1/personnage/Orc.class differ diff --git a/bin/td5/p1/personnage/Personnage.class b/bin/td5/p1/personnage/Personnage.class new file mode 100644 index 0000000..bd0e9dd Binary files /dev/null and b/bin/td5/p1/personnage/Personnage.class differ diff --git a/bin/td5/p1/personnage/Tauren.class b/bin/td5/p1/personnage/Tauren.class new file mode 100644 index 0000000..a84f184 Binary files /dev/null and b/bin/td5/p1/personnage/Tauren.class differ diff --git a/bin/td5/p1/personnage/Troll.class b/bin/td5/p1/personnage/Troll.class new file mode 100644 index 0000000..164fec8 Binary files /dev/null and b/bin/td5/p1/personnage/Troll.class differ diff --git a/bin/td5/p1/td5p1.png b/bin/td5/p1/td5p1.png new file mode 100644 index 0000000..b863fc4 Binary files /dev/null and b/bin/td5/p1/td5p1.png differ diff --git a/bin/td5/p1/testArmes.class b/bin/td5/p1/testArmes.class new file mode 100644 index 0000000..f628596 Binary files /dev/null and b/bin/td5/p1/testArmes.class differ diff --git a/src/Diagramme_de_classe_forum.ucls b/src/Diagramme_de_classe_forum.ucls new file mode 100755 index 0000000..395f71b --- /dev/null +++ b/src/Diagramme_de_classe_forum.ucls @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/designPattern/facebookGhost/Event.java b/src/designPattern/facebookGhost/Event.java new file mode 100644 index 0000000..9d8e17d --- /dev/null +++ b/src/designPattern/facebookGhost/Event.java @@ -0,0 +1,5 @@ +package designPattern.facebookGhost; + +public interface Event { + +} diff --git a/src/designPattern/facebookGhost/FacebookGhostNetwork.java b/src/designPattern/facebookGhost/FacebookGhostNetwork.java new file mode 100644 index 0000000..eea1e33 --- /dev/null +++ b/src/designPattern/facebookGhost/FacebookGhostNetwork.java @@ -0,0 +1,125 @@ +package designPattern.facebookGhost; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Observable; + + +/** + * + * Inspired by + * //https://github.com/roundrop/facebook4j/blob/master/facebook4j-core/src/main/java/facebook4j/api/FriendMethods.java + * pour imaginer une esquisse de rseau tr�s tr�s simplifi� + * @author blay + * + */ +@SuppressWarnings("deprecation") +public class FacebookGhostNetwork extends Observable { + + public static final String DEFAULT_LOCATION = "unspecified"; + HashMap users = new HashMap<> (); + + public FacebookGhostNetwork() { + } + + + public User addUser(String nom, String profile){ + return addUser(nom, profile,DEFAULT_LOCATION); + } + + public User addUser(String nom, String profile, String location){ + User user = new UserImpl(nom, profile,location); + users.put(nom, user); + Event e = new UserEvent(user); + setChanged(); + notifyObservers(e); + return user; + } + + /** + * Returns a user's friends. + * @param userId the ID of a user + * @return users + * @see User#friends - Facebook Developers + */ + ArrayList getFriends(String userId){ + return getUser(userId).getFriends(); + } + + + /** + * Returns a user's family members. + * @param userId the ID of a user + * @return users + * @see User#friends - Facebook Developers + */ + ArrayList getFamily(String userId){ + return getUser(userId).getFamily(); + } + + + + /** + * Returns a given user, specified by ID. + * @param userId the ID of the user + * @return user + * remove but not the use of dedicated exception !! @throws FacebookException when Facebook service or network is unavailable + * @see User - Facebook Developers + */ + public User getUser(String userId) { + return users.get(userId); + } + + + /** + * Create a relation between 2 given members of a same family + * @param id1 the ID of the user + * @param id2 the ID of the user + */ + public void addFamilyRelation(String id1, String id2) { + User u1 = users.get(id1); + User u2 = users.get(id2); + addFamilyRelation(u1, u2); + + } + + + public void addFamilyRelation(User u1, User u2) { + u1.addFamily(u2); + u2.addFamily(u1); + Event e = new RelationEvent("family",u1,u2); + setChanged(); + notifyObservers(e); + + } + + + + /** + * Create a relation between 2 given friends + * @param id1 the ID of the user + * @param id2 the ID of the user + */ + public void addFriendRelation(String id1, String id2) { + User u1 = users.get(id1); + User u2 = users.get(id2); + addFriendRelation(u1, u2); + } + + public void addFriendRelation(User u1, User u2) { + u1.addFriend(u2); + u2.addFriend(u1); + Event e = new RelationEvent("Friend",u1,u2); + setChanged(); + notifyObservers(e); + + } + @Override + public String toString() { + return "FacebookGhostNetwork [ " + users + "]"; + } + + + + +} diff --git a/src/designPattern/facebookGhost/IdNameEntity.java b/src/designPattern/facebookGhost/IdNameEntity.java new file mode 100644 index 0000000..71b77e0 --- /dev/null +++ b/src/designPattern/facebookGhost/IdNameEntity.java @@ -0,0 +1,6 @@ +package designPattern.facebookGhost; + +public interface IdNameEntity { + String getId(); + String getName(); +} diff --git a/src/designPattern/facebookGhost/IdNameEntityImpl.java b/src/designPattern/facebookGhost/IdNameEntityImpl.java new file mode 100644 index 0000000..62eaab6 --- /dev/null +++ b/src/designPattern/facebookGhost/IdNameEntityImpl.java @@ -0,0 +1,25 @@ +package designPattern.facebookGhost; + +public class IdNameEntityImpl implements IdNameEntity { + + private String id; + private String name; + + @Override + public String getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + public IdNameEntityImpl(String id, String name) { + super(); + this.id = id; + this.name = name; + } + + +} diff --git a/src/designPattern/facebookGhost/RelationEvent.java b/src/designPattern/facebookGhost/RelationEvent.java new file mode 100644 index 0000000..27307f2 --- /dev/null +++ b/src/designPattern/facebookGhost/RelationEvent.java @@ -0,0 +1,32 @@ +package designPattern.facebookGhost; + +public class RelationEvent implements Event { + public String getNature() { + return nature; + } + + public User getU1() { + return u1; + } + + public User getU2() { + return u2; + } + + String nature; + User u1; + User u2; + + public RelationEvent(String nature, User u1, User u2) { + this.nature = nature; + this.u1 = u1; + this.u2=u2; + } + + @Override + public String toString() { + return "RelationEvent [nature=" + nature + ", u1=" + u1 + ", u2=" + u2 + + "]"; + } + +} diff --git a/src/designPattern/facebookGhost/User.java b/src/designPattern/facebookGhost/User.java new file mode 100644 index 0000000..39b97c6 --- /dev/null +++ b/src/designPattern/facebookGhost/User.java @@ -0,0 +1,104 @@ +package designPattern.facebookGhost; + +/*import java.net.URL; + +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Set;*/ + +import java.util.ArrayList; + +/** + * Emprunt� � https://github.com/roundrop/facebook4j + * @author Ryuji Yamashita - roundrop at gmail.com + */ +public interface User { + + String myProfil(); + String getId(); + String getName(); + /* String getFirstName(); + String getMiddleName(); + String getLastName(); + String getGender(); + Locale getLocale(); + List getLanguages(); + URL getLink(); + String getUsername(); + String getThirdPartyId(); + Boolean isInstalled(); + Double getTimezone(); + Date getUpdatedTime(); + Boolean isVerified(); + String getBio(); + String getBirthday(); +// Cover getCover(); + List getEducation(); + String getEmail(); + */ + IdNameEntity getHometown(); + /* + List getInterestedIn(); + IdNameEntity getLocation(); + String getPolitical(); + List getFavoriteAthletes(); + List getFavoriteTeams(); +// Picture getPicture(); + String getQuotes(); + String getRelationshipStatus(); + String getReligion(); + IdNameEntity getSignificantOther(); + User.VideoUploadLimits getVideoUploadLimits(); + URL getWebsite(); + List getWork(); +; + + interface Education { + IdNameEntity getYear(); + String getType(); + IdNameEntity getSchool(); + IdNameEntity getDegree(); + List getConcentration(); + List getClasses(); + List getWith(); + } + + interface EducationClass { + List getWith(); + String getDescription(); + } + + interface VideoUploadLimits { + long getLength(); + long getSize(); + } + + interface Work { + IdNameEntity getEmployer(); + IdNameEntity getLocation(); + IdNameEntity getPosition(); + String getStartDate(); + String getEndDate(); + + }*/ + + User.AgeRange getAgeRange(); + interface AgeRange { + // one value could be null (13-17 / 18-20 / 21 - null) + Integer getMin(); + Integer getMax(); + int getAge(); + } + ArrayList getFriends(); + void addFriend(User friend); + void addFamily(User familyMember); + ArrayList getFamily(); + + void setLocation(String name); + //String BIRTHDAY_DATE_FORMAT = "MM/dd/yyyy"; + + + + +} \ No newline at end of file diff --git a/src/designPattern/facebookGhost/UserEvent.java b/src/designPattern/facebookGhost/UserEvent.java new file mode 100644 index 0000000..424f8ff --- /dev/null +++ b/src/designPattern/facebookGhost/UserEvent.java @@ -0,0 +1,11 @@ +package designPattern.facebookGhost; + +public class UserEvent implements Event { + + User user; + + public UserEvent(User user) { + this.user = user; + } + +} diff --git a/src/designPattern/facebookGhost/UserImpl.java b/src/designPattern/facebookGhost/UserImpl.java new file mode 100644 index 0000000..db222c6 --- /dev/null +++ b/src/designPattern/facebookGhost/UserImpl.java @@ -0,0 +1,105 @@ +package designPattern.facebookGhost; + +import java.util.ArrayList; + + +public class UserImpl implements User { + + + private String id; + private String myProfile; + private User.AgeRange range; + private IdNameEntity homeTown; + + + class AgeRangeImpl implements User.AgeRange{ + + int age = 20; + public Integer getMin() { + return 0; + } + + public Integer getMax() { + return 120; + } + + public int getAge() { + return age; + } + + } + + + public UserImpl(String id, String profile, String phomeTown) { + this.id = id; + myProfile = profile; + range = new AgeRangeImpl(); + homeTown = new IdNameEntityImpl(phomeTown,phomeTown); + } + + + public UserImpl(String id, String profile) { + this.id = id; + myProfile = profile; + range = new AgeRangeImpl(); + } + + public String myProfil() { + return myProfile; + } + + public String getId() { + return id; + } + + public String getName() { + return id; + } + + public AgeRange getAgeRange() { + return range; + } + + + + private ArrayList friends = new ArrayList (); + + public void addFriend(User friend) { + friends.add(friend); + } + + public ArrayList getFriends() { + return friends; + } + + private ArrayList family = new ArrayList (); + + public void addFamily(User familyMember) { + family.add(familyMember); + } + + public ArrayList getFamily(){ + return family; + } + + @Override + public String toString() { + return "UserImpl [id=" + id + ", myProfile=" + myProfile + ", range=" + + range + + //",friends=" + friends + ", family=" + family + + "]"; + } + + @Override + public IdNameEntity getHometown() { + return homeTown; + } + + + @Override + public void setLocation(String name) { + homeTown = new IdNameEntityImpl(name,name) ; + } + + +} diff --git a/src/designPattern/grapheSimple/Chemin.java b/src/designPattern/grapheSimple/Chemin.java new file mode 100644 index 0000000..527f79a --- /dev/null +++ b/src/designPattern/grapheSimple/Chemin.java @@ -0,0 +1,192 @@ +package designPattern.grapheSimple; + +import designPattern.grapheX.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * La classe Chemin définit un chemin comme un ensemble d'arcs et maintient pour + * chaque chemin la somme des valeurs des arcs + * + * @author blay + * @param + * + */ +public class Chemin implements Comparable> { + + // On pourrait éviter cet attribut en calculant la distance à la demande. + int distance = 0; + + List> paths = new ArrayList<>(); + + public Chemin() { + paths = new ArrayList<>(); + } + + public Chemin(List> arcs) { + paths = arcs; + } + + /** + * @return le Sommet terminant le chemin si le chemin est vide il vaut null + */ + public S arrivee() { + if (paths.isEmpty()) + return null; + Arc arc = paths.get(paths.size() - 1); + return arc.destination(); + } + + /** + * @return la somme des valeurs des arcs + */ + public int distance() { + return distance; + } + + /** + * @return la liste des arcs qui composent le chemin Attention dangereux une + * copie serait préférable + */ + public List> getArcs() { + return paths; + } + + /** + * Ajoute un arc � la fin du chemin + * + * @TODO : verifier que le dernier noeud est bien le premier noeud de l'arc + * ajoute + */ + public boolean add(Arc e) { + distance += e.valeur(); + return paths.add(e); + } + + public void add(int x, Arc e) { + distance += e.valeur(); + paths.add(x, e); + } + + public boolean addAll(Collection> c) { + for (Arc a : c) + distance += a.valeur(); + return paths.addAll(c); + } + + public void clear() { + distance = 0; + paths.clear(); + + } + + /** + * verifie l'appartenance d'un arc au chemin + * + * @param arc + * @return vrai si l'arc appartient au chemin + */ + public boolean contains(Arc arc) { + return paths.contains(arc); + } + + public boolean isEmpty() { + return paths.isEmpty(); + } + + public boolean remove(Arc o) { + return paths.remove(o); + } + + public boolean removeAll(Collection> c) { + return paths.removeAll(c); + } + + public int size() { + return paths.size(); + } + + @Override + public String toString() { + return "Chemin [dist.=" + distance + ", paths=" + paths + "]"; + } + + /** + * d�termine si le sommet appartient au chemin + * + * @param sommet + * @return vrai si le sommet appartient au chemin + */ + public boolean atteint(S sommet) { + for (Arc a : paths) + if (a.destination().equals(sommet)) + return true; + return false; + } + + /** + * @param depart + * @param arrivee + * @return le sous-chemin reliant depart et arrivee si les deux noeuds + * appartiennent au chemin. + * + */ + public Chemin extraireChemin(S depart, S arrivee) { + boolean debutee = false; + Chemin c = new Chemin<>(); + for (Arc a : paths) { + if (debutee) { + c.add(a); + } + if (a.origine().equals(depart)) { + c.add(a); + debutee = true; + } + if (debutee && a.destination().equals(arrivee)) + return c; + } + return c; + + } + + public int compareTo(Chemin c) { + if (this.distance() < c.distance()) + return -1; + else if (this.distance() == c.distance()) + return 0; + else + return 1; + + } + + public boolean equals(Object o) { + if (!(o instanceof Chemin)) + return false; + + Chemin o2 = (Chemin) o; + Chemin c = o2; + if ((distance == c.distance) && (c.paths.size() == this.paths.size())) { + for (Arc a : c.paths) { + if (!paths.contains(a)) { + return false; + } + } + return true; + } else + return false; + + } + + public List sommets() { + List sommets = new ArrayList<>(); + if (! paths.isEmpty()) { + for (Arc arc : paths) + sommets.add(arc.origine()); + sommets.add(paths.get(paths.size() - 1).destination()); + } + return sommets; + } + +} diff --git a/src/designPattern/grapheSimple/GrapheSimple.java b/src/designPattern/grapheSimple/GrapheSimple.java new file mode 100644 index 0000000..c86d0cd --- /dev/null +++ b/src/designPattern/grapheSimple/GrapheSimple.java @@ -0,0 +1,260 @@ +package designPattern.grapheSimple; + +import designPattern.grapheX.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +/** + * Cette classe a ete necessaire pour gérer les graphes ayant plusieurs arétes entre deux sommets données + * et ayant des arcs dans les deux sens entre deux sommets. + * Ces fonctionnalités n'étaient pas prises en charge par les classes initiales. + * Elle permet egalement de simplifier la comprehension des codes données. + * @author blay + * + */ +public class GrapheSimple extends Graphe { + HashMap mesSommets = new HashMap<>(); + + HashMap>>> aretes; + + + public GrapheSimple() { + aretes = new HashMap<>(); + } + + + public T getSommet(String ident){ + return mesSommets.get(ident); + } + + @Override + public int taille() { + return mesSommets.size(); + } + + + @Override + + public Graphe copie() { + //@TODO + return null; + } + + //n'ajoute le sommet que s'il n'est pas deja dans le graphe. + @Override + public void ajouterSommet(T s) { + if (existeSommet(s)) + return; + mesSommets.put(s.identifiant(), s); + aretes.put(s,new HashMap>>()); + } + + @Override + public boolean existeArc(Sommet s, Sommet t) { + return aretes.get(s).containsKey(t); + } + + + //A revoir avec la nouvelle version + //@todo + private boolean existeSommet(T s) { + return aretes.containsKey(s); + } + + + public List> arcs(T s, T t) { + return aretes.get(s).get(t); + } + + @Override + public void ajouterArc(T s, T t) { + this.ajouterArc(s,t,0); + } + + + @Override + public void ajouterArc(Arc arc) { + HashMap>> s = aretes.get(arc.origine()); + if (s == null){ + ajouterSommet(arc.origine()); + s=aretes.get(arc.origine()); + } + if (aretes.get(arc.destination()) == null) + ajouterSommet(arc.destination()); + if (s.get(arc.destination()) == null) + s.put(arc.destination(), new ArrayList<>()); + s.get(arc.destination()).add(arc); + + } + @Override + public void ajouterArc(T s, T t, int val) { + Arc a = new Arc<>(s,t,val); + this.ajouterArc(a); + } + + //Remarque : gestion horrible des exceptions mais on s'adapte à cause de l'héritage qui nous interdit de lever une exception. + @Override + public int valeurArc(T s, T t) { + if (!existeArc(s,t)) throw new Error("Arc inexistant"); + return aretes.get(s).get(t).get(0).valeur(); + } + + //RETIRE TOUS LES ARCS VERS T + @Override + public void enleverArc(Sommet s, Sommet t) { + if (!existeArc(s,t)) return ; + aretes.get(s).remove(t); + } + + @Override + public Collection sommets() { + return mesSommets.values(); + } + + @Override + public Collection> voisins(Sommet s) { + ArrayList> voisins = new ArrayList<>(); + HashMap>> arcs = aretes.get(s); + if ( arcs != null ) + for (ArrayList> av : arcs.values()) + voisins.addAll(av); + return voisins ; + } + + @Override + public String toString() { + return "Sommets=" + mesSommets + ";\n arcs=" + + toStringArretes(aretes) + "]"; + } + + private String toStringArretes( + HashMap>>> aretes2) { + StringBuilder bld = new StringBuilder(); + for ( HashMap>> x : aretes2.values()){ + for ( ArrayList> edges : x.values()) + for (Arc a : edges) + bld.append( "\t").append(a).append("\n" ); + } + return bld.toString(); + } + + + /** + * @param origine + * @return une liste de chemin + * Cette m�thode renvoie les chemins les plus longs possibles � partir du point d'orgine + */ + public List> chemins(T origine){ + HashMap>> dejaVu = new HashMap<>(); + return chemins(origine,dejaVu); + } + + /** + * @param origine + * @param destination + * @return une liste de chemins entre deux Ts + * Cette m�thode renvoie tous les chemins entre deux Sommets donnes + */ + //Pbme avec la comparaison des chemins... qui considere comme �gal deux objets diff�rents... cela doit venir de l'h�ritage... + + public List> chemins(T origine, T destination){ + List> chemins = chemins(origine); + List> cheminsEntreDeuxSommets = new ArrayList<> (); + for(Chemin c : chemins) { + if (c.atteint(destination)){ + Chemin raccourcis = c.extraireChemin(origine, destination); + if (! cheminsEntreDeuxSommets.contains(raccourcis)) { + cheminsEntreDeuxSommets.add(raccourcis); + } + } + } + return cheminsEntreDeuxSommets; + } + + + private List> chemins(T origine, HashMap>> dejaVu){ + + List> chemins = new ArrayList<>(); + + if (dejaVu.containsKey(origine)){ + chemins.add(new Chemin<>(dejaVu.get(origine))); + return chemins; + } + + + dejaVu.put(origine, new ArrayList>()); + + + Collection> voisins = voisins(origine); + HashMap>> dejavVuLocal ; + + for (Arc a : voisins) { + T destination = a.destination(); + dejavVuLocal= new HashMap<>(dejaVu); + + if (nouvelleDestinationOuNouvelArcSansRetour(origine,dejavVuLocal,destination,a)) { + dejavVuLocal.get(origine).add(a); + List> cheminsLocaux = chemins(destination,dejavVuLocal); + if (cheminsLocaux.isEmpty()) { + Chemin chemin = new Chemin<>(); + chemin.add(a); + chemins.add(chemin); + } + else { + for (Chemin c : cheminsLocaux) { + c.add(0,a); + chemins.add(c); + } + } + } + } + return chemins; + } + + //todo : tenir compte de Origine + private boolean nouvelleDestinationOuNouvelArcSansRetour( + T origine, HashMap>> dejaVu, T destination, + Arc a) { + + if (! dejaVu.containsKey(destination) ) + return true; + + return ( (! dejaVu.get(destination).contains(a)) && (! dejaVu.containsKey(a.destination()) ) ); + } + + + public Chemin cheminLePlusCourt(T origine, T destination){ + List> chemins = this.chemins(origine, destination); + Chemin cheminLePlusCourt = null; + int distanceLaPlusCourte = Integer.MAX_VALUE; + for(Chemin c : chemins) { + if (distanceLaPlusCourte > c.distance()) { + distanceLaPlusCourte = c.distance(); + cheminLePlusCourt = c; + } + } + return cheminLePlusCourt; + } + + public Set voisinsAuRang(T origine, int rang){ + List> chemins = chemins(origine); + Set TsVoisinsDejaVu = new TreeSet<>(); + Set TsDeBonRang = new TreeSet<>(); + for (Chemin c : chemins) { + List sommets = c.sommets(); + int i = 0; + for (i = 0; (i d avec valeur val +public class Arc implements Comparable> { + private S o, d; + + private int val; + + public Arc(S o0, S d0, int val0) { + this.o = o0; + this.d = d0; + this.val = val0; + } + + public Arc(S o0, S d0) { + this.o = o0; + this.d = d0; + this.val = 0; + } + + public Arc(Arc a) { + this.o = a.o; + this.d = a.d; + this.val = a.val; + } + + public S destination() { + return d; + } + + public S origine() { + return o; + } + + public int valeur() { + return val; + } + + public void modifierValeur(int vv) { + this.val = vv; + } + + @Override +public String toString() { + return "(" + val + ":" + this.o + ", " + this.d + ")"; + } + + @Override +public int hashCode() { + int codeOri = (o == null ? 0 : o.hashCode()); + int codeDst = (d == null ? 0 : d.hashCode()); + return codeDst ^ (codeOri * 31); + } + + @Override +public boolean equals(Object aa) { + if (!(aa instanceof Arc)) + return false; + Arc arc = (Arc) aa; + boolean equalsO = o == null && arc.o == null || o != null + && o.equals(arc.o); + boolean equalsD = d == null && arc.d == null || d != null + && d.equals(arc.d); + return equalsO && equalsD && (val == arc.val); + } + +public int compareTo(Arc a) { + int comp = Identifiable.compare(this.o, a.o); + if (comp == 0) + comp = Identifiable.compare(d, a.d); + return comp; + } + +} diff --git a/src/designPattern/grapheX/Graphe.java b/src/designPattern/grapheX/Graphe.java new file mode 100644 index 0000000..9481ecc --- /dev/null +++ b/src/designPattern/grapheX/Graphe.java @@ -0,0 +1,871 @@ +package designPattern.grapheX; + +import java.util.*; + +/** + Classe abstraite de graphes + + + @author FMorain (morain@lix.polytechnique.fr) + @version 2008.03.01 + @author MBF revisée pour la rendre générique + */ + +public abstract class Graphe extends GrapheGenerique{ + + @Override +public abstract int taille(); + public abstract Graphe copie(); + + @Override +public abstract void ajouterSommet(T s); + @Override +public abstract boolean existeArc(T s, T t); + @Override +public abstract void ajouterArc(T s, T t, int val); + public abstract void ajouterArc(Arc arc); + @Override +public abstract int valeurArc(T s, T t); + @Override +public abstract void enleverArc(T s, T t); + + @Override +public abstract Collection sommets(); + @Override +public abstract Collection> voisins(T s); + + public boolean oriente; + + public static String version(){ + return "grapheX -- version 1.3d, 2008/02/27"; + } + + public void ajouterArc(T s, T t){ + ajouterArc(s, t, 0); + } + + public boolean existeArc(Arc alpha){ + return existeArc(alpha.origine(), alpha.destination()); + } + + + +public String toString(){ + String str = ""; + + for(T s : sommets()){ + str += s + ":"; + for(T t : sommets()){ + if(existeArc(s, t)) + str += " " + valeurArc(s, t); + else + str += " -"; + } + str += "\n"; + } + return str; + } + + /* public void faireComplet(){ + int n = taille(); + for(int i = 0; i < n; i++) + ajouterSommet(new Sommet(i+"")); + for(Sommet s : sommets()) + for(Sommet t : sommets()) + if(!s.equals(t)) + ajouterArc(s, t, 1); + } + + public static void afficherParcours(HashMap L){ + System.err.println("PARCOURS"); + for(Sommet s : L.keySet()) + System.err.print(" ["+s+", "+L.get(s)+"]"); + System.err.println(); + } + + public static Graphe RoyWarshall(Graphe G){ + Graphe F = G.copie(); + + for(Sommet s : G.sommets()) + F.ajouterArc(s, s, 1); + System.err.println("FT_ini = \n"+F); + for(Sommet r : G.sommets()){ + for(Sommet s : G.sommets()) + for(Sommet t : G.sommets()) + if(!F.existeArc(s, t) + && (F.existeArc(s, r) && F.existeArc(r, t))) + F.ajouterArc(s, t, 1); + System.err.println("\nA_"+r); + System.err.println(F); + } + return F; + }*/ + + //////////////////// Dijkstra //////////////////// + + public HashMap Dijkstra(T s){ + int INFINITY = 1000000; + HashMap L = new HashMap(); + + // 1. initialisation + for(T t : sommets()) + if(! t.equals(s)) + if(existeArc(s, t)) + L.put(t, valeurArc(s, t)); + else + L.put(t, INFINITY); + // 2. + HashSet U = new HashSet<>(sommets()); // copie + L.put(s, 0); + U.remove(s); + // 3. + while(! U.isEmpty()){ + //afficherParcours(L); + // 4. + T v = null; + int Lv = INFINITY; + for(T t : U) + if(L.get(t) < Lv){ + v = t; + Lv = L.get(t); + } + System.err.println("-->v="+v); + // 5. + U.remove(v); + // 6. + // for(Sommet t : U) + // if(existeArc(v, t)){ + for(Arc a : voisins(v)){ + T t = a.destination(); + int tmp = Lv + a.valeur(); + if(tmp < L.get(t)) + L.put(t, tmp); + } + } + return L; + } +/* + TreeSet Dijkstra2Init(HashMap L, T s){ + int INFINITY = 1000000; + TreeSet fp = + new TreeSet( + new Comparator() { + public int compare(SommetValue s1, SommetValue s2) { + if(s1.valeur < s2.valeur) + return -1; + else if(s1.valeur > s2.valeur) + return 1; + if(s1.s.equals(s2.s)) + return 0; + return -1; + } + } + ); + for(Sommet u : sommets()){ + if(u.equals(s)) + L.put(u, 0); + else if(existeArc(s, u)){ + int val = valeurArc(s, u); + fp.add(new SommetValue(u, val)); + L.put(u, val); + } + else{ + fp.add(new SommetValue(u, INFINITY)); + L.put(u, INFINITY); + } + } + return fp; + } + + public HashMap Dijkstra2(T s){ + HashMap L = new HashMap(); + + // 1. initialisation + TreeSet U = Dijkstra2Init(L, s); + // 3. + while(! U.isEmpty()){ + //afficherParcours(L); + // 4. + SommetValue v = U.first(); + U.remove(v); + int Lv = v.valeur; + //System.err.println("v="+v.s+" Lv="+Lv); + // 5. + // 6. + for(Arc a : voisins(v.s)){ + Sommet t = a.destination(); + int tmp = Lv + a.valeur(); + if(tmp < L.get(t)){ + // System.err.println("-"+t+" "+L.get(t)); + U.remove(new SommetValue(t, L.get(t))); + // System.err.println("+"+t+" "+tmp); + U.add(new SommetValue(t, tmp)); + L.put(t, tmp); + } + } + } + return L; + } + + public void Prim(){ + HashSet HS = new HashSet(); + for(Sommet u : sommets()){ + if(! HS.contains(u)){ + //System.err.println("Je pars de "+u); + HS.add(u); + TreeSet> fp = + new TreeSet>( + new Comparator>(){ + public int compare(Arc a1, Arc a2){ + if(a1.valeur() < a2.valeur()) + return -1; + else if(a1.valeur() > a2.valeur()) + return 1; + else if(a1.equals(a2)) + return 0; + else if(! a1.origine().equals(a2.origine())) + return a1.origine().compareTo(a2.origine()); + else if(! a1.destination().equals(a2.destination())) + return a1.destination().compareTo(a2.destination()); + else + return 0; + } + } + ); + for(Arc a : voisins(u)){ + //System.err.println("fp += "+a+" ["+a.valeur()+"]"); + fp.add(a); + } + while(! fp.isEmpty()){ + System.err.println("FP_BEGIN"); + for(Arc z : fp){ + System.err.println(z+" "+z.valeur()); + } + System.err.println("FP_END"); + Arc a = fp.first(); + fp.remove(a); + Sommet t = a.destination(); + System.err.print("Je regarde "+a+"["+a.valeur()+"] : "); + if(HS.contains(t)) + System.err.println("il forme un cycle"); + else{ + System.err.println("je l'ajoute dans T"); + HS.add(t); + for(Arc b : voisins(t)){ + System.err.println("fp += "+b+" ["+b.valeur()+"]"); + fp.add(b); + } + } + } + } + } + } + + //////////////////// BFS //////////////////// + + + final static int inexplore = 0, encours = 1, explore = 2; + + public void bfs(HashMap etat, Sommet s){ + LinkedList f = new LinkedList(); + + etat.put(s, encours); + f.addLast(s); + while(! f.isEmpty()){ + Sommet t = f.removeFirst(); + System.err.println("J'explore "+t); + for(Arc a : voisins(t)){ + Sommet u = a.destination(); + if(etat.get(u) == inexplore){ + etat.put(u, encours); + f.addLast(u); + } + } + etat.put(t, explore); + } + } + + public HashMap bfsDistance(Sommet s){ + HashMap etat = new HashMap(); + LinkedList f = new LinkedList(); + HashMap distance = + new HashMap(); + HashMap numero = + new HashMap(); + int num = 0; + + for(Sommet t : sommets()){ + etat.put(t, inexplore); + distance.put(t, 0); + numero.put(t, 0); + } + etat.put(s, encours); + f.addLast(s); + numero.put(s, num++); + while(! f.isEmpty()){ + Sommet t = f.removeFirst(); + System.err.println("J'explore "+t); + for(Arc a : voisins(t)){ + Sommet u = a.destination(); + if(etat.get(u) == inexplore){ + etat.put(u, encours); + f.addLast(u); + numero.put(u, num++); + System.err.println("num["+u+"]="+numero.get(u)); + distance.put(u, distance.get(t) + 1); + } + } + etat.put(t, explore); + } + return distance; + } + + public void composantesConnexesBFS(){ + HashMap etat = new HashMap(); + for(Sommet s : sommets()) + etat.put(s, inexplore); + int ncc = 0; + for(Sommet s : sommets()) + if(etat.get(s) == inexplore){ + ncc++; + System.err.println("Composante "+ncc); + bfs(etat, s); + } + } + + public boolean bfsBiparti(HashMap etat, HashMap couleur, Sommet s){ + LinkedList f = new LinkedList(); + int c = 0; // la couleur + + etat.put(s, encours); + couleur.put(s, c); + f.addLast(s); + while(! f.isEmpty()){ + Sommet t = f.removeFirst(); + System.err.println("J'explore "+t+" de couleur "+couleur.get(t)); + // c <- couleur des voisins de t + c = 1 - couleur.get(t); + for(Arc a : voisins(t)){ + Sommet u = a.destination(); + if(etat.get(u) == inexplore){ + etat.put(u, encours); + couleur.put(u, c); + f.addLast(u); + } + else if(couleur.get(u) != c){ + System.err.println(u+" est de'ja` colorie' avec la mauvaise couleur"); + return false; + } + } + etat.put(t, explore); + } + return true; + } + + // n'a vraiment un sens que sur les graphes non oriente's connexes + public HashMap estBiparti(){ + HashMap etat = new HashMap(); + HashMap couleur = new HashMap(); + for(Sommet s : sommets()) + etat.put(s, inexplore); + int ncc = 0; + for(Sommet s : sommets()) + if(etat.get(s) == inexplore){ + ncc++; + System.err.println("Composante "+ncc); + if(!bfsBiparti(etat, couleur, s)) + // le graphe n'est pas biparti + return null; + } + return couleur; + } + +////////////DFS + + public void dfs(HashMap etat, Sommet s){ + LinkedList F = new LinkedList(); + int rg = -1; + + F.addFirst(s); + while(! F.isEmpty()){ + Sommet t = F.removeFirst(); + if(etat.get(t) != explore){ + System.err.println("J'explore "+t); + etat.put(t, encours); + ++rg; + System.err.println("rang["+t+"]="+rg); + for(Arc a : voisins(t)){ + Sommet u = a.destination(); + F.addFirst(u); + } + } + etat.put(t, explore); + } + } + + public void dfs(){ + Sommet r = null; + for(Sommet s : sommets()){ + r = s; + break; + } + HashMap etat = new HashMap(); + for(Sommet s : sommets()) + etat.put(s, inexplore); + //dfsFausse(etat, r); // pour avoir un exemple qui foire Data/pchassignet.in + dfs(etat, r); + } + + public int dfsRec(HashMap etat, + HashMap,String> etat_a, + HashMap rang, int rg, + Sommet racine, Sommet s){ + etat.put(s, encours); + rang.put(s, rg++); + System.err.println("J'explore "+s); + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat.get(t) == inexplore){ + System.err.println("("+s+", "+t+") liaison"); + etat_a.put(a, "arcliaison"); + rg = dfsRec(etat, etat_a, rang, rg, racine, t); + } + else{ + if(etat.get(t) == encours){ + // t est ascendant de s + System.err.println("("+s+", "+t+") arrie`re"); + etat_a.put(a, "arcarriere"); + } + else{ + // t a de'ja` e'te' explore' + if(rang.get(t) < rang.get(racine)){ + System.err.println("("+s+", "+t+") transverse car racine("+t+") <> racine("+s+")"); + etat_a.put(a, "arcinter"); + } + else{ // t est dans la me^me arborescence que s + if(rang.get(s) < rang.get(t)){ + System.err.println("("+s+", "+t+") avant"); + etat_a.put(a, "arcavant"); + } + else{ + System.err.println("("+s+", "+t+") transverse"); + etat_a.put(a, "arcintra"); + } + } + } + } + } + etat.put(s, explore); + return rg; + } + + public void dfsRang(){ + HashMap etat = new HashMap(); + HashMap,String> etat_a = new HashMap,String>(); + HashMap rang = new HashMap(); + + for(Sommet s : sommets()){ + etat.put(s, inexplore); + for(Arc alpha : voisins(s)) + etat_a.put(alpha, "arclibre"); + } + int rg = 0; + for(Sommet s : sommets()) + if(etat.get(s) == inexplore) + rg = dfsRec(etat, etat_a, rang, rg, s, s); + System.err.print(" "); + for(Sommet t : sommets()) + System.err.print(t); + System.err.print("\nrang "); + for(Sommet t : sommets()) + System.err.print(rang.get(t)); + System.err.println(); + } + + // on retourne un arbre couvrant de racine s + public Arbre dfsRec(HashMap etat, Sommet s){ + etat.put(s, encours); + Arbre A = new Arbre(s); + System.err.println("J'explore "+s); + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat.get(t) == inexplore) + A.ajouterFils(dfsRec(etat, t)); + } + etat.put(s, explore); + return A; + } + + public void dfsCouvrant(){ + Sommet ALPHA = new Sommet("ALPHA"); + Arbre F = new Arbre(ALPHA); + HashMap etat = new HashMap(); + + for(Sommet s : sommets()) + etat.put(s, inexplore); + for(Sommet s : sommets()) + if(etat.get(s) == inexplore) + F.ajouterFils(dfsRec(etat, s)); + System.err.println("F=\n"+F); + } + + //// Tri topologique + + boolean dfsTopo(HashMap etat, + LinkedList L, Sommet s){ + etat.put(s, encours); + System.err.println("J'explore "+s); + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat.get(t) == inexplore){ + if(! dfsTopo(etat, L, t)) + return false; + } + else if(etat.get(t) == encours){ + // t est ascendant de s + System.err.println("("+s+", "+t+") arrie`re -> erreur"); + return false; + } + } + etat.put(s, explore); + L.addFirst(s); + return true; + } + + public void triTopologique(){ + HashMap etat = new HashMap(); + for(Sommet s : sommets()) + etat.put(s, inexplore); + for(Sommet s : sommets()){ + if(etat.get(s) == inexplore){ + LinkedList L = new LinkedList(); + if(! dfsTopo(etat, L, s)){ + System.err.println("Graphe avec circuit"); + return; + } + for(Sommet t : L) + System.err.print(t+" -> "); + System.err.println(); + } + } + } + + //// Points d'attache + int dfsAttache(HashMap etat, + HashMap rang, int rg, + HashMap rat, Sommet racine, Sommet s){ + etat.put(s, encours); + System.err.println("J'explore "+s); + rang.put(s, rg++); + int rats = rang.get(s), ratt; + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat.get(t) == inexplore){ + rg = dfsAttache(etat, rang, rg, rat, racine, t); + ratt = rat.get(t); + } + else if(etat.get(t) == encours) + // (s, t) est un arc arrie`re + ratt = rang.get(t); + else if(rang.get(t) < rang.get(racine)) + // (s, t) transverse inter + continue; + else // (s, t) avant ou transverse intra + ratt = rang.get(t); + // HERE: vrai? Cf. exemple bbc1 pour l semble faux...! + rats = Math.min(rats, ratt); + } + rat.put(s, rats); + etat.put(s, explore); + return rg; + } + + public void pointsDAttache(){ + HashMap etat = new HashMap(); + HashMap rang = new HashMap(); + HashMap rat = new HashMap(); + + for(Sommet s : sommets()) + etat.put(s, inexplore); + int rg = 0; + for(Sommet s : sommets()) + if(etat.get(s) == inexplore) + rg = dfsAttache(etat, rang, rg, rat, s, s); + System.err.println("Rangs"); + for(Sommet s : sommets()) + System.err.println(s+" "+rang.get(s)); + System.err.println("Rangs d'attache"); + for(Sommet s : sommets()) + System.err.println(s+" "+rat.get(s)); + } + + //// Composantes fortement connexes + + final static int libre = 0, empile = 1, exclus = 2, pointdentree = 3, dansCFC = 4; + + int dfsCfc(HashMap etat, + HashMap etat_cfc, + HashMap,String> etat_a, + LinkedList pile, + HashMap rang, int rg, + HashMap rat, + Sommet racine, Sommet s){ + etat.put(s, encours); + System.err.println("J'explore "+s); + rang.put(s, rg++); + rat.put(s, rang.get(s)); + pile.addFirst(s); + etat_cfc.put(s, empile); + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat_cfc.get(t) == inexplore){ + System.err.println("("+s+", "+t+") liaison"); + etat_a.put(a, "arcliaison"); + rg = dfsCfc(etat, etat_cfc, etat_a, pile, rang, rg, rat, racine, t); + if(rat.get(t) < rat.get(s)){ + rat.put(s, rat.get(t)); + } + } + else{ + if(etat_cfc.get(t) == empile){ + if(rang.get(t) > rang.get(s)) + // (s, t) est avant + etat_a.put(a, "arcavant"); + else{ + // (s, t) est arriere ou intra-arbre + // t est dans C(s) car t descendant de s et s -> t + if(etat.get(t) == encours){ + System.err.println("("+s+", "+t+") arrie`re"); + etat_a.put(a, "arcarriere"); + } + else{ + System.err.println("("+s+", "+t+") intra-arbre"); + etat_a.put(a, "arcintra"); + } + System.err.println(t+" est dans C("+s+")"); + if(rang.get(t) < rat.get(s)) + rat.put(s, rang.get(t)); + } + } + else{ + // t est exclus + System.err.println(t+" exclus"); + if(rang.get(t) < rang.get(racine)) + // (s, t) est inter-arbre + etat_a.put(a, "arcinter"); + else + etat_a.put(a, "arcintra"); + } + } + } + etat.put(s, explore); + System.err.print("rang["+s+"]="+rang.get(s)); + System.err.println(" rat["+s+"]="+rat.get(s)); + if(rat.get(s) == rang.get(s)){ + // s est un point d'entre'e + etat_cfc.put(s, pointdentree); + for(Sommet u : pile){ + if(u.equals(s)) + break; + etat_cfc.put(u, dansCFC); + } + Sommet t; + System.err.print("CFC={"); + do{ + t = pile.removeFirst(); + etat_cfc.put(t, exclus); + System.err.print(" "+t); + } while(! t.equals(s)); + System.err.println(" }"); + } + return rg; + } + + public void cfc(){ + HashMap etat = new HashMap(); + HashMap etat_cfc = new HashMap(); + HashMap,String> etat_a = new HashMap, String>(); + HashMap rang = new HashMap(); + HashMap rat = new HashMap(); + LinkedList pile = new LinkedList(); + + for(Sommet s : sommets()){ + etat.put(s, inexplore); + etat_cfc.put(s, libre); + for(Arc alpha : voisins(s)) + etat_a.put(alpha, "arclibre"); + } + int rg = 0; + for(Sommet s : sommets()) + if(etat.get(s) == inexplore) + rg = dfsCfc(etat, etat_cfc, etat_a, pile, rang, rg, rat, s, s); + System.err.println("Rangs"); + for(Sommet s : sommets()) + System.err.println(s+" "+rang.get(s)); + } + + //// Points d'articulation et blocs + + void depiler(LinkedList> pile, Sommet s, Sommet t){ + Sommet x, y; + System.err.print("Bloc = {"); + do{ + Arc a = pile.removeFirst(); + x = a.origine(); + y = a.destination(); + System.err.print("("+x+", "+y+")"); + } while(!x.equals(s) && !y.equals(t)); + System.err.println("}"); + } + + void depiler(LinkedList> pile){ + System.err.print("Bloc_racine = {"); + while(! pile.isEmpty()){ + Arc a = pile.removeFirst(); + System.err.print("("+a.origine()+", "+a.destination()+")"); + } + System.err.println("}"); + } + + // pere -> s + int dfsPda(LinkedList lpda, + HashMap etat, + LinkedList> pile, + HashMap rang, int rg, + HashMap rat, + Sommet pere, Sommet s){ + etat.put(s, encours); + System.err.println("J'explore "+s); + rang.put(s, rg++); + int rats = rang.get(s); + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat.get(t) == inexplore){ + System.err.println("("+s+", "+t+") liaison"); + pile.addFirst(a); + rg = dfsPda(lpda, etat, pile, rang, rg, rat, s, t); + rats = Math.min(rats, rat.get(t)); + if(rat.get(t) >= rang.get(s)){ + System.err.println(s+" est point d'articulation"); + depiler(pile, s, t); + lpda.addFirst(s); + } + } + else if((rang.get(t) < rang.get(s)) && !t.equals(pere)){ + System.err.println("("+s+", "+t+") arrie`re ou transverse"); + pile.addFirst(a); + rats = Math.min(rats, rang.get(t)); + } + } + rat.put(s, rats); + System.err.print("rang["+s+"]="+rang.get(s)); + System.err.println(" rat["+s+"]="+rat.get(s)); + etat.put(s, explore); + return rg; + } + + // s est la racine de l'arborescence + int dfsPda(LinkedList lpda, + HashMap etat, + LinkedList> pile, + HashMap rang, int rg, + HashMap rat, Sommet s){ + etat.put(s, encours); + System.err.println("J'explore "+s); + rang.put(s, rg++); + int rats = rang.get(s); + int nfils = 0; + for(Arc a : voisins(s)){ + Sommet t = a.destination(); + if(etat.get(t) == inexplore){ + System.err.println("("+s+", "+t+") liaison"); + pile.addFirst(a); + rg = dfsPda(lpda, etat, pile, rang, rg, rat, s, t); + nfils++; + } + } + if(nfils > 1){ + lpda.addFirst(s); + System.err.println(s+" est racine ET point d'articulation"); + depiler(pile); + } + rat.put(s, rats); + System.err.print("rang["+s+"]="+rang.get(s)); + System.err.println(" rat["+s+"]="+rat.get(s)); + etat.put(s, explore); + return rg; + } + + public void pointsDArticulation(LinkedList lpda, + HashMap rat){ + HashMap etat = new HashMap(); + HashMap rang = new HashMap(); + + for(Sommet s : sommets()) + etat.put(s, inexplore); + int rg = 0; + LinkedList> pile = new LinkedList>(); + for(Sommet s : sommets()) + if(etat.get(s) == inexplore) + // nouvelle composante connexe + rg = dfsPda(lpda, etat, pile, rang, rg, rat, s); + System.err.println("Rangs"); + for(Sommet s : sommets()) + System.err.println(s+" "+rang.get(s)); + } + + public static String XMLHeader(){ + String str = "\n"; + str += "\n"; + str += " \n"; + str += " 1.3.9\n"; + str += " \n"; + str += " \n"; + str += " \n"; + str += " \n"; + str += " \n"; + str += " \n"; + return str; + } + public static String XMLTrailer(){ + return "\n"; + } + // pos[s] est la position de s dans le plan, color[s] le contenu de s, par exemple une couleur. + // pos[s] doit etre de la forme x,y + public String toGraphml(String nom, HashMap pos, HashMap color){ + String str = XMLHeader(); + str += " \n"; + else + str += " edgedefault=\"undirected\">\n"; + // les sommets + for(Sommet s : sommets()){ + str += " \n"; + if(pos != null) + str += " "+pos.get(s)+"\n"; + if(color != null) + str += " " + color.get(s) + "\n"; + str += " " + s + "\n"; + str += " \n"; + } + // les aretes + for(Sommet s : sommets()){ + for(Arc arc : voisins(s)){ + // TODO: permettre des couleurs et labels sur les arcs + Sommet t = arc.destination(); + str += " \n"; + str += " 1\n"; + str += " 1\n"; + str += " \n"; + } + } + str += " \n"; + str += XMLTrailer(); + return str; + }*/ +} + diff --git a/src/designPattern/grapheX/GrapheGenerique.java b/src/designPattern/grapheX/GrapheGenerique.java new file mode 100644 index 0000000..1b9df35 --- /dev/null +++ b/src/designPattern/grapheX/GrapheGenerique.java @@ -0,0 +1,81 @@ +package designPattern.grapheX; + +import java.util.Collection; + +/** + * Super-classe abstraite des graphes, les sommets doivent �tre identifiables. + * + * @author FMorain (morain@lix.polytechnique.fr) + * @author PChassignet (chassign@lix.polytechnique.fr) + * @version 2007.03.21 + */ + +public abstract class GrapheGenerique { + + /** + * @return le nombre de sommets de ce graphe. + */ + public abstract int taille(); + + /** + * @param s + * le sommet � ajouter � ce graphe. + */ + public abstract void ajouterSommet(S s); + + /** + * @return une Collection de tous les sommets de ce graphe. + */ + public abstract Collection sommets(); + + /** + * Teste l'existence de l'arc de s � t dans ce graphe. + * + * @param s + * l'origine de l'arc, + * @param t + * l'extr�mit� de l'arc. + */ + public abstract boolean existeArc(S s, S t); + + /** + * @param s + * l'origine de l'arc, + * @param t + * l'extr�mit� de l'arc, + * @param val + * une valeur enti�re attach�e � l'arc de s � t + * dans ce graphe. + */ + public abstract void ajouterArc(S s, S t, int val); + + /** + * @param s + * l'origine de l'arc, + * @param t + * l'extr�mit� de l'arc. + * @return la valeur enti�re attach�e � l'arc de s � t + * dans ce graphe. + */ + public abstract int valeurArc(S s, S t); + + /** + * Supprime l'arc de s � t dans ce graphe. + * + * @param s + * l'origine de l'arc, + * @param t + * l'extr�mit� de l'arc. + */ + public abstract void enleverArc(S s, S t); + + /** + * @param s + * l'origine des arcs. + * @return une Collection de tous les arcs de ce graphe ayant + * s pour origine. Ces arcs sont de type + * Arc<S>. + */ + public abstract Collection> voisins(S s); + +} diff --git a/src/designPattern/grapheX/Identifiable.java b/src/designPattern/grapheX/Identifiable.java new file mode 100644 index 0000000..603d30e --- /dev/null +++ b/src/designPattern/grapheX/Identifiable.java @@ -0,0 +1,100 @@ +package designPattern.grapheX; + +/** + * D�finit des objets identifi�s par une String. Deux objets + * Identifiable qui sont construit avec le m�me identifiant seront + * consid�r�s comme identiques pour les m�thodes hashCode, + * equals et compareTo. Cette classe sert notamment de + * super-classe pour les sommets d'un graphe. + * + * @author PChassignet (chassign@lix.polytechnique.fr) + * @version 2007.03.21 + */ + +public class Identifiable implements Comparable { + private final String ident; + + /** + * @param identifiant + * l'identifiant pour cet objet. + */ + public Identifiable(String identifiant) { + ident = identifiant; + } + + /** + * @return l'identifiant pour cet objet. + */ + public final String identifiant() { + return ident; + } + + /** + * @return le hashCode de l'identifiant de cet objet. + */ + @Override +public final int hashCode() { + if (ident == null) + return 0; + else + return ident.hashCode(); + } + + /** + * @return le r�sultat de equals sur les identifiants. + */ + @Override +public final boolean equals(Object o) { + if (!(o instanceof Identifiable)) { + return false; + } + String oid = ((Identifiable) o).ident; + if (ident == null) + return oid == null; + else + return ident.equals(oid); + } + + /** + * @return le r�sultat de compareTo sur les identifiants. + */ +public final int compareTo(Identifiable id) { + if (ident == null) + if (id.ident == null) + return 0; + else + return -1; + else if (id.ident == null) + return 1; + else + return ident.compareTo(id.ident); + } + + /** + * @param id1 + * premier objet � comparer, + * @param id2 + * second objet � comparer, + * @return le r�sultat de id1.compareTo(id2). + */ + public static final int compare(Identifiable id1, Identifiable id2) { + if (id1 == null) + if (id2 == null) + return 0; + else + return -1; + else if (id2 == null) + return 1; + else + return id1.compareTo(id2); + } + + @Override +public String toString() { + if (ident == null) + return "[null]"; + else + return "[\"" + ident + "\"]"; + } + +} diff --git a/src/designPattern/grapheX/Sommet.java b/src/designPattern/grapheX/Sommet.java new file mode 100644 index 0000000..2048e5a --- /dev/null +++ b/src/designPattern/grapheX/Sommet.java @@ -0,0 +1,23 @@ +package designPattern.grapheX; + +/** + * Classe de sommets, toutes les propri�t�s sont h�rit�es de Identifiable. + * + * @author FMorain (morain@lix.polytechnique.fr) + * @author PChassignet (chassign@lix.polytechnique.fr) + * @version 2007.03.21 + */ + +public class Sommet extends Identifiable { + + public Sommet(String nn) { + super(nn); + } + + @Override +public String toString() { + return identifiant(); + } + + +} diff --git a/src/designPattern/grapheX/SommetValue.java b/src/designPattern/grapheX/SommetValue.java new file mode 100644 index 0000000..2dfba10 --- /dev/null +++ b/src/designPattern/grapheX/SommetValue.java @@ -0,0 +1,11 @@ +package designPattern.grapheX; + +public class SommetValue { + Sommet s; + int valeur; + + SommetValue(Sommet ss, int vv){ + s = ss; + valeur = vv; + } +} diff --git a/src/designPattern/reseauSocial/core/Member.java b/src/designPattern/reseauSocial/core/Member.java new file mode 100644 index 0000000..895531b --- /dev/null +++ b/src/designPattern/reseauSocial/core/Member.java @@ -0,0 +1,44 @@ +package designPattern.reseauSocial.core; + +import designPattern.grapheX.Sommet; + +public class Member extends Sommet implements MemberInterface { + + private String localisation; + private Enum force; + + public Member(String nn) { + super(nn); + // TODO Auto-generated constructor stub + } + + @Override + public String getLocation() { + return this.localisation; + } + + @Override + public void setLocation(String s) { + this.localisation = s; + } + + @Override + public String getName() { + return super.toString(); + } + + public Enum getForce() { + return force; + } + + public void setForce(Enum force) { + this.force = force; + } + + public void addMember(String nom, String location, SocialNetworkInterface reseau) { + Member m = new Member(nom); + m.setLocation(location); + reseau.addMember(m); + } + +} diff --git a/src/designPattern/reseauSocial/core/MemberInterface.java b/src/designPattern/reseauSocial/core/MemberInterface.java new file mode 100755 index 0000000..1416c5d --- /dev/null +++ b/src/designPattern/reseauSocial/core/MemberInterface.java @@ -0,0 +1,10 @@ +package designPattern.reseauSocial.core; + +public interface MemberInterface { + + + public String getLocation(); + public void setLocation(String s); + + public String getName(); +} diff --git a/src/designPattern/reseauSocial/core/SocialNetWorkImpl.java b/src/designPattern/reseauSocial/core/SocialNetWorkImpl.java new file mode 100644 index 0000000..3e0be47 --- /dev/null +++ b/src/designPattern/reseauSocial/core/SocialNetWorkImpl.java @@ -0,0 +1,85 @@ +package designPattern.reseauSocial.core; + +import java.util.Collection; +import java.util.Observable; +import java.util.Set; + +import designPattern.facebookGhost.FacebookGhostNetwork; +import designPattern.grapheSimple.GrapheSimple; + +@SuppressWarnings("deprecation") +public class SocialNetWorkImpl implements SocialNetworkInterface{ + + private String nom; + private GrapheSimple reseau; + + public SocialNetWorkImpl() { + this("Default"); + } + + public SocialNetWorkImpl(String n) { + this.nom = n; + reseau = new GrapheSimple(); + } + + @Override + public void update(Observable arg0, Object arg1) { + // TODO Auto-generated method stub + + } + + @Override + public Member getMember(String identifier) { + return reseau.getSommet(identifier); + } + + @Override + public Collection getMembers() { + return reseau.sommets(); + } + + @Override + public void addMember(Member m) { + reseau.ajouterSommet(m); + } + + @Override + public Member addMember(String ident, FacebookGhostNetwork fg) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Member addMember(String identifier) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void relate(Strength force, Member member, Member friend) { + // TODO Auto-generated method stub + + } + + @Override + public Set relatedToRank(Member member, int rank) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int distance(Member member1, Member member2) { + // TODO Auto-generated method stub + return 0; + } + + public String getNom() { + return nom; + } + + public void setNom(String n) { + this.nom = n; + } + + +} diff --git a/src/designPattern/reseauSocial/core/SocialNetworkInterface.java b/src/designPattern/reseauSocial/core/SocialNetworkInterface.java new file mode 100755 index 0000000..ec4101c --- /dev/null +++ b/src/designPattern/reseauSocial/core/SocialNetworkInterface.java @@ -0,0 +1,74 @@ +package designPattern.reseauSocial.core; + + +import java.util.Collection; +import java.util.Observer; +import java.util.Set; + +import designPattern.facebookGhost.FacebookGhostNetwork; + +/** + * + * Basic" interface for defining a social network + * + * @author blay + * + */ + +@SuppressWarnings("deprecation") +public interface SocialNetworkInterface extends Observer{ + + /** + * @param identifier for a member + * @return member if known by the network + */ + public T getMember(String identifier); + + /** + * @return the set of members belonging to the network + */ + public Collection getMembers(); + + /** + * add a member to the network + */ + public void addMember(T membre); + + /** + * @param ident + * @param fg a facebookGhostNetwork, if the member belongs to fg, an adapter to this network is created. + * @return the member corresponding to the identifier. If a member with this identifer already exists, the member is not created. + */ + public T addMember(String ident, FacebookGhostNetwork fg); + public T addMember(String identifier); + + + /** + * + * Add the relationship between a member and a friend with a given force. + * + * @param force + * @param member + * @param friend + * + */ + public void relate(Strength force, T member, T friend); + + /** + * @param member + * @param rank + * @return returns all members given the rank (at rank 1 : direct neighbors; at rank 2 : neighbors of neighbors. + * A member appears at the lowest rank, it does not appear in a higher rank + */ + public Set relatedToRank(T member, int rank); + + /** + * @param member1 + * @param member2 + * @return distance between the two members + */ + public int distance(T member1, T member2); + + + +} diff --git a/src/designPattern/reseauSocial/core/Strength.java b/src/designPattern/reseauSocial/core/Strength.java new file mode 100755 index 0000000..9835d50 --- /dev/null +++ b/src/designPattern/reseauSocial/core/Strength.java @@ -0,0 +1,17 @@ +package designPattern.reseauSocial.core; + +public enum Strength { + LOW (4), MEDIUM (3), HIGH (2), STRONG(1); + + int value; + + public int getValue() { + return value; + } + + Strength( int pvalue){ + value = pvalue; + } + + +} diff --git a/src/forum/Administrateur.java b/src/forum/Administrateur.java new file mode 100755 index 0000000..6e14ba6 --- /dev/null +++ b/src/forum/Administrateur.java @@ -0,0 +1,15 @@ +package forum; + +public class Administrateur { + + private String nom; + + public Administrateur() { + + } + + public Administrateur(String nomAdmin) { + this.nom = nomAdmin; + } + +} \ No newline at end of file diff --git a/src/forum/Canal.java b/src/forum/Canal.java new file mode 100755 index 0000000..57bb469 --- /dev/null +++ b/src/forum/Canal.java @@ -0,0 +1,17 @@ +package forum; + +import java.util.ArrayList; + +public class Canal { + + private int maxMessage; + private String nomCanal; + private Message message; + ArrayList canal = new ArrayList(); + + public Canal(String nomCanal, int maxMessage) { + this.nomCanal = nomCanal; + this.maxMessage = maxMessage; + } + +} diff --git a/src/forum/CanalDeBreve.java b/src/forum/CanalDeBreve.java new file mode 100755 index 0000000..a2000aa --- /dev/null +++ b/src/forum/CanalDeBreve.java @@ -0,0 +1,14 @@ +package forum; + +public class CanalDeBreve { + + private int tailleBreves; + private String nomCanal; + private Message message; + + public CanalDeBreve(String nomCanal, int tailleBreves) { + this.nomCanal = nomCanal; + this.tailleBreves = tailleBreves; + } + +} diff --git a/src/forum/CanalParDefaut.java b/src/forum/CanalParDefaut.java new file mode 100755 index 0000000..61fd710 --- /dev/null +++ b/src/forum/CanalParDefaut.java @@ -0,0 +1,9 @@ +package forum; + +public class CanalParDefaut { + public String nom; + + public CanalParDefaut(String nom) { + } + +} diff --git a/src/forum/Controleur.java b/src/forum/Controleur.java new file mode 100755 index 0000000..d5f07f4 --- /dev/null +++ b/src/forum/Controleur.java @@ -0,0 +1,88 @@ +package forum; + +public class Controleur { + + private GestionnaireForum registreF = new GestionnaireForum(); + private GestionnaireCanal registreC = new GestionnaireCanal(); + private UserConsole ui = new UserConsole(); + + public void start() throws Exception { + String commande = ui.lireCommande(); + switch (commande.charAt(0)) { + case UserConsole.COM_CREER_FORUM: + creerForum(); + start(); + break; + case UserConsole.COM_CREER_CANAL: + creerCanal(); + start(); + break; + case UserConsole.COM_POSTER_MESSAGES: +// posterMessage(); + start(); + break; + case UserConsole.COM_LIRE_MESSAGES: +// lireMessage(); + start(); + break; + case UserConsole.COM_STOP: + ui.afficher("Au revoir "); + // Memoire.save(registre, "sauvegarde.txt"); + System.exit(0); + break; + default: + ui.afficher("La commande spécifiée n'existe pas\n"); + Thread.sleep(1000); + start(); + } + } + + private void creerForum() { + String nomForum = ui.getValeur("Nom du forum :"); + registreF.addForum(nomForum); + + } + + private void creerCanal() { + String nomForum = ui.getValeur("Entrer le nom du forum dans lequel vous voulez créer un canal :"); + while (!GestionnaireForum.doesExist(nomForum)) { + System.out.println("Erreur : Il n'y a aucun forum de ce nom."); + nomForum = ui.getValeur("Entrer le nom du forum dans lequel vous voulez créer un canal :"); + } + + String typeCanal; + System.out.println("Quel type de canal voulez-vous créer ?"); + typeCanal = ui.getValeur("Entrer \"c\" pour canal ou \"b\" pour canal de brèves"); + while (!(typeCanal.contentEquals("c") || typeCanal.contentEquals("b"))) { + System.out.println("Erreur : donnée invalide."); + typeCanal = ui.getValeur("Quel type de canal voulez-vous créer ?"); + } + + String nomCanal = ui.getValeur("Entrer le nom du canal"); + + if (typeCanal.contentEquals("c")) { + System.out.println("Voulez-vous changer le nombre de messages max possibles pour ce canal?"); + String nb = ui.getValeur("Répondre y pour oui, n pour non"); + try { + int maxMessage = Integer.parseInt(nb); + registreC.CreerCanal(nomCanal, maxMessage); + } catch (NumberFormatException nfe) { + System.out.println("Erreur, ce n'est pas un entier"); + } + } else { + String nb = ui.getValeur("Quelle taille max voulez-vous pour les brèves?"); + try { + int tailleBreve = Integer.parseInt(nb); + registreC.CreerCanalDeBreve(nomCanal, tailleBreve); + } catch (NumberFormatException nfe) { + System.out.println("Erreur, ce n'est pas un entier"); + } + } + + } + + public static void main(String[] args) throws Exception { + Controleur c = new Controleur(); + c.start(); + } +} \ No newline at end of file diff --git a/src/forum/Forum.java b/src/forum/Forum.java new file mode 100755 index 0000000..7ddbf90 --- /dev/null +++ b/src/forum/Forum.java @@ -0,0 +1,17 @@ +package forum; + +public class Forum { + + private String title; + private CanalParDefaut defaultCanal; + + public Forum(String nomForum) { + this.title = nomForum; + this.defaultCanal = new CanalParDefaut("defaut"); + } + + public String getTitle() { + return title; + } + +} diff --git a/src/forum/GestionnaireCanal.java b/src/forum/GestionnaireCanal.java new file mode 100755 index 0000000..2822698 --- /dev/null +++ b/src/forum/GestionnaireCanal.java @@ -0,0 +1,26 @@ +package forum; + +import java.util.HashMap; + +public class GestionnaireCanal { + + private static HashMap canal = new HashMap(); + private static HashMap canalDeBreve = new HashMap(); + + public void CreerCanal(String nomCanal, int maxMessage) { + canal.put(nomCanal, new Canal(nomCanal, maxMessage)); + } + + public void CreerCanalDeBreve(String nomCanal, int tailleBreves) { + canalDeBreve.put(nomCanal, new CanalDeBreve(nomCanal, tailleBreves)); + } + + + public static boolean doesExist(String nomCanal) { + if (canal.containsKey(nomCanal)) { + return true; + } + return false; + } + +} \ No newline at end of file diff --git a/src/forum/GestionnaireForum.java b/src/forum/GestionnaireForum.java new file mode 100755 index 0000000..fbbb2e1 --- /dev/null +++ b/src/forum/GestionnaireForum.java @@ -0,0 +1,29 @@ +package forum; + +import java.util.HashMap; + +public class GestionnaireForum { + + private static HashMap forum = new HashMap(); + + public Forum getForum(String nomForum) { + return forum.get(nomForum); + } + + public void addForum(String nomForum) { + if (!doesExist(nomForum)) { + forum.put(nomForum, new Forum(nomForum)); + + } else { + System.out.println("erreur : Un forum du même nom existe déjà."); + } + } + + public static boolean doesExist(String nom) { + if (forum.containsKey(nom)) { + return true; + } + return false; + } + +} diff --git a/src/forum/Memoire.java b/src/forum/Memoire.java new file mode 100755 index 0000000..9da8972 --- /dev/null +++ b/src/forum/Memoire.java @@ -0,0 +1,52 @@ +package forum; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Based on http://www.jmdoudoux.fr/java/dej/chap-serialisation.htm + * + * @author Mireille Blay + * + */ + +public class Memoire { + + static Logger monLog = Logger.getLogger(Memoire.class.getName()); + + private Memoire() { + super(); + } + + public static void save(Object o, String fileName) { + + try (FileOutputStream fichier = new FileOutputStream(fileName); + ObjectOutputStream oos = new ObjectOutputStream(fichier);) { + oos.writeObject(o); + oos.flush(); + } catch (java.io.IOException e) { + monLog.log(Level.SEVERE, e.getMessage(), e); + } + } + + + public static Object read(String fileName) { + + Object o = null; + try (FileInputStream fichier = new FileInputStream(fileName); + ObjectInputStream ois = new ObjectInputStream(fichier);) { + o = ois.readObject(); + } catch ( java.io.FileNotFoundException e) { + monLog.log(Level.SEVERE, "Pas de precedentes sauvegardes",e); + } catch (final java.io.IOException e) { + monLog.log(Level.SEVERE, "Pbme de fichier",e); + } catch (final ClassNotFoundException e) { + monLog.log(Level.SEVERE, "Pbme de sauvegarde, classe inattendue",e); + } + return o; + } +} \ No newline at end of file diff --git a/src/forum/Message.java b/src/forum/Message.java new file mode 100755 index 0000000..d05e5ad --- /dev/null +++ b/src/forum/Message.java @@ -0,0 +1,7 @@ +package forum; + +public class Message { + + private String contenu; + +} diff --git a/src/forum/Producteur.java b/src/forum/Producteur.java new file mode 100755 index 0000000..0a77682 --- /dev/null +++ b/src/forum/Producteur.java @@ -0,0 +1,15 @@ +package forum; + +import java.util.ArrayList; + +public class Producteur extends Administrateur { + + public String nom; + public ArrayList canal = new ArrayList (); + + public Producteur() { + super(); + // TODO Auto-generated constructor stub + } + +} diff --git a/src/forum/UserConsole.java b/src/forum/UserConsole.java new file mode 100755 index 0000000..f9ea3da --- /dev/null +++ b/src/forum/UserConsole.java @@ -0,0 +1,80 @@ +package forum; + +import java.util.List; +import java.util.Scanner; +import java.util.Set; + +public class UserConsole { + Scanner sc = new Scanner(System.in); + + public static final char COM_CREER_FORUM = 'f'; + public static final char COM_CREER_CANAL = 'c'; + public static final char COM_LIRE_MESSAGES = 'l'; + public static final char COM_POSTER_MESSAGES = 'p'; + public static final char COM_STOP = 's'; + + //On pourra modifier facilement pour par exemple utiliser des logger. + private final void sop(String s) { + System.out.println(s); + } + + public String lireCommande() { + sop("------- COMMANDES ----------"); + sop("creer Forum : " + COM_CREER_FORUM ) ; + sop("creer Canal : " + COM_CREER_CANAL); + sop("lire messages : " + COM_LIRE_MESSAGES); + sop("poster un nouveau message : " + COM_POSTER_MESSAGES); + sop("stop : " + COM_STOP); + sop("Que voulez-vous faire ?"); + String str = sc.nextLine().toLowerCase(); + sop("Vous avez saisi la commande: " + str); + return str; + } + + public void afficher(String str) { + sop(str); + } + + public void afficherMessages(List arrayList) { + int i = 1; + sop("\t messages : "); + if (arrayList == null) { + sop("\t Pas de messages "); + } else + for (Message m : arrayList) { + sop("\t" + i + "-\t" + m); + i++; + } + } + + public String getNomDuForum(Set nomsForum) { + sop("--- Forum disponibles --- "); + afficheListe(nomsForum); + sop("==> Nom du Forum ?"); + return sc.nextLine(); + } + + public void afficheListe(Set noms) { + for (String nom : noms) + sop("\t"+ nom); + } + + + public String getNomCanal(Set nomsCanaux) { + sop("--- Canals disponibles --- "); + afficheListe(nomsCanaux); + sop("==> Nom du Canal ?"); + return sc.nextLine(); + } + + + public String getValeur(String message) { + sop(message); + return sc.nextLine(); + } + + public String write(){ + return sc.nextLine(); + } + +} diff --git a/src/openClosedPrinciples/core/AlreadyBooked.java b/src/openClosedPrinciples/core/AlreadyBooked.java new file mode 100644 index 0000000..e402214 --- /dev/null +++ b/src/openClosedPrinciples/core/AlreadyBooked.java @@ -0,0 +1,18 @@ +package openClosedPrinciples.core; + +/** + * @author Mireille Blay-Fornarino + * + */ +public class AlreadyBooked extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public AlreadyBooked(String message) { + super(message); + } + +} diff --git a/src/openClosedPrinciples/core/AucunItemCorrespondant.java b/src/openClosedPrinciples/core/AucunItemCorrespondant.java new file mode 100644 index 0000000..d4adb4b --- /dev/null +++ b/src/openClosedPrinciples/core/AucunItemCorrespondant.java @@ -0,0 +1,14 @@ +package openClosedPrinciples.core; + +public class AucunItemCorrespondant extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public AucunItemCorrespondant(String message) { + super(message); + } + +} diff --git a/src/openClosedPrinciples/core/Car.java b/src/openClosedPrinciples/core/Car.java new file mode 100644 index 0000000..d831ac7 --- /dev/null +++ b/src/openClosedPrinciples/core/Car.java @@ -0,0 +1,50 @@ +package openClosedPrinciples.core; + +/** + * @author Mireille Blay-Fornarino + * + */ + +public class Car { + private String numberPlate; + private double dayPrice; + + + /// Constructeurs + + public Car(String numberPlate, double dayPrice) { + super(); + this.numberPlate = numberPlate; + this.dayPrice = dayPrice; + } + + + /// Accesseurs et mutateurs + + public String getNumberPlate() { + return numberPlate; + } + + public void setNumberPlate(String numberPlate) { + this.numberPlate = numberPlate; + } + + public double getDayPrice() { + return dayPrice; + } + + public void setDayPrice(double dayPrice) { + this.dayPrice = dayPrice; + } + + + /// Méthodes + + // Afficher + @Override + public String toString() { + return "Car [numberPlate=" + numberPlate + // ", rentals=" + rentals + + ", dayPrice=" + super.toString() + "]"; + } + +} diff --git a/src/openClosedPrinciples/core/CarRental.java b/src/openClosedPrinciples/core/CarRental.java new file mode 100644 index 0000000..ee3bcf4 --- /dev/null +++ b/src/openClosedPrinciples/core/CarRental.java @@ -0,0 +1,77 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; + +/** + * @author Mireille Blay-Fornarino + * + * 6 oct. 2018 + */ +public class CarRental extends PayingItem { + private String carNumber; + private int duration; + private LocalDate beginDate; + + + /// Constructeurs + + private CarRental(String carNumber, double dayPrice, int duration, LocalDate beginDate) { + super(dayPrice); + this.carNumber = carNumber; + this.duration = duration; + this.beginDate = beginDate; + } + + public CarRental(Car c, LocalDate beginDate, int duration) { + //On considere que le prix de la location ne doit plus bouger même si le prix de la voiture change + this(c.getNumberPlate(),c.getDayPrice(),duration,beginDate); + } + + + /// Accesseurs et mutateurs + + public String getCarNumber() { + return carNumber; + } + public void setCarNumber(String carNumber) { + this.carNumber = carNumber; + } + public int getDuration() { + return duration; + } + public void setDuration(int duration) { + this.duration = duration; + } + public LocalDate getBeginDate() { + return beginDate; + } + public void setBeginDate(LocalDate beginDate) { + this.beginDate = beginDate; + } + + + /// Méthodes + + // Récupérer le prix + public double getPrice() { + return super.price*duration; + } + + // Rechercher si dispo un jour + public boolean includeADate(LocalDate[] dates) { + for (LocalDate d : dates) { + if (d.equals(beginDate)) + return true; + if ( (d.isAfter(beginDate)) && + (d.isBefore(beginDate.plusDays(duration) ) ) ) + return true; + } + return false; + } + + // Afficher + @Override + public String toString() { + return "CarRental [carNumber=" + carNumber.toString() + ", duration=" + duration + ", beginDate=" + beginDate + ", price=" +super.toString() + "]"; + } +} diff --git a/src/openClosedPrinciples/core/CarRentalService.java b/src/openClosedPrinciples/core/CarRentalService.java new file mode 100644 index 0000000..596ae31 --- /dev/null +++ b/src/openClosedPrinciples/core/CarRentalService.java @@ -0,0 +1,77 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * @author Mireille Blay-Fornarino + * + * 6 oct. 2018 + */ +public class CarRentalService extends Service { + private ArrayList cars; + + + /// Constructeurs + + public CarRentalService(ArrayList cars) { + super(new ArrayList()); + this.cars = cars; + } + + /// Méthodes + + // Récupérer la liste des voitures dispo tel date et telle durée + public List getAvailableCars(LocalDate d, int duration) { + ArrayList availableCars = new ArrayList<>(); + LocalDate[] dates = DateTools.getDays(d, duration); + for (Car c : cars) { + if (isAvailable(c, dates)) { + availableCars.add(c); + } + } + return availableCars; + } + + // On voit si une voiture est dispo pendant ces dates + private boolean isAvailable(Car c, LocalDate[] dates) { + for (CarRental carRental : payingItemList) { + if (c.getNumberPlate().equals(carRental.getCarNumber()) && + (carRental.includeADate(dates)) ) { + return false; + } + } + return true; + } + + // On réserve une voiture + public CarRental book(Car c, LocalDate d, int duration) throws NotPossibleCarRentalException { + CarRental carRental = null; + if (cars == null || !(cars.contains(c)) ) + throw new NotPossibleCarRentalException("Not known car"); + LocalDate[] dates = DateTools.getDays(d, duration); + if (isAvailable(c, dates)) { + carRental = new CarRental(c, d, duration); + payingItemList.add(carRental); + } + return carRental; + } + + // Recherche d'une voiture correspondant à la description + public CarRental find(Description description) { + List listeVoitures = this.getAvailableCars(description.getDateDepart(), description.getDuree()); + listeVoitures.sort(Comparator.comparing(Car::getDayPrice)); + CarRental cr = null; + try{ + if(listeVoitures.isEmpty()) { + return null; + } + cr = this.book(listeVoitures.get(0), description.getDateDepart(), description.getDuree()); + }catch(NotPossibleCarRentalException e) { + e.getMessage(); + } + return cr; + } +} diff --git a/src/openClosedPrinciples/core/DateTools.java b/src/openClosedPrinciples/core/DateTools.java new file mode 100644 index 0000000..8bdc4f1 --- /dev/null +++ b/src/openClosedPrinciples/core/DateTools.java @@ -0,0 +1,37 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; + +/** + * Classe Utilitaire + * + * + * @author Mireille Blay-Fornarino + * + * + * 6 oct. 2018 + */ +public final class DateTools { + + + private DateTools() { + throw new IllegalStateException("Utility class"); + } + + public static LocalDate addDays(LocalDate date, int nbJour) { + return date.plusDays(nbJour); + } + + public static LocalDate[] getDays(LocalDate date, int nbJour) { + int i = 0; + LocalDate[] dates = new LocalDate[nbJour]; + dates[i] = date; + i+=1; + while (i < nbJour) { + dates[i] = addDays(date,i); + i++; + } + return dates; + } + +} diff --git a/src/openClosedPrinciples/core/Description.java b/src/openClosedPrinciples/core/Description.java new file mode 100644 index 0000000..e80d126 --- /dev/null +++ b/src/openClosedPrinciples/core/Description.java @@ -0,0 +1,68 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; +import java.util.Date; + +public class Description { + private String depart; + private String destination; + private LocalDate dateDepart; + private int duree; + + + /// Constructeurs + + // Vide + public Description() { + depart = null; + destination = null; + dateDepart = null; + duree = 0; + } + + // Avec tout rempli + public Description(String depart, String destination, LocalDate dateDepart, int duree) { + this.depart = depart; + this.destination = destination; + this.dateDepart = dateDepart; + this.duree = duree; + } + + + /// Accesseurs et mutateurs + + public String getDestination() { + return destination; + } + + public void setDestination(String destination) { + this.destination = destination; + } + + public String getDepart() { + return depart; + } + + public void setDepart(String depart) { + this.depart = depart; + } + + public LocalDate getDateDepart() { + return dateDepart; + } + + public void setDateDepart(LocalDate dateDepart) { + this.dateDepart = dateDepart; + } + + public int getDuree() { + return duree; + } + + public void setDuree(int duree) { + this.duree = duree; + } + + + +} diff --git a/src/openClosedPrinciples/core/Flight.java b/src/openClosedPrinciples/core/Flight.java new file mode 100644 index 0000000..c75fd21 --- /dev/null +++ b/src/openClosedPrinciples/core/Flight.java @@ -0,0 +1,92 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.Random; + +/** + * @author Mireille Blay-Fornarino + * + * 6 oct. 2018 + */ +public class Flight extends PayingItem { + private LocalDate departDate; + private String departAirport; + private String arrivalAirport; + private LocalTime departTime; + + + /// Constructeurs + + public Flight(String departAirport) { + this(-1, LocalDate.now(), LocalTime.now(), departAirport, "Paris"); + } + + public Flight(double price, LocalDate departDate, LocalTime departTime, String departAirport, String arrivalAirport) { + super(price); + this.departDate = departDate; + this.departAirport = departAirport; + this.arrivalAirport = arrivalAirport; + this.departTime= departTime; + } + + + /// Accesseurs et mutateurs + + public LocalTime getDepartTime() { + return departTime; + } + public void setDepartTime(LocalTime departTime) { + this.departTime = departTime; + } + public LocalDate getDepartDate() { + return departDate; + } + public void setDepartDate(LocalDate departDate) { + this.departDate = departDate; + } + + public String getDepartAirport() { + return departAirport; + } + public void setDepartAirport(String departAirport) { + this.departAirport = departAirport; + } + + public String getArrivalAirport() { + return arrivalAirport; + } + public void setArrivalAirport(String arrivalAirport) { + this.arrivalAirport = arrivalAirport; + } + + public void setPrice(double price) { + super.setPrice(price); + } + + public double getPrice() { + if (super.price == -1) { + double start = 10; + double end = 1000; + double random = new Random().nextDouble(); + super.setPrice(start + (random * (end - start))); + } + return super.price; + } + + + /// Méthodes + + // On voit si le vol correspond à celui entré en paramètres + public boolean match(LocalDate d, String from, String to) { + return getDepartDate().equals(d) && getDepartAirport().equals(from) && getArrivalAirport().equals(to); + } + + + // Affichage + @Override + public String toString() { + return "Flight [price=" + super.toString() + ", departDate=" + departDate + ", departAirport=" + departAirport + + ", arrivalAirport=" + arrivalAirport + ", departTime=" + departTime + "]"; + } +} diff --git a/src/openClosedPrinciples/core/FlightService.java b/src/openClosedPrinciples/core/FlightService.java new file mode 100644 index 0000000..7f1daa2 --- /dev/null +++ b/src/openClosedPrinciples/core/FlightService.java @@ -0,0 +1,50 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @author Mireille Blay-Fornarino + * + * 6 oct. 2018 + */ +public class FlightService extends Service { + + /// Constructeurs + + public FlightService(ArrayList flights) { + super(flights); + } + + + /// Méthodes + + // Récupérer les vols de cette date + public List getFlights(LocalDate d) { + Stream parallelStream = super.getpayingItemList().parallelStream(); + Stream results = parallelStream.filter(f -> (f.getDepartDate().equals(d)) ) ; + return results.collect(Collectors.toCollection(ArrayList::new)); + } + + // Récupérer les vols de cette date + lieux départ et destination + public ArrayList getFlights(LocalDate d, String from, String to) { + Stream parallelStream = super.getpayingItemList().parallelStream(); + Stream results = parallelStream.filter(f -> + f.match(d, from, to)) ; + return results.collect(Collectors.toCollection(ArrayList::new)); + } + + // Recherche d'un vol correspondant à la description + public Flight find(Description description) { + ArrayList listeVols = this.getFlights(description.getDateDepart(), description.getDepart(), description.getDestination()); + listeVols.sort(Comparator.comparing(Flight::getPrice)); + if(listeVols.isEmpty()) { + return null; + } + return listeVols.get(0); + } +} diff --git a/src/openClosedPrinciples/core/GestionnaireVoyages.java b/src/openClosedPrinciples/core/GestionnaireVoyages.java new file mode 100644 index 0000000..e8e2e89 --- /dev/null +++ b/src/openClosedPrinciples/core/GestionnaireVoyages.java @@ -0,0 +1,112 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.Month; +import java.util.ArrayList; +import java.util.Scanner; + +public class GestionnaireVoyages { + private static TravelOrganizer to = new TravelOrganizer(); + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + + //// GESTION DU VOYAGE CHOISI PAR L'UTILISATEUR + + /// On récupère le départ + System.out.println("De où partez-vous ?"); + String depart = sc.nextLine(); + + /// On récupère la destination + System.out.println("Où voulez-vous aller ?"); + String destination = sc.nextLine(); + + /// On récupère la durée du voyage + System.out.println("Combien de temps voulez-vous partir?"); + int duree = Integer.parseInt(sc.nextLine()); + + //Date (non demandée par l'utilisateur) + LocalDate ld = LocalDate.of(2019, Month.OCTOBER, 18); + + //Date pour tester + LocalDate ldr = LocalDate.of(2019, Month.JUNE, 18); + LocalTime lt = LocalTime.now(); + + //Description du voyage de l'utilisateur + Description d = new Description(depart, destination, ld, duree); + + /// GESTION DES VOLS + + // Première compagnie de vols + Flight f1 = new Flight(350, ld, lt, depart, destination); + Flight f2 = new Flight(100, ld, lt, depart, destination); // moins cher + Flight f3 = new Flight(56, ld, lt, "Cannes", destination); // n'a pas le bon départ + ArrayList flights1 = new ArrayList<>(); + flights1.add(f1); + flights1.add(f2); + flights1.add(f3); + FlightService fs1 = new FlightService(flights1); + to.addAirlineCompany(fs1); + + // Deuxième compagnie de vols + Flight f4 = new Flight(20, ld, lt, depart, "Tokyo"); // n'a pas la bonne destination + Flight f5 = new Flight(22, ldr, lt, depart, destination); // n'a pas la bonne date + ArrayList flights2 = new ArrayList<>(); + flights2.add(f4); + flights2.add(f5); + FlightService fs2 = new FlightService(flights2); + to.addAirlineCompany(fs2); + + + + /// GESTION DES LOCATIONS DE VOITURES + + // Première compagnie qui contiendra 3 voitures + Car c1 = new Car("111", 10); //sera réservée plus tard + Car c2 = new Car("222", 15); + Car c3 = new Car("333", 30); //sera réservée plus tard + ArrayList cs1 = new ArrayList<>(); + cs1.add(c1); + cs1.add(c2); + cs1.add(c3); + CarRentalService crs1 = new CarRentalService(cs1); + to.addCarRentCompany(crs1); + + // Deuxième compagnie qui contiendra 2 voitures S + Car c4 = new Car("444", 4); //voiture la moins chère, mais sera réservée plus tard + Car c5 = new Car("555", 50); + ArrayList cs2 = new ArrayList<>(); + cs2.add(c4); + cs2.add(c5); + CarRentalService crs2 = new CarRentalService(cs2); + to.addCarRentCompany(crs2); + + + try { + // On réserve 3 voitures + crs1.book(c1, ld, duree); + crs1.book(c3, ld, duree); + crs2.book(c4, ld, duree); + } catch (NotPossibleCarRentalException e) { + System.out.println(e.getMessage()); + } + + + try { + Trip voyageChoisi = to.createATrip(d); + + //Affichage du meilleur vol + System.out.println("Le meilleur vol pour partir de "+ depart +" et arriver à " + destination + + " le 18/10/2019 est : \n\t" + voyageChoisi.getItems().get(0)); + + //Affichage de la meilleure location de voiture + System.out.println("La meilleure voiture à louer pour une durée de " + duree + + " jours à partir du " + ld +" est : \n\t" + voyageChoisi.getItems().get(1)); + } catch(AucunItemCorrespondant e) { + System.out.println(e.getMessage()); + } + + + } +} diff --git a/src/openClosedPrinciples/core/NotPossibleCarRentalException.java b/src/openClosedPrinciples/core/NotPossibleCarRentalException.java new file mode 100644 index 0000000..752cb20 --- /dev/null +++ b/src/openClosedPrinciples/core/NotPossibleCarRentalException.java @@ -0,0 +1,19 @@ +package openClosedPrinciples.core; + +/** + * @author Mireille Blay-Fornarino + * + * 6 oct. 2018 + */ +public class NotPossibleCarRentalException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public NotPossibleCarRentalException(String message) { + super(message); + } + +} diff --git a/src/openClosedPrinciples/core/PayingItem.java b/src/openClosedPrinciples/core/PayingItem.java new file mode 100644 index 0000000..abf7fbd --- /dev/null +++ b/src/openClosedPrinciples/core/PayingItem.java @@ -0,0 +1,30 @@ +package openClosedPrinciples.core; + +public abstract class PayingItem { + protected double price; + + /// Constructeurs + + public PayingItem(double price) { + this.price = price; + } + + + /// Accesseurs et mutateurs + + // Méthode abstraite parce que le calcul du prix n'est pas le même pour une voiture et pour une vol + public abstract double getPrice(); + + public void setPrice(double price) { + this.price = price; + } + + + /// Méthodes + + // Affichage + @Override + public String toString() { + return "" + price; + } +} diff --git a/src/openClosedPrinciples/core/Service.java b/src/openClosedPrinciples/core/Service.java new file mode 100644 index 0000000..bc8435d --- /dev/null +++ b/src/openClosedPrinciples/core/Service.java @@ -0,0 +1,46 @@ +package openClosedPrinciples.core; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public abstract class Service{ + protected List payingItemList = new ArrayList<>(); + + /// Constructeurs + + public Service(List payingItemList) { + this.payingItemList = payingItemList; + } + + + /// Accesseur + + protected List getpayingItemList(){ + return payingItemList; + } + + + /// Méthodes + + // Trier la liste d'item par prix + public List sortedByPrice() { + payingItemList.sort(Comparator.comparing(PayingItem::getPrice)); + return payingItemList; + } + + // Récupérer l'item le moins cher + public T lessExpensiveItem(){ + sortedByPrice(); + return payingItemList.get(0); + } + + // Ajouter un item à la liste + public void add(T payingItem) { + payingItemList.add(payingItem); + } + + // Trouver + public abstract T find(Description description) throws AucunItemCorrespondant; + +} diff --git a/src/openClosedPrinciples/core/TravelOrganizer.java b/src/openClosedPrinciples/core/TravelOrganizer.java new file mode 100644 index 0000000..c02cd0f --- /dev/null +++ b/src/openClosedPrinciples/core/TravelOrganizer.java @@ -0,0 +1,99 @@ +package openClosedPrinciples.core; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.Month; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Scanner; + +public class TravelOrganizer { + List airlinesCompanies; + List carRentCompanies; + + /// Constructeurs + + public TravelOrganizer() { + airlinesCompanies = new ArrayList<>(); + carRentCompanies = new ArrayList<>(); + } + + + /// Accesseurs et mutateurs + + public List getAirlinesCompanies() { + return airlinesCompanies; + } + + public void setAirlinesCompanies(List airlinesCompanies) { + this.airlinesCompanies = airlinesCompanies; + } + + + public List getCarRentCompanies() { + return carRentCompanies; + } + + + public void setCarRentCompanies(List carRentCompanies) { + this.carRentCompanies = carRentCompanies; + } + + + /// Méthodes + + // Ajouter une compagnie aérienne + public void addAirlineCompany(FlightService company) { + airlinesCompanies.add(company); + } + + // Ajouter une compagnie de location de voitures + public void addCarRentCompany(CarRentalService company) { + carRentCompanies.add(company); + } + + // Créer un voyage + public Trip createATrip(Description description) throws AucunItemCorrespondant { + Trip t = new Trip(description); + Flight f = this.findFlight(description); + CarRental cr = this.findCar(description); + if(f!=null && cr!=null) { + t.addItem(f); + t.addItem(cr); + }else { + throw new AucunItemCorrespondant("Aucun voyage ne correspond aux critères recherchés."); + } + return t; + } + + // Recherche un vol + public Flight findFlight(Description description) throws AucunItemCorrespondant { + List flights = new ArrayList(); + for(FlightService fs : airlinesCompanies) { + Flight f = fs.find(description); + if(f != null) + flights.add(f); + } + flights.sort(Comparator.comparing(Flight::getPrice)); + if(flights.isEmpty()) { + throw new AucunItemCorrespondant("Aucun vol correspondant à votre recherche."); + } + return flights.get(0); + } + + // Recherche une voiture + public CarRental findCar(Description description) throws AucunItemCorrespondant { + List cars = new ArrayList(); + for(CarRentalService c : carRentCompanies) { + CarRental cr = c.find(description); + if(cr!=null) + cars.add(cr); + } + cars.sort(Comparator.comparing(CarRental::getPrice)); + if(cars.isEmpty()) { + throw new AucunItemCorrespondant("Aucune location de voiture correspondant à votre recherche."); + } + return cars.get(0); + } +} diff --git a/src/openClosedPrinciples/core/Trip.java b/src/openClosedPrinciples/core/Trip.java new file mode 100644 index 0000000..cc9e6a4 --- /dev/null +++ b/src/openClosedPrinciples/core/Trip.java @@ -0,0 +1,49 @@ +package openClosedPrinciples.core; + +import java.util.ArrayList; +import java.util.List; + +public class Trip { + private Description description; + private List items; + + /// Constructeurs + + // Vide + public Trip() { + description = null; + items = new ArrayList(); + } + + // Avec la description + public Trip(Description description) { + this.description = description; + items = new ArrayList(); + } + + + /// Accesseurs et mutateurs + + public Description getDescription() { + return description; + } + + public void setDescription(Description description) { + this.description = description; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + + /// Méthodes + + public void addItem(PayingItem item) { + items.add(item); + } +} diff --git a/src/td5/p1/Launch.java b/src/td5/p1/Launch.java new file mode 100644 index 0000000..21ba10c --- /dev/null +++ b/src/td5/p1/Launch.java @@ -0,0 +1,26 @@ +package td5.p1; + +import td5.p1.personnage.Orc; +import td5.p1.personnage.Tauren; + +public class Launch { + + public static void main(String[] args) { + + Tauren diablon = new Tauren("Diablon", 15); + Orc azag = new Orc("Azag", 5); + + diablon.attack(azag); + azag.attack(diablon); + + azag.setHp(15); + + System.out.println(azag.getState()); + System.out.println(diablon.getState()); + + + + } + + +} diff --git a/src/td5/p1/ModernWeaponFactory.java b/src/td5/p1/ModernWeaponFactory.java new file mode 100644 index 0000000..992bebe --- /dev/null +++ b/src/td5/p1/ModernWeaponFactory.java @@ -0,0 +1,37 @@ +package td5.p1; + +import td5.p1.arme.*; + +public class ModernWeaponFactory extends WeaponFactory { + + public ModernWeaponFactory() { + super(); + } + + public Arme createWeapon(String t, String n) { + Arme a; + switch (t) { + case "Epee": + a = new Epée(n); + break; + case "Dague": + a = new Dague(n); + break; + case "Bouclier": + a = new Bouclier(n); + break; + case "Fusil": + a = new Fusil(n); + break; + default: + a = null; + break; + } + super.ajoute(a); + return a; + } + + public Arme getWeapon(String n) { + return super.getWeapon(n); + } +} diff --git a/src/td5/p1/WeaponFactory.java b/src/td5/p1/WeaponFactory.java new file mode 100644 index 0000000..e8c0809 --- /dev/null +++ b/src/td5/p1/WeaponFactory.java @@ -0,0 +1,74 @@ +package td5.p1; + +import java.util.ArrayList; + +import td5.p1.arme.*; + +public class WeaponFactory { + + private static ArrayList l = new ArrayList(); + + public WeaponFactory() { + Arme d = new Arme("Arme1"); + l.add(d); + } + + public Arme createWeapon(String t, String n) { + Arme a; + switch (t) { + case "SWORD": + a = new Epée(n); + break; + case "DAG": + a = new Dague(n); + break; + case "SHIELD": + a = new Bouclier(n); + break; + default: + a = new Arme(n); + break; + } + l.add(a); + return a; + } + + public Arme getWeapon(String n) { + boolean trouve = false; + int i = 0; + + if (l.isEmpty()) { + return null; + } else { + while (!trouve) { + l.get(i); + if (i < l.size()) { + if (l.get(i).getNom().equals(n)) { + trouve = true; + return l.get(i); + } + i++; + } else { + return null; + } + + } + } + return null; + } + + // ========================================================================== + + public ArrayList getL() { + return l; + } + + public void setL(ArrayList l) { + this.l = l; + } + + public void ajoute(Arme a) { + l.add(a); + } + +} diff --git a/src/td5/p1/arme/Arme.java b/src/td5/p1/arme/Arme.java new file mode 100644 index 0000000..f06bce0 --- /dev/null +++ b/src/td5/p1/arme/Arme.java @@ -0,0 +1,74 @@ +package td5.p1.arme; + +public class Arme { + + private int force; + private int protection; + private String nom; + + public Arme() { + this(0, 0, null); + } + + public Arme(String n) { + this(0, 0, n); + } + + public Arme(int f, int p, String n) { + this.setForce(f); + this.setProtection(p); + this.setNom(n); + } + + @Override + public String toString() { + return this.nom; + } + + public int getForce() { + return force; + } + + public void setForce(int force) { + this.force = force; + } + + public int getProtection() { + return protection; + } + + public void setProtection(int protection) { + this.protection = protection; + } + + public String getNom() { + return nom; + } + + public void setNom(String nom) { + this.nom = nom; + } + + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Arme other = (Arme) obj; + if (force != other.force) + return false; + if (nom == null) { + if (other.nom != null) + return false; + } else if (!nom.equals(other.nom)) + return false; + if (protection != other.protection) + return false; + return true; + } + +} diff --git a/src/td5/p1/arme/Bouclier.java b/src/td5/p1/arme/Bouclier.java new file mode 100644 index 0000000..fd528a8 --- /dev/null +++ b/src/td5/p1/arme/Bouclier.java @@ -0,0 +1,14 @@ +package td5.p1.arme; + +public class Bouclier extends Arme { + + public Bouclier() { + this("Bouclier"); + } + + public Bouclier(String n) { + super(5, 20, n); + } + + +} diff --git a/src/td5/p1/arme/Dague.java b/src/td5/p1/arme/Dague.java new file mode 100644 index 0000000..499d768 --- /dev/null +++ b/src/td5/p1/arme/Dague.java @@ -0,0 +1,13 @@ +package td5.p1.arme; + +public class Dague extends Arme { + + public Dague() { + this("Dague"); + } + + public Dague(String n) { + super(20, 10, n); + } + +} diff --git a/src/td5/p1/arme/Epée.java b/src/td5/p1/arme/Epée.java new file mode 100644 index 0000000..1a7e5ed --- /dev/null +++ b/src/td5/p1/arme/Epée.java @@ -0,0 +1,13 @@ +package td5.p1.arme; + +public class Epée extends Arme { + + public Epée() { + this("Epée"); + } + + public Epée(String n) { + super(25, 5, n); + } + +} diff --git a/src/td5/p1/arme/Fusil.java b/src/td5/p1/arme/Fusil.java new file mode 100644 index 0000000..6a866ce --- /dev/null +++ b/src/td5/p1/arme/Fusil.java @@ -0,0 +1,14 @@ +package td5.p1.arme; + +public class Fusil extends Arme { + + public Fusil() { + this("Fusil"); + } + + public Fusil(String n) { + super(30, 1, n); + } + + +} diff --git a/src/td5/p1/etat/Faible.java b/src/td5/p1/etat/Faible.java new file mode 100644 index 0000000..3d7a8be --- /dev/null +++ b/src/td5/p1/etat/Faible.java @@ -0,0 +1,24 @@ +package td5.p1.etat; + +import td5.p1.personnage.Personnage; + +public class Faible extends PlayerState { + + public Faible(Personnage p) { + super(p); + } + + public void attack(Personnage p) { + int damage = player.getWeapon().getForce() - p.getWeapon().getProtection() - (1 - 1/p.getHp()); + + if(damage != 0) { + System.out.print(player.getNom() + player.vie() + " a attaqué " + p.getNom() + p.vie() + "."); + p.getDamage(damage); + System.out.println(" " + p.getNom() + " a perdu " + damage + " HP" + p.vie() + "!"); + } else { + System.out.println(player.getNom() + " a attaqué " + p.getNom() + ". " + p.getNom() + " n'a pris aucun dégats."); + } + + } + +} diff --git a/src/td5/p1/etat/Mort.java b/src/td5/p1/etat/Mort.java new file mode 100644 index 0000000..71411b0 --- /dev/null +++ b/src/td5/p1/etat/Mort.java @@ -0,0 +1,17 @@ +package td5.p1.etat; + +import td5.p1.personnage.Personnage; + +public class Mort extends PlayerState { + + public Mort(Personnage p) { + super(p); + } + + public void attack(Personnage p) { + + } + + + +} diff --git a/src/td5/p1/etat/PlayerState.java b/src/td5/p1/etat/PlayerState.java new file mode 100644 index 0000000..c10bb10 --- /dev/null +++ b/src/td5/p1/etat/PlayerState.java @@ -0,0 +1,41 @@ +package td5.p1.etat; + +import td5.p1.personnage.Personnage; + +public class PlayerState { + + protected Personnage player; + + public PlayerState(Personnage p) { + this.player = p; + } + + public void attack(Personnage p) { + + } + + public void checkState(Personnage p) { + checkAlive(p); + checkFaible(p); + checkMort(p); + } + + protected static void checkMort(Personnage p) { + if(p.getHp() <= 0 ) { + p.setState(new Mort(p)); + } + } + + protected static void checkFaible(Personnage p) { + if((p.getHp() <= 25) && (p.getHp() > 0)) { + p.setState(new Faible(p)); + } + } + + protected static void checkAlive(Personnage p) { + if(p.getHp() >= 25) { + p.setState(new Vivant(p)); + } + } + +} diff --git a/src/td5/p1/etat/Vivant.java b/src/td5/p1/etat/Vivant.java new file mode 100644 index 0000000..f5113de --- /dev/null +++ b/src/td5/p1/etat/Vivant.java @@ -0,0 +1,24 @@ +package td5.p1.etat; + +import td5.p1.personnage.Personnage; + +public class Vivant extends PlayerState { + + public Vivant(Personnage p) { + super(p); + } + + public void attack(Personnage p) { + int damage = player.getWeapon().getForce() - p.getWeapon().getProtection(); + + if(damage != 0) { + System.out.print(player.getNom() + player.vie() + " a attaqué " + p.getNom() + p.vie() + "."); + p.getDamage(damage); + System.out.println(" " + p.getNom() + " a perdu " + damage + " HP" + p.vie() + "!"); + } else { + System.out.println(player.getNom() + " a attaqué " + p.getNom() + ". " + p.getNom() + " n'a pris aucun dégats."); + } + + } + +} diff --git a/src/td5/p1/personnage/Humain.java b/src/td5/p1/personnage/Humain.java new file mode 100644 index 0000000..a3ddf9e --- /dev/null +++ b/src/td5/p1/personnage/Humain.java @@ -0,0 +1,27 @@ +package td5.p1.personnage; + +import td5.p1.arme.Epée; + +public class Humain extends Personnage { + + private String eyeColor; + + public Humain() { + this(null, null); + } + + public Humain(String n, String c) { + super(n); + this.setEyeColor(c); + super.setWeapon(new Epée()); + } + + public String getEyeColor() { + return this.eyeColor; + } + + public void setEyeColor(String eyeColor) { + this.eyeColor = eyeColor; + } + +} diff --git a/src/td5/p1/personnage/Orc.java b/src/td5/p1/personnage/Orc.java new file mode 100644 index 0000000..3060975 --- /dev/null +++ b/src/td5/p1/personnage/Orc.java @@ -0,0 +1,27 @@ +package td5.p1.personnage; + +import td5.p1.arme.Epée; + +public class Orc extends Personnage { + + private int earSize; + + public Orc() { + this(null, 0); + } + + public Orc(String n, int e) { + super(n); + this.setEarSize(e);; + super.setWeapon(new Epée()); + } + + public int getEarSize() { + return earSize; + } + + public void setEarSize(int earSize) { + this.earSize = earSize; + } + +} diff --git a/src/td5/p1/personnage/Personnage.java b/src/td5/p1/personnage/Personnage.java new file mode 100644 index 0000000..2168792 --- /dev/null +++ b/src/td5/p1/personnage/Personnage.java @@ -0,0 +1,86 @@ +package td5.p1.personnage; + +import td5.p1.arme.Arme; +import td5.p1.etat.*; + +public class Personnage { + + private int hp; + + private String nom; + private Arme weapon; + private PlayerState state = new Vivant(this); + + public Personnage() { + this("DefaultCharater"); + } + + public Personnage(String n) { + this.setNom(n); + this.setHp(100); + } + + public void attack(Personnage p) { + /** + * int damage = this.getWeapon().getForce() - p.getWeapon().getProtection(); + + if(damage != 0) { + System.out.print(this.getNom() + this.vie() + " a attaqué " + p.getNom() + p.vie() + "."); + p.getDamage(damage); + System.out.println(" " + p.getNom() + " a perdu " + damage + " HP" + p.vie() + "!"); + } else { + System.out.println(this.getNom() + " a attaqué " + p.getNom() + ". " + p.getNom() + " n'a pris aucun dégats."); + } + + */ + + + } + + public void getDamage(int a) { + this.setHp(this.hp - a); + } + + public String vie() { + return " (" + this.getHp() + "/100 HP)"; + } + + //====================================================================================================== + + public String getNom() { + return nom; + } + + public void setNom(String nom) { + this.nom = nom; + } + + public int getHp() { + return hp; + } + + public void setHp(int hp) { + this.hp = hp; + } + + public Arme getWeapon() { + return weapon; + } + + public void setWeapon(Arme weapon) { + this.weapon = weapon; + } + + public Object getArme() { + return this.getWeapon(); + } + + public PlayerState getState() { + return state; + } + + public void setState(PlayerState s) { + this.state = s; + } + +} diff --git a/src/td5/p1/personnage/Tauren.java b/src/td5/p1/personnage/Tauren.java new file mode 100644 index 0000000..59b0e02 --- /dev/null +++ b/src/td5/p1/personnage/Tauren.java @@ -0,0 +1,26 @@ +package td5.p1.personnage; + +import td5.p1.arme.Bouclier; + +public class Tauren extends Personnage { + + private int hornSize; + + public Tauren() { + this(null, 0); + } + + public Tauren(String n, int c) { + super(n); + this.setHornSize(c); + super.setWeapon(new Bouclier()); + } + + public int getHornSize() { + return hornSize; + } + + public void setHornSize(int hornSize) { + this.hornSize = hornSize; + } +} diff --git a/src/td5/p1/personnage/Troll.java b/src/td5/p1/personnage/Troll.java new file mode 100644 index 0000000..bb2eb05 --- /dev/null +++ b/src/td5/p1/personnage/Troll.java @@ -0,0 +1,26 @@ +package td5.p1.personnage; + +import td5.p1.arme.Dague; + +public class Troll extends Personnage { + + private String favouriteBeer; + + public Troll() { + this(null, null); + } + + public Troll(String n, String b) { + super(n); + this.setFavouriteBeer(b); + super.setWeapon(new Dague()); + } + + public String getFavouriteBeer() { + return favouriteBeer; + } + + public void setFavouriteBeer(String favouriteBeer) { + this.favouriteBeer = favouriteBeer; + } +} diff --git a/src/td5/p1/td5p1.png b/src/td5/p1/td5p1.png new file mode 100644 index 0000000..b863fc4 Binary files /dev/null and b/src/td5/p1/td5p1.png differ diff --git a/tests/openClosedPrinciples/core/CarRentalServiceTest.java b/tests/openClosedPrinciples/core/CarRentalServiceTest.java new file mode 100644 index 0000000..d2cec6d --- /dev/null +++ b/tests/openClosedPrinciples/core/CarRentalServiceTest.java @@ -0,0 +1,87 @@ +package openClosedPrinciples.core; + +import static org.junit.Assert.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import openClosedPrinciples.core.Car; +import openClosedPrinciples.core.CarRental; +import openClosedPrinciples.core.CarRentalService; +import openClosedPrinciples.core.NotPossibleCarRentalException; + + +public class CarRentalServiceTest { + + CarRentalService service ; + Car myCar0 = new Car("1111 AB 06",50); + Car myCar1 = new Car("1111 AB 75",100); + Car myCar2 = new Car("1111 AB 83",75); + LocalDate currentDate; + + @Before + public void setUp() throws Exception { + myCar0 = new Car("1111 AB 06",50); + myCar1 = new Car("1111 AB 75",100); + myCar2 = new Car("1111 AB 83",75); + service = new CarRentalService( new ArrayList<>(Arrays.asList(myCar0, myCar1, myCar2) ) ) ; + + } + + @Test + public void testGetAvailableCars() { + ArrayList possibleCars = + (ArrayList) service.getAvailableCars(LocalDate.of(2018,9,11), 2); + assertEquals(3, possibleCars.size()); + } + + + @Test + public void testBookAnAvalaibleCar() throws NotPossibleCarRentalException { + CarRental carRental = service.book(myCar0,LocalDate.of(2018,9,11), 2); + assertFalse(carRental==null); + List possibleCars = service.getAvailableCars(LocalDate.of(2018,9,11), 1); + assertEquals(2, possibleCars.size()); + + possibleCars = service.getAvailableCars(LocalDate.of(2018,9,12), 3); + assertEquals(2, possibleCars.size()); + + possibleCars = service.getAvailableCars(LocalDate.of(2018,9,13), 3); + assertEquals(3, possibleCars.size()); + + possibleCars = service.getAvailableCars(LocalDate.of(2018,9,9), 4); + assertEquals(2, possibleCars.size()); + + possibleCars = service.getAvailableCars(LocalDate.of(2018,9,19), 7); + assertEquals(3, possibleCars.size()); + + } + + + @Test + public void testBookANonAvalaibleCar() throws NotPossibleCarRentalException { + CarRental carRental = service.book(myCar0,LocalDate.of(2017,9,11), 2); + assertFalse(carRental==null); + carRental = service.book(myCar0,LocalDate.of(2017,9,12), 2); + assertTrue(carRental==null); + } + + @Test + public void testGetNotAvailableCars() throws NotPossibleCarRentalException { + service.book(myCar0,LocalDate.of(2017,9,11), 2); + List possibleCars = service.getAvailableCars(LocalDate.of(2017,9,11), 2); + assertEquals(2, possibleCars.size()); + possibleCars = service.getAvailableCars(LocalDate.of(2017,9,12), 2); + assertEquals(2, possibleCars.size()); + possibleCars = service.getAvailableCars(LocalDate.of(2017,9,13), 2); + assertEquals(3, possibleCars.size()); + } + + + +} diff --git a/tests/openClosedPrinciples/core/CarRentalTest.java b/tests/openClosedPrinciples/core/CarRentalTest.java new file mode 100644 index 0000000..876cad1 --- /dev/null +++ b/tests/openClosedPrinciples/core/CarRentalTest.java @@ -0,0 +1,61 @@ +package openClosedPrinciples.core; +import static org.junit.jupiter.api.Assertions.*; + +import java.time.LocalDate; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import openClosedPrinciples.core.Car; +import openClosedPrinciples.core.CarRental; +import openClosedPrinciples.core.DateTools; + + +class CarRentalTest { + + Car myCar = new Car("1111 AB 06",50); + CarRental carRental; + + @BeforeEach + public void setUp() throws Exception { + myCar = new Car("1111 AB 06",50); + } + + + @Test + public void testCarRental() { + carRental = new CarRental(myCar, LocalDate.of(2018, 8, 30), 3); + assertEquals( myCar.getDayPrice()*3, carRental.getPrice()); + } + + @Test + public void testCarRentalAvailability() { + carRental = new CarRental(myCar, LocalDate.of(2018, 8, 30), 3); + LocalDate[] dates = DateTools.getDays(LocalDate.of(2018, 8, 30), 3); + assertEquals(3, dates.length ); + dates = DateTools.getDays(LocalDate.of(2018, 8, 30), 1); + assertTrue(carRental.includeADate(dates),"date de début OK"); + + dates = DateTools.getDays(LocalDate.of(2018, 8, 29), 1); + assertFalse(carRental.includeADate(dates),"date à un jour avant"); + + dates = DateTools.getDays(LocalDate.of(2018, 9, 2), 1); + assertFalse(carRental.includeADate(dates),"date à un jour après"); + + dates = DateTools.getDays(LocalDate.of(2018, 8, 25), 10); + assertTrue(carRental.includeADate(dates),"date incluse après"); + + dates = DateTools.getDays(LocalDate.of(2018, 9, 1), 1); + assertTrue(carRental.includeADate(dates),"date incluse sur la fin"); + dates = DateTools.getDays(LocalDate.of(2018, 8, 31), 10); + assertTrue(carRental.includeADate(dates),"date incluse sur la fin"); + } + + @Test + public void testGetPrice() { + carRental = new CarRental(myCar, LocalDate.of(2017, 8, 31), 3); + assertEquals(50,myCar.getDayPrice()); + assertEquals(50*3,carRental.getPrice()); + } + +} diff --git a/tests/openClosedPrinciples/core/FlightServiceTest.java b/tests/openClosedPrinciples/core/FlightServiceTest.java new file mode 100644 index 0000000..bf0b9c6 --- /dev/null +++ b/tests/openClosedPrinciples/core/FlightServiceTest.java @@ -0,0 +1,47 @@ +package openClosedPrinciples.core; + +import static org.junit.Assert.*; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import openClosedPrinciples.core.Flight; +import openClosedPrinciples.core.FlightService; + +public class FlightServiceTest { + + FlightService service ; + @Before + public void setUp() throws Exception { + ArrayList list = new ArrayList<>(); + list.add(new Flight("Belfort")); + list.add(new Flight("Nice")); + list.add(new Flight(100, LocalDate.of(2017, 12, 24), LocalTime.of(7, 45),"Nice", "Paris")); + list.add(new Flight(150, LocalDate.of(2017, 12, 24), LocalTime.of(9, 30), "Nice", "Paris")); + list.add(new Flight(150, LocalDate.of(2017, 12, 24), LocalTime.of(18, 30), "Paris", "Nice")); + service = new FlightService(list); + } + + + @Test + public void testGetFlightsOnADivenDate() { + List flights = service.getFlights(LocalDate.now()); + assertEquals(2, flights.size()); + flights = service.getFlights(LocalDate.of(2017, 12, 24)); + assertEquals(3, flights.size()); + } + + @Test + public void testGetFlights() { + List flights = service.getFlights(LocalDate.now(),"Nice","Paris"); + assertEquals(1, flights.size()); + flights = service.getFlights(LocalDate.of(2017, 12, 24),"Nice","Paris"); + assertEquals(2, flights.size()); + } + +} diff --git a/tests/openClosedPrinciples/core/FlightTest.java b/tests/openClosedPrinciples/core/FlightTest.java new file mode 100644 index 0000000..632de4d --- /dev/null +++ b/tests/openClosedPrinciples/core/FlightTest.java @@ -0,0 +1,30 @@ +package openClosedPrinciples.core; + +import static org.junit.Assert.*; + +import java.time.LocalDate; +import java.time.LocalTime; + +import org.junit.Before; +import org.junit.Test; + +import openClosedPrinciples.core.Flight; + +public class FlightTest { + + + Flight f1 = new Flight(100, LocalDate.of(2017,11,11), LocalTime.of(7, 45),"Nice","Paris"); + @Before + public void setUp() throws Exception { + } + + + @Test + public void testGetPrice() { + assertEquals(100,f1.getPrice(),0); + f1.setPrice(-1); + assertTrue(f1.getPrice()>=10); + assertTrue(f1.getPrice()<=1000); + } + +} diff --git a/tests/td5/p1/testArmes.java b/tests/td5/p1/testArmes.java new file mode 100644 index 0000000..fb663d4 --- /dev/null +++ b/tests/td5/p1/testArmes.java @@ -0,0 +1,61 @@ +package td5.p1; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import td5.p1.arme.Arme; +import td5.p1.personnage.Orc; +import td5.p1.personnage.Personnage; +import td5.p1.personnage.Tauren; + +public class testArmes { + + @Test + public void test1() { + Tauren diablon = new Tauren("Diablon", 15); + Orc azag = new Orc("Azag", 5); + + diablon.attack(azag); + azag.attack(diablon); + assertEquals(100, azag.getHp()); + assertEquals(95, diablon.getHp()); + } + + @Test + public void test2() { + WeaponFactory wf = new WeaponFactory(); + Arme w = wf.createWeapon("SWORD", "excalibur"); + Arme w1 = wf.getWeapon("excalibur"); + assertEquals(w, w1); + Personnage azag = new Orc("Azag", 5); + try { + assertEquals(Class.forName("td5.p1.arme.Epée"), azag.getArme().getClass()); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + @Test + public void test3() { + WeaponFactory wp = new WeaponFactory(); + WeaponFactory wp2 = new ModernWeaponFactory(); + String nom = "Ref"; + int i = 0; + Arme a1 = wp.createWeapon("SWORD", nom + i); + i++; + Arme a2 = wp2.createWeapon("Dague", nom + i); + i++; + Arme a3 = wp2.createWeapon("Fusil", nom + i); + i++; + Arme a4 = wp2.createWeapon("Missil", nom + i); // Type non reconnu + assertTrue(a1 != null); + assertTrue(a2 != null); + assertTrue(a3 != null); + assertTrue(a4 == null); + assertEquals(a1, wp.getWeapon(nom + 0)); // On retrouve une arme créée par un autre + assertEquals(a3, wp.getWeapon(nom + 2)); + } + +}