From 42ccbd10413644a31a199de9000ba137e3307030 Mon Sep 17 00:00:00 2001 From: Rossi Oddet Date: Tue, 11 Apr 2017 07:26:39 +0200 Subject: [PATCH 1/9] 01-default-method --- .gitignore | 5 ++ README.md | 7 +- pom.xml | 42 ++++++++++++ src/test/java/java8/data/Account.java | 23 +++++++ src/test/java/java8/data/Data.java | 15 +++++ src/test/java/java8/data/Person.java | 51 +++++++++++++++ src/test/java/java8/ex01/Method_01_Test.java | 68 ++++++++++++++++++++ src/test/java/java8/ex02/Method_02_Test.java | 55 ++++++++++++++++ src/test/java/java8/ex03/Method_03_Test.java | 44 +++++++++++++ 9 files changed, 306 insertions(+), 4 deletions(-) create mode 100644 .gitignore create mode 100644 pom.xml create mode 100644 src/test/java/java8/data/Account.java create mode 100644 src/test/java/java8/data/Data.java create mode 100644 src/test/java/java8/data/Person.java create mode 100644 src/test/java/java8/ex01/Method_01_Test.java create mode 100644 src/test/java/java8/ex02/Method_02_Test.java create mode 100644 src/test/java/java8/ex03/Method_03_Test.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a077dd64 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.idea +*.iml +.classpath +.project +.settings \ No newline at end of file diff --git a/README.md b/README.md index 65514ae9..f7642d17 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -# Workshop Java 8 +# Méthode par défaut -Thèmes abordées : - -* Méthode par défaut (01-default-method) \ No newline at end of file +* Importer le projet Maven +* Compléter les tests unitaires \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..09008186 --- /dev/null +++ b/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + devinstitut + workshop-java8 + 1.0-SNAPSHOT + + + utf-8 + + + + + + + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + junit + junit + 4.12 + + + org.hamcrest + hamcrest-library + 1.3 + + + + \ No newline at end of file diff --git a/src/test/java/java8/data/Account.java b/src/test/java/java8/data/Account.java new file mode 100644 index 00000000..3f8c3c14 --- /dev/null +++ b/src/test/java/java8/data/Account.java @@ -0,0 +1,23 @@ +package java8.data; + +public class Account { + + private Person owner; + private Integer balance; + + public Person getOwner() { + return owner; + } + + public void setOwner(Person owner) { + this.owner = owner; + } + + public Integer getBalance() { + return balance; + } + + public void setBalance(Integer balance) { + this.balance = balance; + } +} diff --git a/src/test/java/java8/data/Data.java b/src/test/java/java8/data/Data.java new file mode 100644 index 00000000..44c0dafb --- /dev/null +++ b/src/test/java/java8/data/Data.java @@ -0,0 +1,15 @@ +package java8.data; + + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class Data { + + public static List buildPersonList(int nb) { + return IntStream.rangeClosed(1,nb) + .mapToObj(i -> new Person("first_" + i, "last_" + i, i, i % 9 == 0 ? "test": "password"+i)) + .collect(Collectors.toList()); + } +} diff --git a/src/test/java/java8/data/Person.java b/src/test/java/java8/data/Person.java new file mode 100644 index 00000000..da028d2f --- /dev/null +++ b/src/test/java/java8/data/Person.java @@ -0,0 +1,51 @@ +package java8.data; + +public class Person { + + private String firstname; + private String lastname; + private Integer age; + private String password; + + public Person() { + } + + public Person(String firstname, String lastname, Integer age, String password) { + this.firstname = firstname; + this.lastname = lastname; + this.age = age; + this.password = password; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/test/java/java8/ex01/Method_01_Test.java b/src/test/java/java8/ex01/Method_01_Test.java new file mode 100644 index 00000000..39ab95bc --- /dev/null +++ b/src/test/java/java8/ex01/Method_01_Test.java @@ -0,0 +1,68 @@ +package java8.ex01; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 01 - Méthode par défaut + */ +public class Method_01_Test { + + // tag::IDao[] + interface IDao { + List findAll(); + + // TODO créer une méthode int sumAge() + // TODO Cette méthode retourne le résultat de l'addition des ages des personnes + } + // end::IDao[] + + class DaoA implements IDao { + + List people = Data.buildPersonList(20); + + @Override + public List findAll() { + return people; + } + } + + class DaoB implements IDao { + + List people = Data.buildPersonList(100); + + @Override + public List findAll() { + return people; + } + } + + @Test + public void test_daoA_sumAge() throws Exception { + + DaoA daoA = new DaoA(); + + // TODO invoquer la méthode sumAge pour que le test soit passant + int result = 0; + + assertThat(result, is(210)); + } + + @Test + public void test_daoB_sumAge() throws Exception { + + DaoB daoB = new DaoB(); + + // TODO invoquer la méthode sumAge pour que le test soit passant + int result = 0; + + assertThat(result, is(5050)); + + } +} diff --git a/src/test/java/java8/ex02/Method_02_Test.java b/src/test/java/java8/ex02/Method_02_Test.java new file mode 100644 index 00000000..2242e651 --- /dev/null +++ b/src/test/java/java8/ex02/Method_02_Test.java @@ -0,0 +1,55 @@ +package java8.ex02; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 02 - Redéfinition + */ +public class Method_02_Test { + + // tag::IDao[] + interface IDao { + List findAll(); + + // TODO créer une méthode String format() + // TODO la méthode retourne une chaîne de la forme [ persons] + // TODO exemple de résultat : "[14 persons]", "[30 persons]" + } + // end::IDao[] + + // tag::DaoA[] + class DaoA implements IDao { + + List people = Data.buildPersonList(20); + + @Override + public List findAll() { + return people; + } + + // TODO redéfinir la méthode String format() + // TODO la méthode retourne une chaîne de la forme DaoA[ persons] + // TODO exemple de résultat : "DaoA[14 persons]", "DaoA[30 persons]" + // TODO l'implémentation réutilise la méthode format() de l'interface + + } + // end::DaoA[] + + @Test + public void test_daoA_format() throws Exception { + + DaoA daoA = new DaoA(); + + // TODO invoquer la méthode format() pour que le test soit passant + String result = null; + + assertThat(result, is("DaoA[20 persons]")); + } +} diff --git a/src/test/java/java8/ex03/Method_03_Test.java b/src/test/java/java8/ex03/Method_03_Test.java new file mode 100644 index 00000000..b3781c65 --- /dev/null +++ b/src/test/java/java8/ex03/Method_03_Test.java @@ -0,0 +1,44 @@ +package java8.ex03; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 03 - Méthode statique + */ +public class Method_03_Test { + + // tag::IDao[] + interface IDao { + List findAll(); + + // TODO créer une méthode statique IDao getDefaultInstance() + // TODO cette méthode retourne une instance de la classe DaoA + } + // end::IDao[] + + class DaoA implements IDao { + + List people = Data.buildPersonList(20); + + @Override + public List findAll() { + return people; + } + + } + + @Test + public void test_getDefaultInstance() throws Exception { + // TODO invoquer la méthode getDefaultInstance() pour que le test soit passant + IDao result = null; + + assertThat(result.findAll(), hasSize(20)); + } +} From e6d513c4e49ab13607814564f6e4eb2e338e9ab8 Mon Sep 17 00:00:00 2001 From: Rossi Oddet Date: Tue, 11 Apr 2017 07:50:27 +0200 Subject: [PATCH 2/9] 02-lambda --- src/test/java/java8/ex01/Lambda_01_Test.java | 75 ++++++++++++ src/test/java/java8/ex01/Method_01_Test.java | 68 ----------- src/test/java/java8/ex02/Lambda_02_Test.java | 63 ++++++++++ src/test/java/java8/ex02/Method_02_Test.java | 55 --------- src/test/java/java8/ex03/Lambda_03_Test.java | 47 ++++++++ src/test/java/java8/ex03/Method_03_Test.java | 44 ------- src/test/java/java8/ex04/Lambda_04_Test.java | 119 +++++++++++++++++++ 7 files changed, 304 insertions(+), 167 deletions(-) create mode 100644 src/test/java/java8/ex01/Lambda_01_Test.java delete mode 100644 src/test/java/java8/ex01/Method_01_Test.java create mode 100644 src/test/java/java8/ex02/Lambda_02_Test.java delete mode 100644 src/test/java/java8/ex02/Method_02_Test.java create mode 100644 src/test/java/java8/ex03/Lambda_03_Test.java delete mode 100644 src/test/java/java8/ex03/Method_03_Test.java create mode 100644 src/test/java/java8/ex04/Lambda_04_Test.java diff --git a/src/test/java/java8/ex01/Lambda_01_Test.java b/src/test/java/java8/ex01/Lambda_01_Test.java new file mode 100644 index 00000000..25a18947 --- /dev/null +++ b/src/test/java/java8/ex01/Lambda_01_Test.java @@ -0,0 +1,75 @@ +package java8.ex01; + +import java8.data.Data; +import java8.data.Person; + +import org.junit.Test; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.List; + +/** + * Exercice 01 - Filter + */ +public class Lambda_01_Test { + + // tag::PersonPredicate[] + interface PersonPredicate { + boolean test(Person p); + } + // end::PersonPredicate[] + + // tag::filter[] + private List filter(List persons, PersonPredicate predicate) { + // TODO implementer la méthode + return null; + } + // end::filter[] + + + // tag::test_filter_by_age[] + @Test + public void test_filter_by_age() throws Exception { + + List personList = Data.buildPersonList(100); + + // TODO result ne doit contenir que des personnes adultes (age >= 18) + List result = filter(personList, null); + + assertThat(result.size(), is(83)); + assertThat(result, everyItem(hasProperty("age", greaterThan(17)))); + } + // end::test_filter_by_age[] + + // tag::test_filter_by_firstname[] + @Test + public void test_filter_by_firstname() throws Exception { + + List personList = Data.buildPersonList(100); + + // TODO result ne doit contenir que des personnes dont le prénom est "first_10" + List result = filter(personList, null); + + assertThat(result.size(), is(1)); + assertThat(result, everyItem(hasProperty("firstname", is("first_10")))); + } + // end::test_filter_by_firstname[] + + // tag::test_filter_by_password[] + @Test + public void test_filter_by_password() throws Exception { + + List personList = Data.buildPersonList(100); + + String passwordSha512Hex = "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"; + + // TODO result ne doit contenir que les personnes dont l'age est > 49 et dont le hash du mot de passe correspond à la valeur de la variable passwordSha512Hex + // TODO Pour obtenir le hash d'un mot, utiliser la méthode DigestUtils.sha512Hex(mot) + List result = filter(personList, null); + + assertThat(result.size(), is(6)); + assertThat(result, everyItem(hasProperty("password", is("test")))); + } + // end::test_filter_by_password[] +} diff --git a/src/test/java/java8/ex01/Method_01_Test.java b/src/test/java/java8/ex01/Method_01_Test.java deleted file mode 100644 index 39ab95bc..00000000 --- a/src/test/java/java8/ex01/Method_01_Test.java +++ /dev/null @@ -1,68 +0,0 @@ -package java8.ex01; - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 01 - Méthode par défaut - */ -public class Method_01_Test { - - // tag::IDao[] - interface IDao { - List findAll(); - - // TODO créer une méthode int sumAge() - // TODO Cette méthode retourne le résultat de l'addition des ages des personnes - } - // end::IDao[] - - class DaoA implements IDao { - - List people = Data.buildPersonList(20); - - @Override - public List findAll() { - return people; - } - } - - class DaoB implements IDao { - - List people = Data.buildPersonList(100); - - @Override - public List findAll() { - return people; - } - } - - @Test - public void test_daoA_sumAge() throws Exception { - - DaoA daoA = new DaoA(); - - // TODO invoquer la méthode sumAge pour que le test soit passant - int result = 0; - - assertThat(result, is(210)); - } - - @Test - public void test_daoB_sumAge() throws Exception { - - DaoB daoB = new DaoB(); - - // TODO invoquer la méthode sumAge pour que le test soit passant - int result = 0; - - assertThat(result, is(5050)); - - } -} diff --git a/src/test/java/java8/ex02/Lambda_02_Test.java b/src/test/java/java8/ex02/Lambda_02_Test.java new file mode 100644 index 00000000..75e673a3 --- /dev/null +++ b/src/test/java/java8/ex02/Lambda_02_Test.java @@ -0,0 +1,63 @@ +package java8.ex02; + +import java8.data.Account; +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 02 - Map + */ +public class Lambda_02_Test { + + // tag::PersonToAccountMapper[] + interface PersonToAccountMapper { + Account map(Person p); + } + // end::PersonToAccountMapper[] + + // tag::map[] + private List map(List personList, PersonToAccountMapper mapper) { + // TODO implémenter la méthode + return null; + } + // end::map[] + + + // tag::test_map_person_to_account[] + @Test + public void test_map_person_to_account() throws Exception { + + List personList = Data.buildPersonList(100); + + // TODO transformer la liste de personnes en liste de comptes + // TODO tous les objets comptes ont un solde à 100 par défaut + List result = map(personList, null); + + assertThat(result, hasSize(personList.size())); + assertThat(result, everyItem(hasProperty("balance", is(100)))); + assertThat(result, everyItem(hasProperty("owner", notNullValue()))); + } + // end::test_map_person_to_account[] + + // tag::test_map_person_to_firstname[] + @Test + public void test_map_person_to_firstname() throws Exception { + + List personList = Data.buildPersonList(100); + + // TODO transformer la liste de personnes en liste de prénoms + List result = null; + + assertThat(result, hasSize(personList.size())); + assertThat(result, everyItem(instanceOf(String.class))); + assertThat(result, everyItem(startsWith("first"))); + } + // end::test_map_person_to_firstname[] +} diff --git a/src/test/java/java8/ex02/Method_02_Test.java b/src/test/java/java8/ex02/Method_02_Test.java deleted file mode 100644 index 2242e651..00000000 --- a/src/test/java/java8/ex02/Method_02_Test.java +++ /dev/null @@ -1,55 +0,0 @@ -package java8.ex02; - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 02 - Redéfinition - */ -public class Method_02_Test { - - // tag::IDao[] - interface IDao { - List findAll(); - - // TODO créer une méthode String format() - // TODO la méthode retourne une chaîne de la forme [ persons] - // TODO exemple de résultat : "[14 persons]", "[30 persons]" - } - // end::IDao[] - - // tag::DaoA[] - class DaoA implements IDao { - - List people = Data.buildPersonList(20); - - @Override - public List findAll() { - return people; - } - - // TODO redéfinir la méthode String format() - // TODO la méthode retourne une chaîne de la forme DaoA[ persons] - // TODO exemple de résultat : "DaoA[14 persons]", "DaoA[30 persons]" - // TODO l'implémentation réutilise la méthode format() de l'interface - - } - // end::DaoA[] - - @Test - public void test_daoA_format() throws Exception { - - DaoA daoA = new DaoA(); - - // TODO invoquer la méthode format() pour que le test soit passant - String result = null; - - assertThat(result, is("DaoA[20 persons]")); - } -} diff --git a/src/test/java/java8/ex03/Lambda_03_Test.java b/src/test/java/java8/ex03/Lambda_03_Test.java new file mode 100644 index 00000000..074ad2e7 --- /dev/null +++ b/src/test/java/java8/ex03/Lambda_03_Test.java @@ -0,0 +1,47 @@ +package java8.ex03; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 03 - ForEach + */ +public class Lambda_03_Test { + + // tag::PersonProcessor[] + interface PersonProcessor { + void process(Person p); + } + // end::PersonProcessor[] + + // tag::forEach[] + private void forEach(List source, PersonProcessor processor) { + // TOD0 + } + // end::forEach[] + + + // tag::test_verify_person[] + @Test + public void test_verify_person() throws Exception { + + List personList = Data.buildPersonList(100); + + // TODO vérifier qu'une personne à un prénom qui commence par first + // TODO vérifier qu'une personne à un nom qui commence par last + // TODO vérifier qu'une personne à un age > 0 + PersonProcessor verifyPerson = null; + + assertThat(verifyPerson, notNullValue()); + + forEach(personList, verifyPerson); + } + // end::test_verify_person[] + +} diff --git a/src/test/java/java8/ex03/Method_03_Test.java b/src/test/java/java8/ex03/Method_03_Test.java deleted file mode 100644 index b3781c65..00000000 --- a/src/test/java/java8/ex03/Method_03_Test.java +++ /dev/null @@ -1,44 +0,0 @@ -package java8.ex03; - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 03 - Méthode statique - */ -public class Method_03_Test { - - // tag::IDao[] - interface IDao { - List findAll(); - - // TODO créer une méthode statique IDao getDefaultInstance() - // TODO cette méthode retourne une instance de la classe DaoA - } - // end::IDao[] - - class DaoA implements IDao { - - List people = Data.buildPersonList(20); - - @Override - public List findAll() { - return people; - } - - } - - @Test - public void test_getDefaultInstance() throws Exception { - // TODO invoquer la méthode getDefaultInstance() pour que le test soit passant - IDao result = null; - - assertThat(result.findAll(), hasSize(20)); - } -} diff --git a/src/test/java/java8/ex04/Lambda_04_Test.java b/src/test/java/java8/ex04/Lambda_04_Test.java new file mode 100644 index 00000000..a6a8bdcf --- /dev/null +++ b/src/test/java/java8/ex04/Lambda_04_Test.java @@ -0,0 +1,119 @@ +package java8.ex04; + + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Exercice 04 - FuncCollection + */ +public class Lambda_04_Test { + + // tag::interfaces[] + interface GenericPredicate { + // TODO + } + + interface GenericMapper { + // TODO + } + + interface Processor { + // TODO + } + // end::interfaces[] + + // tag::FuncCollection[] + class FuncCollection { + + private Collection list = new ArrayList<>(); + + public void add(T a) { + list.add(a); + } + + public void addAll(Collection all) { + for(T el:all) { + list.add(el); + } + } + // end::FuncCollection[] + + // tag::methods[] + private FuncCollection filter(GenericPredicate predicate) { + FuncCollection result = new FuncCollection<>(); + // TODO + return result; + } + + private FuncCollection map(GenericMapper mapper) { + FuncCollection result = new FuncCollection<>(); + // TODO + return result; + } + + private void forEach(Processor processor) { + // TODO + } + // end::methods[] + + } + + + + // tag::test_filter_map_forEach[] + @Test + public void test_filter_map_forEach() throws Exception { + + List personList = Data.buildPersonList(100); + FuncCollection personFuncCollection = new FuncCollection<>(); + personFuncCollection.addAll(personList); + + personFuncCollection + // TODO filtrer, ne garder uniquement que les personnes ayant un age > 50 + .filter(null) + // TODO transformer la liste de personnes en liste de comptes. Un compte a par défaut un solde à 1000. + .map(null) + // TODO vérifier que chaque compte a un solde à 1000. + // TODO vérifier que chaque titulaire de compte a un age > 50 + .forEach(null); + } + // end::test_filter_map_forEach[] + + // tag::test_filter_map_forEach_with_vars[] + @Test + public void test_filter_map_forEach_with_vars() throws Exception { + + List personList = Data.buildPersonList(100); + FuncCollection personFuncCollection = new FuncCollection<>(); + personFuncCollection.addAll(personList); + + // TODO créer un variable filterByAge de type GenericPredicate + // TODO filtrer, ne garder uniquement que les personnes ayant un age > 50 + // ??? filterByAge = ???; + + // TODO créer un variable mapToAccount de type GenericMapper + // TODO transformer la liste de personnes en liste de comptes. Un compte a par défaut un solde à 1000. + // ??? mapToAccount = ???; + + // TODO créer un variable verifyAccount de type GenericMapper + // TODO vérifier que chaque compte a un solde à 1000. + // TODO vérifier que chaque titulaire de compte a un age > 50 + // ??? verifyAccount = ???; + + /* TODO Décommenter + personFuncCollection + .filter(filterByAge) + .map(mapToAccount) + .forEach(verifyAccount); + */ + } + // end::test_filter_map_forEach_with_vars[] + + +} From 4f78ff3a2b14d05d085e0795c6b9302b16051d59 Mon Sep 17 00:00:00 2001 From: Rossi Oddet Date: Tue, 11 Apr 2017 07:54:31 +0200 Subject: [PATCH 3/9] 03-functions --- src/test/java/java8/data/Data.java | 16 ++- .../java/java8/ex01/Function_01_Test.java | 100 +++++++++++++++ src/test/java/java8/ex01/Lambda_01_Test.java | 75 ----------- .../java/java8/ex02/Function_02_Test.java | 37 ++++++ src/test/java/java8/ex02/Lambda_02_Test.java | 63 ---------- .../java/java8/ex03/Function_03_Test.java | 41 ++++++ src/test/java/java8/ex03/Lambda_03_Test.java | 47 ------- .../java/java8/ex04/Function_04_Test.java | 79 ++++++++++++ src/test/java/java8/ex04/Lambda_04_Test.java | 119 ------------------ .../java/java8/ex05/Function_05_Test.java | 48 +++++++ .../java/java8/ex06/Function_06_Test.java | 57 +++++++++ .../java/java8/ex07/Function_07_Test.java | 48 +++++++ 12 files changed, 420 insertions(+), 310 deletions(-) create mode 100644 src/test/java/java8/ex01/Function_01_Test.java delete mode 100644 src/test/java/java8/ex01/Lambda_01_Test.java create mode 100644 src/test/java/java8/ex02/Function_02_Test.java delete mode 100644 src/test/java/java8/ex02/Lambda_02_Test.java create mode 100644 src/test/java/java8/ex03/Function_03_Test.java delete mode 100644 src/test/java/java8/ex03/Lambda_03_Test.java create mode 100644 src/test/java/java8/ex04/Function_04_Test.java delete mode 100644 src/test/java/java8/ex04/Lambda_04_Test.java create mode 100644 src/test/java/java8/ex05/Function_05_Test.java create mode 100644 src/test/java/java8/ex06/Function_06_Test.java create mode 100644 src/test/java/java8/ex07/Function_07_Test.java diff --git a/src/test/java/java8/data/Data.java b/src/test/java/java8/data/Data.java index 44c0dafb..47650175 100644 --- a/src/test/java/java8/data/Data.java +++ b/src/test/java/java8/data/Data.java @@ -1,15 +1,19 @@ package java8.data; +import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; public class Data { - public static List buildPersonList(int nb) { - return IntStream.rangeClosed(1,nb) - .mapToObj(i -> new Person("first_" + i, "last_" + i, i, i % 9 == 0 ? "test": "password"+i)) - .collect(Collectors.toList()); + public static List buildPersonList() { + return Arrays.asList( + new Person("Roger", "France", 5, "pass"), + new Person("Aline", "Deschamps", 35, "pass"), + new Person("Laurent", "Thomas", 40, "pass"), + new Person("Chevalier", "France", 19, "pass"), + new Person("Armor", "France", 25, "pass") + ); + } } diff --git a/src/test/java/java8/ex01/Function_01_Test.java b/src/test/java/java8/ex01/Function_01_Test.java new file mode 100644 index 00000000..816811a3 --- /dev/null +++ b/src/test/java/java8/ex01/Function_01_Test.java @@ -0,0 +1,100 @@ +package java8.ex01; + +import java8.data.Account; +import java8.data.Person; +import org.junit.Test; + +import java.util.function.Function; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + + +/** + * Exercice 01 - java.util.function.Function + */ +public class Function_01_Test { + + /******** PART 1 - Integer -> Person *******/ + + // tag::intToPerson[] + // TODO Compléter la définition de cette fonction + // TODO Cette fonction permet de transformer un entier en objet Person + // TODO le prenom sera de la forme "first_" + // TODO le nom sera de la forme "last_" + // TODO l'age sera de la forme "" + // TODO le mot de passe sera de la forme "pass_" + private Function intToPerson = null; + // end::intToPerson[] + + @Test + public void test_intToPerson() throws Exception { + + // TODO invoquer la fonction intToPerson avec en paramètre l'entier 10. + Person result = null; + + assertThat(result, hasProperty("firstname", is("first_10"))); + assertThat(result, hasProperty("lastname", is("last_10"))); + assertThat(result, hasProperty("age", is(10))); + assertThat(result, hasProperty("password", is("pass_10"))); + } + + /******** PART 2 - Person -> Account *******/ + + // tag::personToAccount[] + // TODO Compléter la définition de cette fonction + // TODO la propriété owner est valorisé avec la personne en paramètre + // TODO la propriété balance est valorisé à 1000 + private Function personToAccount = null; + // end::personToAccount[] + + @Test + public void test_personToAccount() throws Exception { + + Person person = new Person("Jules", "France", 10, "pass"); + + // TODO invoquer la fonction personToAccount + Account result = null; + + assertThat(result, hasProperty("owner", is(person))); + assertThat(result, hasProperty("balance", is(1000))); + } + + + /******** PART 3 - Integer -> Account avec compose *******/ + + // tag::intToAccountWithCompose[] + // TODO Compléter la définition de cette fonction + // TODO Utiliser la méthode compose pour réutiliser les fonctions intToPerson et personToAccount + private Function intToAccountWithCompose = null; + // end::intToAccountWithCompose[] + + + @Test + public void test_intToAccount_with_Compose() throws Exception { + + // TODO invoquer la fonction intToAccountWithCompose avec l'entier 10 + Account result = null; + + assertThat(result.getOwner(), hasProperty("firstname", is("first_10"))); + assertThat(result, hasProperty("balance", is(1000))); + } + + /******** PART 4 - Integer -> Account avec andThen *******/ + + // tag::intToAccountWithAndThen[] + // TODO Compléter la définition de cette fonction + // TODO Utiliser la méthode andThen pour réutiliser les fonctions intToPerson et personToAccount + private Function intToAccountWithAndThen = null; + // end::intToAccountWithAndThen[] + + @Test + public void test_intToAccount_with_AndThen() throws Exception { + + // TODO invoquer la fonction intToAccountWithAndThen avec l'entier 11 + Account result = null; + + assertThat(result.getOwner(), hasProperty("firstname", is("first_11"))); + assertThat(result, hasProperty("balance", is(1000))); + } +} diff --git a/src/test/java/java8/ex01/Lambda_01_Test.java b/src/test/java/java8/ex01/Lambda_01_Test.java deleted file mode 100644 index 25a18947..00000000 --- a/src/test/java/java8/ex01/Lambda_01_Test.java +++ /dev/null @@ -1,75 +0,0 @@ -package java8.ex01; - -import java8.data.Data; -import java8.data.Person; - -import org.junit.Test; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.List; - -/** - * Exercice 01 - Filter - */ -public class Lambda_01_Test { - - // tag::PersonPredicate[] - interface PersonPredicate { - boolean test(Person p); - } - // end::PersonPredicate[] - - // tag::filter[] - private List filter(List persons, PersonPredicate predicate) { - // TODO implementer la méthode - return null; - } - // end::filter[] - - - // tag::test_filter_by_age[] - @Test - public void test_filter_by_age() throws Exception { - - List personList = Data.buildPersonList(100); - - // TODO result ne doit contenir que des personnes adultes (age >= 18) - List result = filter(personList, null); - - assertThat(result.size(), is(83)); - assertThat(result, everyItem(hasProperty("age", greaterThan(17)))); - } - // end::test_filter_by_age[] - - // tag::test_filter_by_firstname[] - @Test - public void test_filter_by_firstname() throws Exception { - - List personList = Data.buildPersonList(100); - - // TODO result ne doit contenir que des personnes dont le prénom est "first_10" - List result = filter(personList, null); - - assertThat(result.size(), is(1)); - assertThat(result, everyItem(hasProperty("firstname", is("first_10")))); - } - // end::test_filter_by_firstname[] - - // tag::test_filter_by_password[] - @Test - public void test_filter_by_password() throws Exception { - - List personList = Data.buildPersonList(100); - - String passwordSha512Hex = "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"; - - // TODO result ne doit contenir que les personnes dont l'age est > 49 et dont le hash du mot de passe correspond à la valeur de la variable passwordSha512Hex - // TODO Pour obtenir le hash d'un mot, utiliser la méthode DigestUtils.sha512Hex(mot) - List result = filter(personList, null); - - assertThat(result.size(), is(6)); - assertThat(result, everyItem(hasProperty("password", is("test")))); - } - // end::test_filter_by_password[] -} diff --git a/src/test/java/java8/ex02/Function_02_Test.java b/src/test/java/java8/ex02/Function_02_Test.java new file mode 100644 index 00000000..5a2dcd96 --- /dev/null +++ b/src/test/java/java8/ex02/Function_02_Test.java @@ -0,0 +1,37 @@ +package java8.ex02; + +import java8.data.Account; +import java8.data.Person; +import org.junit.Test; + +import java.util.function.BiFunction; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 02 - java.util.function.BiFunction + */ +public class Function_02_Test { + + // tag::buildAccount[] + // TODO Compléter la fonction buildAccount + // TODO la fonction possède 2 paramètres en entrée : une personne et un solde + BiFunction buildAccount = null; + // end::buildAccount[] + + @Test + public void test_build_account() throws Exception { + + // TODO invoquer la fonction buildAccount pour que le test soit passant + Account account = null; + + assertThat(account, hasProperty("balance", is(500))); + assertThat(account.getOwner(), hasProperty("firstname", is("John"))); + assertThat(account.getOwner(), hasProperty("lastname", is("France"))); + assertThat(account.getOwner(), hasProperty("age", is(80))); + assertThat(account.getOwner(), hasProperty("password", is("pass"))); + } + + +} diff --git a/src/test/java/java8/ex02/Lambda_02_Test.java b/src/test/java/java8/ex02/Lambda_02_Test.java deleted file mode 100644 index 75e673a3..00000000 --- a/src/test/java/java8/ex02/Lambda_02_Test.java +++ /dev/null @@ -1,63 +0,0 @@ -package java8.ex02; - -import java8.data.Account; -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 02 - Map - */ -public class Lambda_02_Test { - - // tag::PersonToAccountMapper[] - interface PersonToAccountMapper { - Account map(Person p); - } - // end::PersonToAccountMapper[] - - // tag::map[] - private List map(List personList, PersonToAccountMapper mapper) { - // TODO implémenter la méthode - return null; - } - // end::map[] - - - // tag::test_map_person_to_account[] - @Test - public void test_map_person_to_account() throws Exception { - - List personList = Data.buildPersonList(100); - - // TODO transformer la liste de personnes en liste de comptes - // TODO tous les objets comptes ont un solde à 100 par défaut - List result = map(personList, null); - - assertThat(result, hasSize(personList.size())); - assertThat(result, everyItem(hasProperty("balance", is(100)))); - assertThat(result, everyItem(hasProperty("owner", notNullValue()))); - } - // end::test_map_person_to_account[] - - // tag::test_map_person_to_firstname[] - @Test - public void test_map_person_to_firstname() throws Exception { - - List personList = Data.buildPersonList(100); - - // TODO transformer la liste de personnes en liste de prénoms - List result = null; - - assertThat(result, hasSize(personList.size())); - assertThat(result, everyItem(instanceOf(String.class))); - assertThat(result, everyItem(startsWith("first"))); - } - // end::test_map_person_to_firstname[] -} diff --git a/src/test/java/java8/ex03/Function_03_Test.java b/src/test/java/java8/ex03/Function_03_Test.java new file mode 100644 index 00000000..5b600c23 --- /dev/null +++ b/src/test/java/java8/ex03/Function_03_Test.java @@ -0,0 +1,41 @@ +package java8.ex03; + +import java8.data.Person; +import org.junit.Test; + +import java.util.function.BinaryOperator; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 03 - java.util.function.BinaryOperator + */ +public class Function_03_Test { + + // tag::makeAChild[] + // TODO Compléter la fonction makeAChild + // TODO l'enfant possède le nom du père + // TODO l'enfant possède le prenom " " + // TODO l'age de l'enfant est 0 + // TODO le mot de passe de l'enfant est null + BinaryOperator makeAChild = null; + // end::makeAChild[] + + + @Test + public void test_makeAChild() throws Exception { + + Person father = new Person("John", "France", 25, "johndoe"); + Person mother = new Person("Aline", "Lebreton", 22, "alino"); + + // TODO compléter le test pour qu'il soit passant + Person child = null; + + assertThat(child, hasProperty("firstname", is("John Aline"))); + assertThat(child, hasProperty("lastname", is("France"))); + assertThat(child, hasProperty("age", is(0))); + assertThat(child, hasProperty("password", nullValue())); + } + +} diff --git a/src/test/java/java8/ex03/Lambda_03_Test.java b/src/test/java/java8/ex03/Lambda_03_Test.java deleted file mode 100644 index 074ad2e7..00000000 --- a/src/test/java/java8/ex03/Lambda_03_Test.java +++ /dev/null @@ -1,47 +0,0 @@ -package java8.ex03; - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 03 - ForEach - */ -public class Lambda_03_Test { - - // tag::PersonProcessor[] - interface PersonProcessor { - void process(Person p); - } - // end::PersonProcessor[] - - // tag::forEach[] - private void forEach(List source, PersonProcessor processor) { - // TOD0 - } - // end::forEach[] - - - // tag::test_verify_person[] - @Test - public void test_verify_person() throws Exception { - - List personList = Data.buildPersonList(100); - - // TODO vérifier qu'une personne à un prénom qui commence par first - // TODO vérifier qu'une personne à un nom qui commence par last - // TODO vérifier qu'une personne à un age > 0 - PersonProcessor verifyPerson = null; - - assertThat(verifyPerson, notNullValue()); - - forEach(personList, verifyPerson); - } - // end::test_verify_person[] - -} diff --git a/src/test/java/java8/ex04/Function_04_Test.java b/src/test/java/java8/ex04/Function_04_Test.java new file mode 100644 index 00000000..1348be2a --- /dev/null +++ b/src/test/java/java8/ex04/Function_04_Test.java @@ -0,0 +1,79 @@ +package java8.ex04; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 4 - java.util.function.Predicate + */ +public class Function_04_Test { + + // tag::filterMethod[] + List filter(List list, Predicate predicate) { + List result = new ArrayList<>(); + for (T el: list) { + if(predicate.test(el)) { + result.add(el); + } + } + return result; + } + // end::filterMethod[] + + // PART 1 - ADULT + + // tag::adult[] + // TODO Compléter la fonction + // TODO AGE >=18 + Predicate adult = null; + // end::adult[] + + @Test + public void test_predicate() throws Exception { + + List personList = Data.buildPersonList(); + + // TODO invoquer la méthode filter pour que le test soit passant + List result = null; + + assertThat(result, hasSize(4)); + + } + + // PART 2 - ADULT AND LASTNAME=France AND FIRSTNAME=Armor + + // tag::predicateand[] + // TODO compléter la fonction + // TODO le prédicat vérifie que le nom est "France" + Predicate lastnameIsFrance = p -> p.getLastname().equals("France"); + + + // TODO compléter la fonction + // TODO le prédicat vérifie que le prénom est "Armor" + Predicate firstnameIsArmor = p -> p.getFirstname().equals("Armor"); + // end::predicateand[] + + @Test + public void test_predicate_and() throws Exception { + + List personList = Data.buildPersonList(); + + // TODO invoquer la méthode filter pour que le test soit passant + // TODO chaîner les prédicats adult, lastnameIsFrance et firstnameIsArmor avec la méthode and + List result = null; + + assertThat(result, hasSize(1)); + assertThat(result.get(0), hasProperty("firstname", is("Armor"))); + assertThat(result.get(0), hasProperty("lastname", is("France"))); + assertThat(result.get(0), hasProperty("age", is(25))); + + } +} diff --git a/src/test/java/java8/ex04/Lambda_04_Test.java b/src/test/java/java8/ex04/Lambda_04_Test.java deleted file mode 100644 index a6a8bdcf..00000000 --- a/src/test/java/java8/ex04/Lambda_04_Test.java +++ /dev/null @@ -1,119 +0,0 @@ -package java8.ex04; - - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Exercice 04 - FuncCollection - */ -public class Lambda_04_Test { - - // tag::interfaces[] - interface GenericPredicate { - // TODO - } - - interface GenericMapper { - // TODO - } - - interface Processor { - // TODO - } - // end::interfaces[] - - // tag::FuncCollection[] - class FuncCollection { - - private Collection list = new ArrayList<>(); - - public void add(T a) { - list.add(a); - } - - public void addAll(Collection all) { - for(T el:all) { - list.add(el); - } - } - // end::FuncCollection[] - - // tag::methods[] - private FuncCollection filter(GenericPredicate predicate) { - FuncCollection result = new FuncCollection<>(); - // TODO - return result; - } - - private FuncCollection map(GenericMapper mapper) { - FuncCollection result = new FuncCollection<>(); - // TODO - return result; - } - - private void forEach(Processor processor) { - // TODO - } - // end::methods[] - - } - - - - // tag::test_filter_map_forEach[] - @Test - public void test_filter_map_forEach() throws Exception { - - List personList = Data.buildPersonList(100); - FuncCollection personFuncCollection = new FuncCollection<>(); - personFuncCollection.addAll(personList); - - personFuncCollection - // TODO filtrer, ne garder uniquement que les personnes ayant un age > 50 - .filter(null) - // TODO transformer la liste de personnes en liste de comptes. Un compte a par défaut un solde à 1000. - .map(null) - // TODO vérifier que chaque compte a un solde à 1000. - // TODO vérifier que chaque titulaire de compte a un age > 50 - .forEach(null); - } - // end::test_filter_map_forEach[] - - // tag::test_filter_map_forEach_with_vars[] - @Test - public void test_filter_map_forEach_with_vars() throws Exception { - - List personList = Data.buildPersonList(100); - FuncCollection personFuncCollection = new FuncCollection<>(); - personFuncCollection.addAll(personList); - - // TODO créer un variable filterByAge de type GenericPredicate - // TODO filtrer, ne garder uniquement que les personnes ayant un age > 50 - // ??? filterByAge = ???; - - // TODO créer un variable mapToAccount de type GenericMapper - // TODO transformer la liste de personnes en liste de comptes. Un compte a par défaut un solde à 1000. - // ??? mapToAccount = ???; - - // TODO créer un variable verifyAccount de type GenericMapper - // TODO vérifier que chaque compte a un solde à 1000. - // TODO vérifier que chaque titulaire de compte a un age > 50 - // ??? verifyAccount = ???; - - /* TODO Décommenter - personFuncCollection - .filter(filterByAge) - .map(mapToAccount) - .forEach(verifyAccount); - */ - } - // end::test_filter_map_forEach_with_vars[] - - -} diff --git a/src/test/java/java8/ex05/Function_05_Test.java b/src/test/java/java8/ex05/Function_05_Test.java new file mode 100644 index 00000000..8aace75e --- /dev/null +++ b/src/test/java/java8/ex05/Function_05_Test.java @@ -0,0 +1,48 @@ +package java8.ex05; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.List; +import java.util.function.Consumer; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 5 - java.util.function.Consumer + */ +public class Function_05_Test { + + //tag::functions[] + // TODO compléter la fonction + // TODO modifier le mot de passe en "secret" + Consumer changePasswordToSecret = null; + + // TODO compléter la fonction + // TODO vérifier que l'age > 4 avec une assertion JUnit + Consumer verifyAge = null; + + // TODO compléter la fonction + // TODO vérifier que le mot de passe est "secret" avec une assertion JUnit + Consumer verifyPassword = null; + //end::functions[] + + + @Test + public void test_consumer() throws Exception { + List personList = Data.buildPersonList(); + + // TODO invoquer la méthode personList.forEach pour modifier les mots de passe en "secret" + // personList.forEach... + + // TODO remplacer la boucle for par l'invocation de la méthode forEach + // TODO Utiliser la méthode andThen pour chaîner les vérifications verifyAge et verifyPassword + // personList.forEach... + for(Person p : personList) { + verifyAge.accept(p); + verifyPassword.accept(p); + } + } +} diff --git a/src/test/java/java8/ex06/Function_06_Test.java b/src/test/java/java8/ex06/Function_06_Test.java new file mode 100644 index 00000000..404ebf95 --- /dev/null +++ b/src/test/java/java8/ex06/Function_06_Test.java @@ -0,0 +1,57 @@ +package java8.ex06; + + +import java8.data.Data; +import java8.data.Person; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.List; +import java.util.Objects; +import java.util.function.Supplier; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 06 - java.util.function.Supplier + */ +public class Function_06_Test { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + // tag::formatAge[] + // TODO compléter la méthode + // TODO la méthode retourne une chaîne de caractères de la forme [age=] (exemple : [age=12]) + String formatAge(Supplier supplier) { + // TODO + return null; + } + // end::formatAge[] + + + @Test + public void test_supplier_formatAge() throws Exception { + // TODO compléter le test unitaire pour qu'il soit passant + String result = formatAge(null); + + assertThat(result, is("[age=35]")); + } + + @Test + public void test_supplier_requireNonNull() throws Exception { + + expectedException.expect(NullPointerException.class); + expectedException.expectMessage("require non null object"); + + // TODO compléter le test unitaire pour qu'il soit passant + Supplier supplier = null; + + // Avec un paramètre null, cette méthode déclenche un NullPointerException + Objects.requireNonNull(null, supplier); + + } + +} diff --git a/src/test/java/java8/ex07/Function_07_Test.java b/src/test/java/java8/ex07/Function_07_Test.java new file mode 100644 index 00000000..282a9a5b --- /dev/null +++ b/src/test/java/java8/ex07/Function_07_Test.java @@ -0,0 +1,48 @@ +package java8.ex07; + +import org.junit.Test; + +import java.util.function.IntBinaryOperator; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 07 - java.util.function.IntBinaryOperator + */ +public class Function_07_Test { + + // tag::format[] + // TODO compléter la méthode pour qu'elle renvoie une chaîne de caractères de la forme "()=" + // TODO ex. "(10+11)=21", "(5-2)=3" + String format(int nb1, int nb2, String symbol, IntBinaryOperator operator) { + // TODO + return null; + } + // end::format[] + + // TODO définir sum pour que le test test_format_sum() soit passant + IntBinaryOperator sum = null; + + @Test + public void test_format_sum() throws Exception { + + String result = format(12, 13, "+", sum); + + assertThat(result, is("(12+13)=25")); + } + + // TODO définir substract afin que le test test_format_subtract() soit passant + IntBinaryOperator substract = null; + + @Test + public void test_format_subtract() throws Exception { + + String result = format(2, 3, "-", substract); + + assertThat(result, is("(2-3)=-1")); + } +} + + + From ca3031c318f29c044714fd054a8854a11e1803f8 Mon Sep 17 00:00:00 2001 From: Rossi Oddet Date: Tue, 11 Apr 2017 07:57:16 +0200 Subject: [PATCH 4/9] 04-optional --- README.md | 4 - src/test/java/java8/data/Data.java | 16 ++- .../java/java8/ex01/Function_01_Test.java | 100 ----------------- .../java/java8/ex01/Optional_01_Test.java | 101 ++++++++++++++++++ .../java/java8/ex02/Function_02_Test.java | 37 ------- .../java/java8/ex02/Optional_02_Test.java | 73 +++++++++++++ .../java/java8/ex03/Function_03_Test.java | 41 ------- .../java/java8/ex03/Optional_03_Test.java | 77 +++++++++++++ .../java/java8/ex04/Function_04_Test.java | 79 -------------- .../java/java8/ex05/Function_05_Test.java | 48 --------- .../java/java8/ex06/Function_06_Test.java | 57 ---------- .../java/java8/ex07/Function_07_Test.java | 48 --------- 12 files changed, 257 insertions(+), 424 deletions(-) delete mode 100644 README.md delete mode 100644 src/test/java/java8/ex01/Function_01_Test.java create mode 100644 src/test/java/java8/ex01/Optional_01_Test.java delete mode 100644 src/test/java/java8/ex02/Function_02_Test.java create mode 100644 src/test/java/java8/ex02/Optional_02_Test.java delete mode 100644 src/test/java/java8/ex03/Function_03_Test.java create mode 100644 src/test/java/java8/ex03/Optional_03_Test.java delete mode 100644 src/test/java/java8/ex04/Function_04_Test.java delete mode 100644 src/test/java/java8/ex05/Function_05_Test.java delete mode 100644 src/test/java/java8/ex06/Function_06_Test.java delete mode 100644 src/test/java/java8/ex07/Function_07_Test.java diff --git a/README.md b/README.md deleted file mode 100644 index f7642d17..00000000 --- a/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Méthode par défaut - -* Importer le projet Maven -* Compléter les tests unitaires \ No newline at end of file diff --git a/src/test/java/java8/data/Data.java b/src/test/java/java8/data/Data.java index 47650175..44c0dafb 100644 --- a/src/test/java/java8/data/Data.java +++ b/src/test/java/java8/data/Data.java @@ -1,19 +1,15 @@ package java8.data; -import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; public class Data { - public static List buildPersonList() { - return Arrays.asList( - new Person("Roger", "France", 5, "pass"), - new Person("Aline", "Deschamps", 35, "pass"), - new Person("Laurent", "Thomas", 40, "pass"), - new Person("Chevalier", "France", 19, "pass"), - new Person("Armor", "France", 25, "pass") - ); - + public static List buildPersonList(int nb) { + return IntStream.rangeClosed(1,nb) + .mapToObj(i -> new Person("first_" + i, "last_" + i, i, i % 9 == 0 ? "test": "password"+i)) + .collect(Collectors.toList()); } } diff --git a/src/test/java/java8/ex01/Function_01_Test.java b/src/test/java/java8/ex01/Function_01_Test.java deleted file mode 100644 index 816811a3..00000000 --- a/src/test/java/java8/ex01/Function_01_Test.java +++ /dev/null @@ -1,100 +0,0 @@ -package java8.ex01; - -import java8.data.Account; -import java8.data.Person; -import org.junit.Test; - -import java.util.function.Function; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - - -/** - * Exercice 01 - java.util.function.Function - */ -public class Function_01_Test { - - /******** PART 1 - Integer -> Person *******/ - - // tag::intToPerson[] - // TODO Compléter la définition de cette fonction - // TODO Cette fonction permet de transformer un entier en objet Person - // TODO le prenom sera de la forme "first_" - // TODO le nom sera de la forme "last_" - // TODO l'age sera de la forme "" - // TODO le mot de passe sera de la forme "pass_" - private Function intToPerson = null; - // end::intToPerson[] - - @Test - public void test_intToPerson() throws Exception { - - // TODO invoquer la fonction intToPerson avec en paramètre l'entier 10. - Person result = null; - - assertThat(result, hasProperty("firstname", is("first_10"))); - assertThat(result, hasProperty("lastname", is("last_10"))); - assertThat(result, hasProperty("age", is(10))); - assertThat(result, hasProperty("password", is("pass_10"))); - } - - /******** PART 2 - Person -> Account *******/ - - // tag::personToAccount[] - // TODO Compléter la définition de cette fonction - // TODO la propriété owner est valorisé avec la personne en paramètre - // TODO la propriété balance est valorisé à 1000 - private Function personToAccount = null; - // end::personToAccount[] - - @Test - public void test_personToAccount() throws Exception { - - Person person = new Person("Jules", "France", 10, "pass"); - - // TODO invoquer la fonction personToAccount - Account result = null; - - assertThat(result, hasProperty("owner", is(person))); - assertThat(result, hasProperty("balance", is(1000))); - } - - - /******** PART 3 - Integer -> Account avec compose *******/ - - // tag::intToAccountWithCompose[] - // TODO Compléter la définition de cette fonction - // TODO Utiliser la méthode compose pour réutiliser les fonctions intToPerson et personToAccount - private Function intToAccountWithCompose = null; - // end::intToAccountWithCompose[] - - - @Test - public void test_intToAccount_with_Compose() throws Exception { - - // TODO invoquer la fonction intToAccountWithCompose avec l'entier 10 - Account result = null; - - assertThat(result.getOwner(), hasProperty("firstname", is("first_10"))); - assertThat(result, hasProperty("balance", is(1000))); - } - - /******** PART 4 - Integer -> Account avec andThen *******/ - - // tag::intToAccountWithAndThen[] - // TODO Compléter la définition de cette fonction - // TODO Utiliser la méthode andThen pour réutiliser les fonctions intToPerson et personToAccount - private Function intToAccountWithAndThen = null; - // end::intToAccountWithAndThen[] - - @Test - public void test_intToAccount_with_AndThen() throws Exception { - - // TODO invoquer la fonction intToAccountWithAndThen avec l'entier 11 - Account result = null; - - assertThat(result.getOwner(), hasProperty("firstname", is("first_11"))); - assertThat(result, hasProperty("balance", is(1000))); - } -} diff --git a/src/test/java/java8/ex01/Optional_01_Test.java b/src/test/java/java8/ex01/Optional_01_Test.java new file mode 100644 index 00000000..6bc6454c --- /dev/null +++ b/src/test/java/java8/ex01/Optional_01_Test.java @@ -0,0 +1,101 @@ +package java8.ex01; + +import java8.data.Data; +import java8.data.Person; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 01 - Optional + */ +public class Optional_01_Test { + + class NotFountException extends RuntimeException {} + + + // tag::findMethod[] + T find(List list, Predicate predicate) { + T result = null; + + for (T p : list) { + if (predicate.test(p)) { + result = p; + break; + } + } + + return result; + } + // end::findMethod[] + + + @Test + public void test_optional_found() throws Exception { + + List personList = Data.buildPersonList(100); + + // TODO invoquer la méthode find(List list, Predicate predicate) + // TODO age == 10 + Optional result = null; + + assertThat(result, instanceOf(Optional.class)); + assertThat(result.isPresent(), is(true)); + assertThat(result.get(), instanceOf(Person.class)); + assertThat(result.get(), hasProperty("firstname", is("first_10"))); + assertThat(result.get(), hasProperty("age", is(10))); + } + + @Test + public void test_optional_notfound() throws Exception { + + + List personList = Data.buildPersonList(100); + + // TODO invoquer la méthode find(List list, Predicate predicate) + // TODO age == 400 + Optional result = null; + + assertThat(result, instanceOf(Optional.class)); + assertThat(result.isPresent(), is(false)); + } + + @Test(expected = NotFountException.class) + public void test_optional_notfound_throw_exception() throws Exception { + + + List personList = Data.buildPersonList(100); + + // TODO invoquer la méthode find(List list, Predicate predicate) + // TODO age == 10 et firstname == "last_10" + Optional result = null; + + // TODO Utiliser la méthode orElseThrow pour déclencher l'exception NotFountException si non trouvé + } + + @Test + public void test_optional_notfound_with_default_value() throws Exception { + + + List personList = Data.buildPersonList(100); + + Person defaultValue = new Person(); + defaultValue.setFirstname("DEFAULT"); + defaultValue.setLastname("DEFAULT"); + + // TODO invoquer la méthode find(List list, Predicate predicate, T defaultValue) + // TODO predicate => age == 400 + Person result = null; + + assertThat(result, notNullValue()); + assertThat(result, hasProperty("firstname", is("DEFAULT"))); + assertThat(result, hasProperty("lastname", is("DEFAULT"))); + } + + +} diff --git a/src/test/java/java8/ex02/Function_02_Test.java b/src/test/java/java8/ex02/Function_02_Test.java deleted file mode 100644 index 5a2dcd96..00000000 --- a/src/test/java/java8/ex02/Function_02_Test.java +++ /dev/null @@ -1,37 +0,0 @@ -package java8.ex02; - -import java8.data.Account; -import java8.data.Person; -import org.junit.Test; - -import java.util.function.BiFunction; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 02 - java.util.function.BiFunction - */ -public class Function_02_Test { - - // tag::buildAccount[] - // TODO Compléter la fonction buildAccount - // TODO la fonction possède 2 paramètres en entrée : une personne et un solde - BiFunction buildAccount = null; - // end::buildAccount[] - - @Test - public void test_build_account() throws Exception { - - // TODO invoquer la fonction buildAccount pour que le test soit passant - Account account = null; - - assertThat(account, hasProperty("balance", is(500))); - assertThat(account.getOwner(), hasProperty("firstname", is("John"))); - assertThat(account.getOwner(), hasProperty("lastname", is("France"))); - assertThat(account.getOwner(), hasProperty("age", is(80))); - assertThat(account.getOwner(), hasProperty("password", is("pass"))); - } - - -} diff --git a/src/test/java/java8/ex02/Optional_02_Test.java b/src/test/java/java8/ex02/Optional_02_Test.java new file mode 100644 index 00000000..2b499038 --- /dev/null +++ b/src/test/java/java8/ex02/Optional_02_Test.java @@ -0,0 +1,73 @@ +package java8.ex02; + + +import java8.data.Person; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 02 - Filter, Map + */ +public class Optional_02_Test { + + class GoodException extends RuntimeException { + } + + Predicate adult = p -> p.getAge() > 18; + Predicate aged = p -> p.getAge() > 80; + + @Test + public void test_optional_filter() throws Exception { + + Person jules = new Person("Hugues", "Jules", 30, "pass"); + + // TODO encapsuler la valeur jules dans un type Optional + // TODO utiliser la méthode "of" + Optional julesOpt = null; + + // TODO appliquer la méthode "filter" à julesOpt avec le prédicat "adult" + Optional adultPerson = null; + + // TODO appliquer la méthode "filter" à julesOpt avec le prédicat "aged" + Optional agedPerson = null; + + assertThat(adultPerson.isPresent(), is(true)); + assertThat(agedPerson.isPresent(), is(false)); + } + + @Test + public void test_optional_map() throws Exception { + Person jules = new Person("Hugues", "Jules", 30, "pass"); + + // TODO encapsuler la valeur jules dans un type Optional + // TODO utiliser la méthode "of" + Optional julesOpt = null; + + // TODO récupérer l'age de jules via la méthode "map" + Optional julesAge = null; + + assertThat(julesAge.isPresent(), is(true)); + assertThat(julesAge.get(), is(30)); + + } + + @Test(expected = GoodException.class) + public void test_optional_ifPresent() throws Exception { + Person jules = new Person("Hugues", "Jules", 30, "pass"); + + // TODO encapsuler la valeur jules dans un type Optional + // TODO utiliser la méthode "of" + Optional julesOpt = null; + + // TODO appliquer la méthode "filter" à julesOpt avec le prédicat "adult" + // TODO chaîner avec la méthode "map" pour récupérer l'age + // TODO utiliser la méthode isPresent pour vérifier que l'age est bien 30, déclencher l'exception GoodException pour valider que la fonction en paramètre de ifPresent a bien été exécutée. + // julesOpt.filter...; + } +} diff --git a/src/test/java/java8/ex03/Function_03_Test.java b/src/test/java/java8/ex03/Function_03_Test.java deleted file mode 100644 index 5b600c23..00000000 --- a/src/test/java/java8/ex03/Function_03_Test.java +++ /dev/null @@ -1,41 +0,0 @@ -package java8.ex03; - -import java8.data.Person; -import org.junit.Test; - -import java.util.function.BinaryOperator; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 03 - java.util.function.BinaryOperator - */ -public class Function_03_Test { - - // tag::makeAChild[] - // TODO Compléter la fonction makeAChild - // TODO l'enfant possède le nom du père - // TODO l'enfant possède le prenom " " - // TODO l'age de l'enfant est 0 - // TODO le mot de passe de l'enfant est null - BinaryOperator makeAChild = null; - // end::makeAChild[] - - - @Test - public void test_makeAChild() throws Exception { - - Person father = new Person("John", "France", 25, "johndoe"); - Person mother = new Person("Aline", "Lebreton", 22, "alino"); - - // TODO compléter le test pour qu'il soit passant - Person child = null; - - assertThat(child, hasProperty("firstname", is("John Aline"))); - assertThat(child, hasProperty("lastname", is("France"))); - assertThat(child, hasProperty("age", is(0))); - assertThat(child, hasProperty("password", nullValue())); - } - -} diff --git a/src/test/java/java8/ex03/Optional_03_Test.java b/src/test/java/java8/ex03/Optional_03_Test.java new file mode 100644 index 00000000..e65edbb5 --- /dev/null +++ b/src/test/java/java8/ex03/Optional_03_Test.java @@ -0,0 +1,77 @@ +package java8.ex03; + +import java8.data.Account; +import java8.data.Person; +import org.junit.Test; + +import java.util.Optional; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Exercice 03 - Navigation avec map + */ +public class Optional_03_Test { + + class GoodException extends RuntimeException { + } + + // tag::methodes[] + private Account getAccountNull() { + return null; + } + + private Account getAccountWithPersonNull() { + return new Account(); + } + + private Account getAccountWithPersonFirstnameNull() { + Account account = new Account(); + account.setOwner(new Person()); + return account; + } + + private Account getAccountWithPersonFirstnameNotNull() { + Account account = new Account(); + account.setOwner(new Person("A", "B", 19, "C")); + return account; + } + // end::methodes[] + + @Test(expected = GoodException.class) + public void test_getAccountNull() throws Exception { + Account account = getAccountNull(); + Optional accOpt = Optional.ofNullable(account); + // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) + // TODO Utiliser la méthode orElseThrow pour déclencher l'exception GoodException si non trouvé + // accOpt.map... + } + + @Test(expected = GoodException.class) + public void test_getAccountWithPersonNull() throws Exception { + Account account = getAccountWithPersonNull(); + Optional accOpt = Optional.ofNullable(account); + // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) + // TODO Utiliser la méthode orElseThrow pour déclencher l'exception GoodException si non trouvé + // accOpt.map... + } + + @Test(expected = GoodException.class) + public void test_getAccountWithPersonFirstnameNull() throws Exception { + Account account = getAccountWithPersonFirstnameNull(); + Optional accOpt = Optional.ofNullable(account); + // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) + // TODO Utiliser la méthode orElseThrow pour déclencher l'exception GoodException si non trouvé + // accOpt.map... + } + + @Test + public void test_getAccountWithPersonFirstnameNotNull() throws Exception { + Account account = getAccountWithPersonFirstnameNotNull(); + Optional accOpt = Optional.ofNullable(account); + // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) + // TODO Utiliser la méthode ifPresent pour valider que le prénom est "A" + // accOpt.map... + } +} diff --git a/src/test/java/java8/ex04/Function_04_Test.java b/src/test/java/java8/ex04/Function_04_Test.java deleted file mode 100644 index 1348be2a..00000000 --- a/src/test/java/java8/ex04/Function_04_Test.java +++ /dev/null @@ -1,79 +0,0 @@ -package java8.ex04; - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Predicate; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 4 - java.util.function.Predicate - */ -public class Function_04_Test { - - // tag::filterMethod[] - List filter(List list, Predicate predicate) { - List result = new ArrayList<>(); - for (T el: list) { - if(predicate.test(el)) { - result.add(el); - } - } - return result; - } - // end::filterMethod[] - - // PART 1 - ADULT - - // tag::adult[] - // TODO Compléter la fonction - // TODO AGE >=18 - Predicate adult = null; - // end::adult[] - - @Test - public void test_predicate() throws Exception { - - List personList = Data.buildPersonList(); - - // TODO invoquer la méthode filter pour que le test soit passant - List result = null; - - assertThat(result, hasSize(4)); - - } - - // PART 2 - ADULT AND LASTNAME=France AND FIRSTNAME=Armor - - // tag::predicateand[] - // TODO compléter la fonction - // TODO le prédicat vérifie que le nom est "France" - Predicate lastnameIsFrance = p -> p.getLastname().equals("France"); - - - // TODO compléter la fonction - // TODO le prédicat vérifie que le prénom est "Armor" - Predicate firstnameIsArmor = p -> p.getFirstname().equals("Armor"); - // end::predicateand[] - - @Test - public void test_predicate_and() throws Exception { - - List personList = Data.buildPersonList(); - - // TODO invoquer la méthode filter pour que le test soit passant - // TODO chaîner les prédicats adult, lastnameIsFrance et firstnameIsArmor avec la méthode and - List result = null; - - assertThat(result, hasSize(1)); - assertThat(result.get(0), hasProperty("firstname", is("Armor"))); - assertThat(result.get(0), hasProperty("lastname", is("France"))); - assertThat(result.get(0), hasProperty("age", is(25))); - - } -} diff --git a/src/test/java/java8/ex05/Function_05_Test.java b/src/test/java/java8/ex05/Function_05_Test.java deleted file mode 100644 index 8aace75e..00000000 --- a/src/test/java/java8/ex05/Function_05_Test.java +++ /dev/null @@ -1,48 +0,0 @@ -package java8.ex05; - -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; - -import java.util.List; -import java.util.function.Consumer; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 5 - java.util.function.Consumer - */ -public class Function_05_Test { - - //tag::functions[] - // TODO compléter la fonction - // TODO modifier le mot de passe en "secret" - Consumer changePasswordToSecret = null; - - // TODO compléter la fonction - // TODO vérifier que l'age > 4 avec une assertion JUnit - Consumer verifyAge = null; - - // TODO compléter la fonction - // TODO vérifier que le mot de passe est "secret" avec une assertion JUnit - Consumer verifyPassword = null; - //end::functions[] - - - @Test - public void test_consumer() throws Exception { - List personList = Data.buildPersonList(); - - // TODO invoquer la méthode personList.forEach pour modifier les mots de passe en "secret" - // personList.forEach... - - // TODO remplacer la boucle for par l'invocation de la méthode forEach - // TODO Utiliser la méthode andThen pour chaîner les vérifications verifyAge et verifyPassword - // personList.forEach... - for(Person p : personList) { - verifyAge.accept(p); - verifyPassword.accept(p); - } - } -} diff --git a/src/test/java/java8/ex06/Function_06_Test.java b/src/test/java/java8/ex06/Function_06_Test.java deleted file mode 100644 index 404ebf95..00000000 --- a/src/test/java/java8/ex06/Function_06_Test.java +++ /dev/null @@ -1,57 +0,0 @@ -package java8.ex06; - - -import java8.data.Data; -import java8.data.Person; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.List; -import java.util.Objects; -import java.util.function.Supplier; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 06 - java.util.function.Supplier - */ -public class Function_06_Test { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - // tag::formatAge[] - // TODO compléter la méthode - // TODO la méthode retourne une chaîne de caractères de la forme [age=] (exemple : [age=12]) - String formatAge(Supplier supplier) { - // TODO - return null; - } - // end::formatAge[] - - - @Test - public void test_supplier_formatAge() throws Exception { - // TODO compléter le test unitaire pour qu'il soit passant - String result = formatAge(null); - - assertThat(result, is("[age=35]")); - } - - @Test - public void test_supplier_requireNonNull() throws Exception { - - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("require non null object"); - - // TODO compléter le test unitaire pour qu'il soit passant - Supplier supplier = null; - - // Avec un paramètre null, cette méthode déclenche un NullPointerException - Objects.requireNonNull(null, supplier); - - } - -} diff --git a/src/test/java/java8/ex07/Function_07_Test.java b/src/test/java/java8/ex07/Function_07_Test.java deleted file mode 100644 index 282a9a5b..00000000 --- a/src/test/java/java8/ex07/Function_07_Test.java +++ /dev/null @@ -1,48 +0,0 @@ -package java8.ex07; - -import org.junit.Test; - -import java.util.function.IntBinaryOperator; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 07 - java.util.function.IntBinaryOperator - */ -public class Function_07_Test { - - // tag::format[] - // TODO compléter la méthode pour qu'elle renvoie une chaîne de caractères de la forme "()=" - // TODO ex. "(10+11)=21", "(5-2)=3" - String format(int nb1, int nb2, String symbol, IntBinaryOperator operator) { - // TODO - return null; - } - // end::format[] - - // TODO définir sum pour que le test test_format_sum() soit passant - IntBinaryOperator sum = null; - - @Test - public void test_format_sum() throws Exception { - - String result = format(12, 13, "+", sum); - - assertThat(result, is("(12+13)=25")); - } - - // TODO définir substract afin que le test test_format_subtract() soit passant - IntBinaryOperator substract = null; - - @Test - public void test_format_subtract() throws Exception { - - String result = format(2, 3, "-", substract); - - assertThat(result, is("(2-3)=-1")); - } -} - - - From a8b47510923f19887143b292f84de4d71a1c6653 Mon Sep 17 00:00:00 2001 From: ricbon35 Date: Fri, 11 Oct 2019 17:01:49 +0200 Subject: [PATCH 5/9] 04 --- .gitignore | 4 +++- pom.xml | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index a077dd64..cab1e50b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,6 @@ *.iml .classpath .project -.settings \ No newline at end of file +.settings +/target/ +/bin/ \ No newline at end of file diff --git a/pom.xml b/pom.xml index 09008186..512f24fc 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 devinstitut - workshop-java8 + java-java8 1.0-SNAPSHOT From d33212f15bb4d901155901c9a9627814fc811c73 Mon Sep 17 00:00:00 2001 From: ricbon35 Date: Fri, 11 Oct 2019 17:21:44 +0200 Subject: [PATCH 6/9] 04 --- .../java/java8/ex01/Optional_01_Test.java | 115 +++++------------- .../java/java8/ex02/Optional_02_Test.java | 73 ----------- .../java/java8/ex03/Optional_03_Test.java | 77 ------------ 3 files changed, 32 insertions(+), 233 deletions(-) delete mode 100644 src/test/java/java8/ex02/Optional_02_Test.java delete mode 100644 src/test/java/java8/ex03/Optional_03_Test.java diff --git a/src/test/java/java8/ex01/Optional_01_Test.java b/src/test/java/java8/ex01/Optional_01_Test.java index 6bc6454c..833e3bbf 100644 --- a/src/test/java/java8/ex01/Optional_01_Test.java +++ b/src/test/java/java8/ex01/Optional_01_Test.java @@ -1,101 +1,50 @@ package java8.ex01; -import java8.data.Data; -import java8.data.Person; -import org.junit.Test; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; import java.util.List; import java.util.Optional; -import java.util.function.Predicate; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import org.junit.Test; + +import java8.data.Data; +import java8.data.Person; /** - * Exercice 01 - Optional + * Exercice 02 - Filter, Map */ public class Optional_01_Test { - - class NotFountException extends RuntimeException {} - - - // tag::findMethod[] - T find(List list, Predicate predicate) { - T result = null; - - for (T p : list) { - if (predicate.test(p)) { - result = p; - break; - } - } - - return result; - } - // end::findMethod[] - + + class NotPresentException extends RuntimeException { + + } @Test - public void test_optional_found() throws Exception { - - List personList = Data.buildPersonList(100); - - // TODO invoquer la méthode find(List list, Predicate predicate) - // TODO age == 10 - Optional result = null; - - assertThat(result, instanceOf(Optional.class)); - assertThat(result.isPresent(), is(true)); - assertThat(result.get(), instanceOf(Person.class)); - assertThat(result.get(), hasProperty("firstname", is("first_10"))); - assertThat(result.get(), hasProperty("age", is(10))); + public void test_optional_ifPresent() throws Exception { + + List persons = Data.buildPersonList(100); + + // TODO rechercher dans la liste ci-dessus la 1ère personne ayant 18 ans + // TODO utiliser la méthode "findFirst" + Optional optPerson = null; + assertThat(optPerson.isPresent(), is(true)); + + // TODO afficher la personne en question si l'optional contient une personne } - @Test - public void test_optional_notfound() throws Exception { + @Test(expected=NotPresentException.class) + public void test_optional_notPresent() throws Exception { + List persons = Data.buildPersonList(50); + // TODO rechercher dans la liste ci-dessus la 1ère personne ayant 75 ans + // TODO utiliser la méthode "findFirst" + Optional optPerson = null; + assertThat(optPerson.isPresent(), is(false)); + + // TODO si la personne n'existe pas, jeter une exception NotPresentException + // TODO utiliser la méthode "orElseThrow" - List personList = Data.buildPersonList(100); - - // TODO invoquer la méthode find(List list, Predicate predicate) - // TODO age == 400 - Optional result = null; - - assertThat(result, instanceOf(Optional.class)); - assertThat(result.isPresent(), is(false)); - } - - @Test(expected = NotFountException.class) - public void test_optional_notfound_throw_exception() throws Exception { - - - List personList = Data.buildPersonList(100); - - // TODO invoquer la méthode find(List list, Predicate predicate) - // TODO age == 10 et firstname == "last_10" - Optional result = null; - - // TODO Utiliser la méthode orElseThrow pour déclencher l'exception NotFountException si non trouvé - } - - @Test - public void test_optional_notfound_with_default_value() throws Exception { - - - List personList = Data.buildPersonList(100); - - Person defaultValue = new Person(); - defaultValue.setFirstname("DEFAULT"); - defaultValue.setLastname("DEFAULT"); - - // TODO invoquer la méthode find(List list, Predicate predicate, T defaultValue) - // TODO predicate => age == 400 - Person result = null; - - assertThat(result, notNullValue()); - assertThat(result, hasProperty("firstname", is("DEFAULT"))); - assertThat(result, hasProperty("lastname", is("DEFAULT"))); } - - } diff --git a/src/test/java/java8/ex02/Optional_02_Test.java b/src/test/java/java8/ex02/Optional_02_Test.java deleted file mode 100644 index 2b499038..00000000 --- a/src/test/java/java8/ex02/Optional_02_Test.java +++ /dev/null @@ -1,73 +0,0 @@ -package java8.ex02; - - -import java8.data.Person; -import org.junit.Test; - -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 02 - Filter, Map - */ -public class Optional_02_Test { - - class GoodException extends RuntimeException { - } - - Predicate adult = p -> p.getAge() > 18; - Predicate aged = p -> p.getAge() > 80; - - @Test - public void test_optional_filter() throws Exception { - - Person jules = new Person("Hugues", "Jules", 30, "pass"); - - // TODO encapsuler la valeur jules dans un type Optional - // TODO utiliser la méthode "of" - Optional julesOpt = null; - - // TODO appliquer la méthode "filter" à julesOpt avec le prédicat "adult" - Optional adultPerson = null; - - // TODO appliquer la méthode "filter" à julesOpt avec le prédicat "aged" - Optional agedPerson = null; - - assertThat(adultPerson.isPresent(), is(true)); - assertThat(agedPerson.isPresent(), is(false)); - } - - @Test - public void test_optional_map() throws Exception { - Person jules = new Person("Hugues", "Jules", 30, "pass"); - - // TODO encapsuler la valeur jules dans un type Optional - // TODO utiliser la méthode "of" - Optional julesOpt = null; - - // TODO récupérer l'age de jules via la méthode "map" - Optional julesAge = null; - - assertThat(julesAge.isPresent(), is(true)); - assertThat(julesAge.get(), is(30)); - - } - - @Test(expected = GoodException.class) - public void test_optional_ifPresent() throws Exception { - Person jules = new Person("Hugues", "Jules", 30, "pass"); - - // TODO encapsuler la valeur jules dans un type Optional - // TODO utiliser la méthode "of" - Optional julesOpt = null; - - // TODO appliquer la méthode "filter" à julesOpt avec le prédicat "adult" - // TODO chaîner avec la méthode "map" pour récupérer l'age - // TODO utiliser la méthode isPresent pour vérifier que l'age est bien 30, déclencher l'exception GoodException pour valider que la fonction en paramètre de ifPresent a bien été exécutée. - // julesOpt.filter...; - } -} diff --git a/src/test/java/java8/ex03/Optional_03_Test.java b/src/test/java/java8/ex03/Optional_03_Test.java deleted file mode 100644 index e65edbb5..00000000 --- a/src/test/java/java8/ex03/Optional_03_Test.java +++ /dev/null @@ -1,77 +0,0 @@ -package java8.ex03; - -import java8.data.Account; -import java8.data.Person; -import org.junit.Test; - -import java.util.Optional; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * Exercice 03 - Navigation avec map - */ -public class Optional_03_Test { - - class GoodException extends RuntimeException { - } - - // tag::methodes[] - private Account getAccountNull() { - return null; - } - - private Account getAccountWithPersonNull() { - return new Account(); - } - - private Account getAccountWithPersonFirstnameNull() { - Account account = new Account(); - account.setOwner(new Person()); - return account; - } - - private Account getAccountWithPersonFirstnameNotNull() { - Account account = new Account(); - account.setOwner(new Person("A", "B", 19, "C")); - return account; - } - // end::methodes[] - - @Test(expected = GoodException.class) - public void test_getAccountNull() throws Exception { - Account account = getAccountNull(); - Optional accOpt = Optional.ofNullable(account); - // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) - // TODO Utiliser la méthode orElseThrow pour déclencher l'exception GoodException si non trouvé - // accOpt.map... - } - - @Test(expected = GoodException.class) - public void test_getAccountWithPersonNull() throws Exception { - Account account = getAccountWithPersonNull(); - Optional accOpt = Optional.ofNullable(account); - // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) - // TODO Utiliser la méthode orElseThrow pour déclencher l'exception GoodException si non trouvé - // accOpt.map... - } - - @Test(expected = GoodException.class) - public void test_getAccountWithPersonFirstnameNull() throws Exception { - Account account = getAccountWithPersonFirstnameNull(); - Optional accOpt = Optional.ofNullable(account); - // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) - // TODO Utiliser la méthode orElseThrow pour déclencher l'exception GoodException si non trouvé - // accOpt.map... - } - - @Test - public void test_getAccountWithPersonFirstnameNotNull() throws Exception { - Account account = getAccountWithPersonFirstnameNotNull(); - Optional accOpt = Optional.ofNullable(account); - // TODO A l'aide de la méthode map récupérer le prénom (account -> person -> firstname) - // TODO Utiliser la méthode ifPresent pour valider que le prénom est "A" - // accOpt.map... - } -} From cd459ab9c26056cb1fa91c7b3a2aacc3ea27088f Mon Sep 17 00:00:00 2001 From: RichardBONNAMY Date: Wed, 30 Jun 2021 15:01:26 +0200 Subject: [PATCH 7/9] Modification de la version de Java --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 512f24fc..a695be81 100644 --- a/pom.xml +++ b/pom.xml @@ -18,8 +18,8 @@ maven-compiler-plugin - 1.8 - 1.8 + 1.11 + 1.11 From e2967fbb1463f1360d7e2689e4c4383f62c20762 Mon Sep 17 00:00:00 2001 From: rbonnamy Date: Tue, 14 Feb 2023 17:48:11 +0100 Subject: [PATCH 8/9] =?UTF-8?q?Passage=20=C3=A0=20java=2017?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 6 +++--- src/test/java/{java8 => java17}/data/Account.java | 2 +- src/test/java/{java8 => java17}/data/Data.java | 2 +- src/test/java/{java8 => java17}/data/Person.java | 2 +- src/test/java/{java8 => java17}/ex01/Optional_01_Test.java | 6 +++--- 5 files changed, 9 insertions(+), 9 deletions(-) rename src/test/java/{java8 => java17}/data/Account.java (94%) rename src/test/java/{java8 => java17}/data/Data.java (94%) rename src/test/java/{java8 => java17}/data/Person.java (97%) rename src/test/java/{java8 => java17}/ex01/Optional_01_Test.java (94%) diff --git a/pom.xml b/pom.xml index a695be81..b20359bb 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 devinstitut - java-java8 + java-java17 1.0-SNAPSHOT @@ -18,8 +18,8 @@ maven-compiler-plugin - 1.11 - 1.11 + 1.17 + 1.17 diff --git a/src/test/java/java8/data/Account.java b/src/test/java/java17/data/Account.java similarity index 94% rename from src/test/java/java8/data/Account.java rename to src/test/java/java17/data/Account.java index 3f8c3c14..6b770795 100644 --- a/src/test/java/java8/data/Account.java +++ b/src/test/java/java17/data/Account.java @@ -1,4 +1,4 @@ -package java8.data; +package java17.data; public class Account { diff --git a/src/test/java/java8/data/Data.java b/src/test/java/java17/data/Data.java similarity index 94% rename from src/test/java/java8/data/Data.java rename to src/test/java/java17/data/Data.java index 44c0dafb..64c25a2c 100644 --- a/src/test/java/java8/data/Data.java +++ b/src/test/java/java17/data/Data.java @@ -1,4 +1,4 @@ -package java8.data; +package java17.data; import java.util.List; diff --git a/src/test/java/java8/data/Person.java b/src/test/java/java17/data/Person.java similarity index 97% rename from src/test/java/java8/data/Person.java rename to src/test/java/java17/data/Person.java index da028d2f..2ddc7d8b 100644 --- a/src/test/java/java8/data/Person.java +++ b/src/test/java/java17/data/Person.java @@ -1,4 +1,4 @@ -package java8.data; +package java17.data; public class Person { diff --git a/src/test/java/java8/ex01/Optional_01_Test.java b/src/test/java/java17/ex01/Optional_01_Test.java similarity index 94% rename from src/test/java/java8/ex01/Optional_01_Test.java rename to src/test/java/java17/ex01/Optional_01_Test.java index 833e3bbf..f1528e80 100644 --- a/src/test/java/java8/ex01/Optional_01_Test.java +++ b/src/test/java/java17/ex01/Optional_01_Test.java @@ -1,4 +1,4 @@ -package java8.ex01; +package java17.ex01; import static org.hamcrest.Matchers.is; @@ -9,8 +9,8 @@ import org.junit.Test; -import java8.data.Data; -import java8.data.Person; +import java17.data.Data; +import java17.data.Person; /** * Exercice 02 - Filter, Map From fa7c6ea5dfb94ee1a0e17036e2e6f9cd5a7f4517 Mon Sep 17 00:00:00 2001 From: PicToWeb Date: Sat, 8 Jun 2024 00:06:55 +0200 Subject: [PATCH 9/9] findFirst and orElseThrow NotPresentExcception --- src/test/java/java17/ex01/Optional_01_Test.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/test/java/java17/ex01/Optional_01_Test.java b/src/test/java/java17/ex01/Optional_01_Test.java index f1528e80..43d73bcf 100644 --- a/src/test/java/java17/ex01/Optional_01_Test.java +++ b/src/test/java/java17/ex01/Optional_01_Test.java @@ -4,6 +4,7 @@ import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; +import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -24,14 +25,15 @@ class NotPresentException extends RuntimeException { @Test public void test_optional_ifPresent() throws Exception { - List persons = Data.buildPersonList(100); + List persons = Data.buildPersonList(10); // TODO rechercher dans la liste ci-dessus la 1ère personne ayant 18 ans // TODO utiliser la méthode "findFirst" - Optional optPerson = null; + Optional optPerson = persons.stream().findFirst(); assertThat(optPerson.isPresent(), is(true)); // TODO afficher la personne en question si l'optional contient une personne + System.out.println(optPerson.get().getFirstname()); } @Test(expected=NotPresentException.class) @@ -40,9 +42,10 @@ public void test_optional_notPresent() throws Exception { // TODO rechercher dans la liste ci-dessus la 1ère personne ayant 75 ans // TODO utiliser la méthode "findFirst" - Optional optPerson = null; + Optional optPerson = persons.stream().filter(person->person.getAge()==75).findFirst(); assertThat(optPerson.isPresent(), is(false)); + Person person = optPerson.orElseThrow(NotPresentException::new); // TODO si la personne n'existe pas, jeter une exception NotPresentException // TODO utiliser la méthode "orElseThrow"