Java 11 migrate 7 remaining f (#1115)

* Moves facade to Java 11

* Moves factory-kit to Java 11

* Moves factory-method to Java 11

* Moves feature-toggle to Java 11

* Moves fluentinterface to Java 11

* Moves flux to Java 11

* Moves flyweight to Java 11

* Moves front-controller to Java 11

* Uses stream properly

* Resolves issues with ci
This commit is contained in:
Anurag Agarwal 2019-12-22 18:11:19 +05:30 committed by Ilkka Seppälä
parent f835d3d516
commit 670c4e43f3
55 changed files with 377 additions and 429 deletions

View File

@ -76,9 +76,7 @@ public abstract class DwarvenMineWorker {
} }
public void action(Action... actions) { public void action(Action... actions) {
for (Action action : actions) { Arrays.stream(actions).forEach(this::action);
action(action);
}
} }
public abstract void work(); public abstract void work();
@ -165,9 +163,7 @@ public class DwarvenGoldmineFacade {
private static void makeActions(Collection<DwarvenMineWorker> workers, private static void makeActions(Collection<DwarvenMineWorker> workers,
DwarvenMineWorker.Action... actions) { DwarvenMineWorker.Action... actions) {
for (DwarvenMineWorker worker : workers) { workers.forEach(worker -> worker.action(actions));
worker.action(actions);
}
} }
} }
``` ```

View File

@ -42,7 +42,7 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); var facade = new DwarvenGoldmineFacade();
facade.startNewDay(); facade.startNewDay();
facade.digOutGold(); facade.digOutGold();
facade.endDay(); facade.endDay();

View File

@ -63,8 +63,6 @@ public class DwarvenGoldmineFacade {
Collection<DwarvenMineWorker> workers, Collection<DwarvenMineWorker> workers,
DwarvenMineWorker.Action... actions DwarvenMineWorker.Action... actions
) { ) {
for (DwarvenMineWorker worker : workers) { workers.forEach(worker -> worker.action(actions));
worker.action(actions);
}
} }
} }

View File

@ -23,6 +23,7 @@
package com.iluwatar.facade; package com.iluwatar.facade;
import java.util.Arrays;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -76,9 +77,7 @@ public abstract class DwarvenMineWorker {
* Perform actions. * Perform actions.
*/ */
public void action(Action... actions) { public void action(Action... actions) {
for (Action action : actions) { Arrays.stream(actions).forEach(this::action);
action(action);
}
} }
public abstract void work(); public abstract void work();

View File

@ -26,15 +26,12 @@ package com.iluwatar.facade;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,20 +23,19 @@
package com.iluwatar.facade; package com.iluwatar.facade;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Date: 12/9/15 - 9:40 PM * Date: 12/9/15 - 9:40 PM
* *
@ -56,16 +55,16 @@ public class DwarvenGoldmineFacadeTest {
appender.stop(); appender.stop();
} }
/** /**
* Test a complete day cycle in the gold mine by executing all three different steps: {@link * Test a complete day cycle in the gold mine by executing all three different steps: {@link
* DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link * DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link
* DwarvenGoldmineFacade#endDay()}. * DwarvenGoldmineFacade#endDay()}.
* * <p>
* See if the workers are doing what's expected from them on each step. * See if the workers are doing what's expected from them on each step.
*/ */
@Test @Test
public void testFullWorkDay() { public void testFullWorkDay() {
final DwarvenGoldmineFacade goldMine = new DwarvenGoldmineFacade(); final var goldMine = new DwarvenGoldmineFacade();
goldMine.startNewDay(); goldMine.startNewDay();
// On the start of a day, all workers should wake up ... // On the start of a day, all workers should wake up ...
@ -128,7 +127,9 @@ public class DwarvenGoldmineFacadeTest {
} }
public boolean logContains(String message) { public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); return log.stream()
.map(ILoggingEvent::getFormattedMessage)
.anyMatch(message::equals);
} }
} }

View File

@ -48,13 +48,13 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
WeaponFactory factory = WeaponFactory.factory(builder -> { var factory = WeaponFactory.factory(builder -> {
builder.add(WeaponType.SWORD, Sword::new); builder.add(WeaponType.SWORD, Sword::new);
builder.add(WeaponType.AXE, Axe::new); builder.add(WeaponType.AXE, Axe::new);
builder.add(WeaponType.SPEAR, Spear::new); builder.add(WeaponType.SPEAR, Spear::new);
builder.add(WeaponType.BOW, Bow::new); builder.add(WeaponType.BOW, Bow::new);
}); });
Weapon axe = factory.create(WeaponType.AXE); var axe = factory.create(WeaponType.AXE);
LOGGER.info(axe.toString()); LOGGER.info(axe.toString());
} }
} }

View File

@ -24,7 +24,6 @@
package com.iluwatar.factorykit; package com.iluwatar.factorykit;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
@ -52,7 +51,7 @@ public interface WeaponFactory {
* @return factory with specified {@link Builder}s * @return factory with specified {@link Builder}s
*/ */
static WeaponFactory factory(Consumer<Builder> consumer) { static WeaponFactory factory(Consumer<Builder> consumer) {
Map<WeaponType, Supplier<Weapon>> map = new HashMap<>(); var map = new HashMap<WeaponType, Supplier<Weapon>>();
consumer.accept(map::put); consumer.accept(map::put);
return name -> map.get(name).get(); return name -> map.get(name).get();
} }

View File

@ -33,8 +33,7 @@ public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,6 +23,8 @@
package com.iluwatar.factorykit.factorykit; package com.iluwatar.factorykit.factorykit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.factorykit.Axe; import com.iluwatar.factorykit.Axe;
import com.iluwatar.factorykit.Spear; import com.iluwatar.factorykit.Spear;
import com.iluwatar.factorykit.Sword; import com.iluwatar.factorykit.Sword;
@ -32,10 +34,8 @@ import com.iluwatar.factorykit.WeaponType;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue; /**
* Test Factory Kit Pattern
/**
* Test Factory Kit Pattern
*/ */
public class FactoryKitTest { public class FactoryKitTest {
@ -51,30 +51,33 @@ public class FactoryKitTest {
} }
/** /**
* Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of {@link Spear} * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of
* {@link Spear}
*/ */
@Test @Test
public void testSpearWeapon() { public void testSpearWeapon() {
Weapon weapon = factory.create(WeaponType.SPEAR); var weapon = factory.create(WeaponType.SPEAR);
verifyWeapon(weapon, Spear.class); verifyWeapon(weapon, Spear.class);
} }
/** /**
* Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of {@link Axe} * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of
* {@link Axe}
*/ */
@Test @Test
public void testAxeWeapon() { public void testAxeWeapon() {
Weapon weapon = factory.create(WeaponType.AXE); var weapon = factory.create(WeaponType.AXE);
verifyWeapon(weapon, Axe.class); verifyWeapon(weapon, Axe.class);
} }
/** /**
* Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of {@link Sword} * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of
* {@link Sword}
*/ */
@Test @Test
public void testWeapon() { public void testWeapon() {
Weapon weapon = factory.create(WeaponType.SWORD); var weapon = factory.create(WeaponType.SWORD);
verifyWeapon(weapon, Sword.class); verifyWeapon(weapon, Sword.class);
} }

View File

@ -55,7 +55,7 @@ public class OrcBlacksmith implements Blacksmith {
Now as the customers come the correct type of blacksmith is summoned and requested weapons are manufactured Now as the customers come the correct type of blacksmith is summoned and requested weapons are manufactured
```java ```java
Blacksmith blacksmith = new ElfBlacksmith(); var blacksmith = new ElfBlacksmith();
blacksmith.manufactureWeapon(WeaponType.SPEAR); blacksmith.manufactureWeapon(WeaponType.SPEAR);
blacksmith.manufactureWeapon(WeaponType.AXE); blacksmith.manufactureWeapon(WeaponType.AXE);
// Elvish weapons are created // Elvish weapons are created

View File

@ -64,7 +64,7 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// Lets go to war with Orc weapons // Lets go to war with Orc weapons
App app = new App(new OrcBlacksmith()); var app = new App(new OrcBlacksmith());
app.manufactureWeapons(); app.manufactureWeapons();
// Lets go to war with Elf weapons // Lets go to war with Elf weapons
@ -73,8 +73,7 @@ public class App {
} }
private void manufactureWeapons() { private void manufactureWeapons() {
Weapon weapon; var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info(weapon.toString()); LOGGER.info(weapon.toString());
weapon = blacksmith.manufactureWeapon(WeaponType.AXE); weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info(weapon.toString()); LOGGER.info(weapon.toString());

View File

@ -23,6 +23,7 @@
package com.iluwatar.factory.method; package com.iluwatar.factory.method;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -35,14 +36,12 @@ public class ElfBlacksmith implements Blacksmith {
static { static {
ELFARSENAL = new HashMap<>(WeaponType.values().length); ELFARSENAL = new HashMap<>(WeaponType.values().length);
for (WeaponType type : WeaponType.values()) { Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAL.put(type, new ElfWeapon(type)));
ELFARSENAL.put(type, new ElfWeapon(type));
}
} }
@Override @Override
public Weapon manufactureWeapon(WeaponType weaponType) { public Weapon manufactureWeapon(WeaponType weaponType) {
return ELFARSENAL.get(weaponType); return ELFARSENAL.get(weaponType);
} }
} }

View File

@ -23,6 +23,7 @@
package com.iluwatar.factory.method; package com.iluwatar.factory.method;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -35,9 +36,7 @@ public class OrcBlacksmith implements Blacksmith {
static { static {
ORCARSENAL = new HashMap<>(WeaponType.values().length); ORCARSENAL = new HashMap<>(WeaponType.values().length);
for (WeaponType type : WeaponType.values()) { Arrays.stream(WeaponType.values()).forEach(type -> ORCARSENAL.put(type, new OrcWeapon(type)));
ORCARSENAL.put(type, new OrcWeapon(type));
}
} }
@Override @Override

View File

@ -25,15 +25,12 @@ package com.iluwatar.factory.method;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
/** /**
* Tests that Factory Method example runs without errors. * Tests that Factory Method example runs without errors.
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() throws IOException { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,79 +23,80 @@
package com.iluwatar.factory.method; package com.iluwatar.factory.method;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/** /**
* The Factory Method is a creational design pattern which uses factory methods to deal with the * The Factory Method is a creational design pattern which uses factory methods to deal with the
* problem of creating objects without specifying the exact class of object that will be created. * problem of creating objects without specifying the exact class of object that will be created.
* This is done by creating objects via calling a factory method either specified in an interface * This is done by creating objects via calling a factory method either specified in an interface
* and implemented by child classes, or implemented in a base class and optionally overridden by * and implemented by child classes, or implemented in a base class and optionally overridden by
* derived classesrather than by calling a constructor. * derived classesrather than by calling a constructor.
* *
* <p>Factory produces the object of its liking. * <p>Factory produces the object of its liking.
* The weapon {@link Weapon} manufactured by the * The weapon {@link Weapon} manufactured by the blacksmith depends on the kind of factory
* blacksmith depends on the kind of factory implementation it is referring to. * implementation it is referring to.
* </p> * </p>
*/ */
public class FactoryMethodTest { public class FactoryMethodTest {
/** /**
* Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of
* of {@link OrcWeapon}. * {@link OrcWeapon}.
*/ */
@Test @Test
public void testOrcBlacksmithWithSpear() { public void testOrcBlacksmithWithSpear() {
Blacksmith blacksmith = new OrcBlacksmith(); var blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class);
} }
/** /**
* Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance of
* of {@link OrcWeapon}. * {@link OrcWeapon}.
*/ */
@Test @Test
public void testOrcBlacksmithWithAxe() { public void testOrcBlacksmithWithAxe() {
Blacksmith blacksmith = new OrcBlacksmith(); var blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE); var weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class);
} }
/** /**
* Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an instance
* instance of {@link ElfWeapon}. * of {@link ElfWeapon}.
*/ */
@Test @Test
public void testElfBlacksmithWithShortSword() { public void testElfBlacksmithWithShortSword() {
Blacksmith blacksmith = new ElfBlacksmith(); var blacksmith = new ElfBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); var weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class);
} }
/** /**
* Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of
* of {@link ElfWeapon}. * {@link ElfWeapon}.
*/ */
@Test @Test
public void testElfBlacksmithWithSpear() { public void testElfBlacksmithWithSpear() {
Blacksmith blacksmith = new ElfBlacksmith(); var blacksmith = new ElfBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class);
} }
/** /**
* This method asserts that the weapon object that is passed is an instance of the clazz and the * This method asserts that the weapon object that is passed is an instance of the clazz and the
* weapon is of type expectedWeaponType. * weapon is of type expectedWeaponType.
* *
* @param weapon weapon object which is to be verified * @param weapon weapon object which is to be verified
* @param expectedWeaponType expected WeaponType of the weapon * @param expectedWeaponType expected WeaponType of the weapon
* @param clazz expected class of the weapon * @param clazz expected class of the weapon
*/ */
private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) { private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) {
assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName());
assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); assertEquals(expectedWeaponType, weapon
.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType);
} }
} }

View File

@ -72,33 +72,33 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
final Properties properties = new Properties(); final var properties = new Properties();
properties.put("enhancedWelcome", true); properties.put("enhancedWelcome", true);
Service service = new PropertiesFeatureToggleVersion(properties); var service = new PropertiesFeatureToggleVersion(properties);
final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
LOGGER.info(welcomeMessage); LOGGER.info(welcomeMessage);
// --------------------------------------------- // ---------------------------------------------
final Properties turnedOff = new Properties(); final var turnedOff = new Properties();
turnedOff.put("enhancedWelcome", false); turnedOff.put("enhancedWelcome", false);
Service turnedOffService = new PropertiesFeatureToggleVersion(turnedOff); var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff);
final String welcomeMessageturnedOff = final var welcomeMessageturnedOff =
turnedOffService.getWelcomeMessage(new User("Jamie No Code")); turnedOffService.getWelcomeMessage(new User("Jamie No Code"));
LOGGER.info(welcomeMessageturnedOff); LOGGER.info(welcomeMessageturnedOff);
// -------------------------------------------- // --------------------------------------------
Service service2 = new TieredFeatureToggleVersion(); var service2 = new TieredFeatureToggleVersion();
final User paidUser = new User("Jamie Coder"); final var paidUser = new User("Jamie Coder");
final User freeUser = new User("Alan Defect"); final var freeUser = new User("Alan Defect");
UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToPaidGroup(paidUser);
UserGroup.addUserToFreeGroup(freeUser); UserGroup.addUserToFreeGroup(freeUser);
final String welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser); final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser);
final String welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser); final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser);
LOGGER.info(welcomeMessageFreeUser); LOGGER.info(welcomeMessageFreeUser);
LOGGER.info(welcomeMessagePaidUser); LOGGER.info(welcomeMessagePaidUser);
} }

View File

@ -23,17 +23,15 @@
package com.iluwatar.featuretoggle.pattern.propertiesversion; package com.iluwatar.featuretoggle.pattern.propertiesversion;
import com.iluwatar.featuretoggle.pattern.Service;
import com.iluwatar.featuretoggle.user.User;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.featuretoggle.user.User;
import java.util.Properties;
import org.junit.jupiter.api.Test;
/** /**
* Test Properties Toggle * Test Properties Toggle
*/ */
@ -49,7 +47,7 @@ public class PropertiesFeatureToggleVersionTest {
@Test @Test
public void testNonBooleanProperty() { public void testNonBooleanProperty() {
assertThrows(IllegalArgumentException.class, () -> { assertThrows(IllegalArgumentException.class, () -> {
final Properties properties = new Properties(); final var properties = new Properties();
properties.setProperty("enhancedWelcome", "Something"); properties.setProperty("enhancedWelcome", "Something");
new PropertiesFeatureToggleVersion(properties); new PropertiesFeatureToggleVersion(properties);
}); });
@ -57,21 +55,21 @@ public class PropertiesFeatureToggleVersionTest {
@Test @Test
public void testFeatureTurnedOn() { public void testFeatureTurnedOn() {
final Properties properties = new Properties(); final var properties = new Properties();
properties.put("enhancedWelcome", true); properties.put("enhancedWelcome", true);
Service service = new PropertiesFeatureToggleVersion(properties); var service = new PropertiesFeatureToggleVersion(properties);
assertTrue(service.isEnhanced()); assertTrue(service.isEnhanced());
final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage);
} }
@Test @Test
public void testFeatureTurnedOff() { public void testFeatureTurnedOff() {
final Properties properties = new Properties(); final var properties = new Properties();
properties.put("enhancedWelcome", false); properties.put("enhancedWelcome", false);
Service service = new PropertiesFeatureToggleVersion(properties); var service = new PropertiesFeatureToggleVersion(properties);
assertFalse(service.isEnhanced()); assertFalse(service.isEnhanced());
final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
assertEquals("Welcome to the application.", welcomeMessage); assertEquals("Welcome to the application.", welcomeMessage);
} }
} }

View File

@ -23,15 +23,15 @@
package com.iluwatar.featuretoggle.pattern.tieredversion; package com.iluwatar.featuretoggle.pattern.tieredversion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.featuretoggle.pattern.Service; import com.iluwatar.featuretoggle.pattern.Service;
import com.iluwatar.featuretoggle.user.User; import com.iluwatar.featuretoggle.user.User;
import com.iluwatar.featuretoggle.user.UserGroup; import com.iluwatar.featuretoggle.user.UserGroup;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Test Tiered Feature Toggle * Test Tiered Feature Toggle
*/ */
@ -49,15 +49,15 @@ public class TieredFeatureToggleVersionTest {
@Test @Test
public void testGetWelcomeMessageForPaidUser() { public void testGetWelcomeMessageForPaidUser() {
final String welcomeMessage = service.getWelcomeMessage(paidUser); final var welcomeMessage = service.getWelcomeMessage(paidUser);
final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; final var expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software.";
assertEquals(expected, welcomeMessage); assertEquals(expected, welcomeMessage);
} }
@Test @Test
public void testGetWelcomeMessageForFreeUser() { public void testGetWelcomeMessageForFreeUser() {
final String welcomeMessage = service.getWelcomeMessage(freeUser); final var welcomeMessage = service.getWelcomeMessage(freeUser);
final String expected = "I suppose you can use this software."; final var expected = "I suppose you can use this software.";
assertEquals(expected, welcomeMessage); assertEquals(expected, welcomeMessage);
} }

View File

@ -23,34 +23,34 @@
package com.iluwatar.featuretoggle.user; package com.iluwatar.featuretoggle.user;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/** /**
* Test User Group specific feature * Test User Group specific feature
*/ */
public class UserGroupTest { public class UserGroupTest {
@Test @Test
public void testAddUserToFreeGroup() throws Exception { public void testAddUserToFreeGroup() {
User user = new User("Free User"); var user = new User("Free User");
UserGroup.addUserToFreeGroup(user); UserGroup.addUserToFreeGroup(user);
assertFalse(UserGroup.isPaid(user)); assertFalse(UserGroup.isPaid(user));
} }
@Test @Test
public void testAddUserToPaidGroup() throws Exception { public void testAddUserToPaidGroup() {
User user = new User("Paid User"); var user = new User("Paid User");
UserGroup.addUserToPaidGroup(user); UserGroup.addUserToPaidGroup(user);
assertTrue(UserGroup.isPaid(user)); assertTrue(UserGroup.isPaid(user));
} }
@Test @Test
public void testAddUserToPaidWhenOnFree() throws Exception { public void testAddUserToPaidWhenOnFree() {
User user = new User("Paid User"); var user = new User("Paid User");
UserGroup.addUserToFreeGroup(user); UserGroup.addUserToFreeGroup(user);
assertThrows(IllegalArgumentException.class, () -> { assertThrows(IllegalArgumentException.class, () -> {
UserGroup.addUserToPaidGroup(user); UserGroup.addUserToPaidGroup(user);
@ -58,8 +58,8 @@ public class UserGroupTest {
} }
@Test @Test
public void testAddUserToFreeWhenOnPaid() throws Exception { public void testAddUserToFreeWhenOnPaid() {
User user = new User("Free User"); var user = new User("Free User");
UserGroup.addUserToPaidGroup(user); UserGroup.addUserToPaidGroup(user);
assertThrows(IllegalArgumentException.class, () -> { assertThrows(IllegalArgumentException.class, () -> {
UserGroup.addUserToFreeGroup(user); UserGroup.addUserToFreeGroup(user);

View File

@ -28,8 +28,6 @@ import static java.lang.String.valueOf;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.StringJoiner; import java.util.StringJoiner;
import java.util.function.Function; import java.util.function.Function;
@ -57,19 +55,23 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>(); var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68);
integerList.addAll(List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2,
-68, 45));
prettyPrint("The initial list contains: ", integerList); prettyPrint("The initial list contains: ", integerList);
List<Integer> firstFiveNegatives = var firstFiveNegatives = SimpleFluentIterable
SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).first(3).asList(); .fromCopyOf(integerList)
.filter(negatives())
.first(3)
.asList();
prettyPrint("The first three negative values are: ", firstFiveNegatives); prettyPrint("The first three negative values are: ", firstFiveNegatives);
List<Integer> lastTwoPositives = var lastTwoPositives = SimpleFluentIterable
SimpleFluentIterable.fromCopyOf(integerList).filter(positives()).last(2).asList(); .fromCopyOf(integerList)
.filter(positives())
.last(2)
.asList();
prettyPrint("The last two positive values are: ", lastTwoPositives); prettyPrint("The last two positive values are: ", lastTwoPositives);
SimpleFluentIterable SimpleFluentIterable
@ -79,15 +81,21 @@ public class App {
.ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber)); .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber));
List<String> transformedList = var transformedList = SimpleFluentIterable
SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).map(transformToString()) .fromCopyOf(integerList)
.asList(); .filter(negatives())
.map(transformToString())
.asList();
prettyPrint("A string-mapped list of negative numbers contains: ", transformedList); prettyPrint("A string-mapped list of negative numbers contains: ", transformedList);
List<String> lastTwoOfFirstFourStringMapped = var lastTwoOfFirstFourStringMapped = LazyFluentIterable
LazyFluentIterable.from(integerList).filter(positives()).first(4).last(2) .from(integerList)
.map(number -> "String[" + valueOf(number) + "]").asList(); .filter(positives())
.first(4)
.last(2)
.map(number -> "String[" + valueOf(number) + "]")
.asList();
prettyPrint("The lazy list contains the last two of the first four positive numbers " prettyPrint("The lazy list contains the last two of the first four positive numbers "
+ "mapped to Strings: ", lastTwoOfFirstFourStringMapped); + "mapped to Strings: ", lastTwoOfFirstFourStringMapped);
@ -96,12 +104,11 @@ public class App {
.filter(negatives()) .filter(negatives())
.first(2) .first(2)
.last() .last()
.ifPresent(lastOfFirstTwo -> LOGGER .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number));
.info("The last of the first two negatives is: {}", lastOfFirstTwo));
} }
private static Function<Integer, String> transformToString() { private static Function<Integer, String> transformToString() {
return integer -> "String[" + valueOf(integer) + "]"; return integer -> "String[" + integer + "]";
} }
private static Predicate<? super Integer> negatives() { private static Predicate<? super Integer> negatives() {
@ -116,14 +123,12 @@ public class App {
prettyPrint(", ", prefix, iterable); prettyPrint(", ", prefix, iterable);
} }
private static <E> void prettyPrint(String delimiter, String prefix, private static <E> void prettyPrint(
Iterable<E> iterable) { String delimiter, String prefix,
StringJoiner joiner = new StringJoiner(delimiter, prefix, "."); Iterable<E> iterable
Iterator<E> iterator = iterable.iterator(); ) {
while (iterator.hasNext()) { var joiner = new StringJoiner(delimiter, prefix, ".");
joiner.add(iterator.next().toString()); iterable.forEach(e -> joiner.add(e.toString()));
}
LOGGER.info(joiner.toString()); LOGGER.info(joiner.toString());
} }
} }

View File

@ -24,7 +24,6 @@
package com.iluwatar.fluentinterface.fluentiterable; package com.iluwatar.fluentinterface.fluentiterable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
@ -102,11 +101,8 @@ public interface FluentIterable<E> extends Iterable<E> {
* @return a list with all objects of the given iterator * @return a list with all objects of the given iterator
*/ */
static <E> List<E> copyToList(Iterable<E> iterable) { static <E> List<E> copyToList(Iterable<E> iterable) {
List<E> copy = new ArrayList<>(); var copy = new ArrayList<E>();
Iterator<E> iterator = iterable.iterator(); iterable.forEach(copy::add);
while (iterator.hasNext()) {
copy.add(iterator.next());
}
return copy; return copy;
} }
} }

View File

@ -65,7 +65,7 @@ public abstract class DecoratingIterator<E> implements Iterator<E> {
if (next == null) { if (next == null) {
return fromIterator.next(); return fromIterator.next();
} else { } else {
final E result = next; final var result = next;
next = null; next = null;
return result; return result;
} }

View File

@ -67,14 +67,14 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public FluentIterable<E> filter(Predicate<? super E> predicate) { public FluentIterable<E> filter(Predicate<? super E> predicate) {
return new LazyFluentIterable<E>() { return new LazyFluentIterable<>() {
@Override @Override
public Iterator<E> iterator() { public Iterator<E> iterator() {
return new DecoratingIterator<E>(iterable.iterator()) { return new DecoratingIterator<E>(iterable.iterator()) {
@Override @Override
public E computeNext() { public E computeNext() {
while (fromIterator.hasNext()) { while (fromIterator.hasNext()) {
E candidate = fromIterator.next(); var candidate = fromIterator.next();
if (predicate.test(candidate)) { if (predicate.test(candidate)) {
return candidate; return candidate;
} }
@ -94,7 +94,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public Optional<E> first() { public Optional<E> first() {
Iterator<E> resultIterator = first(1).iterator(); var resultIterator = first(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
} }
@ -116,7 +116,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
@Override @Override
public E computeNext() { public E computeNext() {
if (currentIndex < count && fromIterator.hasNext()) { if (currentIndex < count && fromIterator.hasNext()) {
E candidate = fromIterator.next(); var candidate = fromIterator.next();
currentIndex++; currentIndex++;
return candidate; return candidate;
} }
@ -134,7 +134,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public Optional<E> last() { public Optional<E> last() {
Iterator<E> resultIterator = last(1).iterator(); var resultIterator = last(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
} }
@ -162,25 +162,20 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
public E computeNext() { public E computeNext() {
initialize(); initialize();
E candidate = null;
while (currentIndex < stopIndex && fromIterator.hasNext()) { while (currentIndex < stopIndex && fromIterator.hasNext()) {
currentIndex++; currentIndex++;
fromIterator.next(); fromIterator.next();
} }
if (currentIndex >= stopIndex && fromIterator.hasNext()) { if (currentIndex >= stopIndex && fromIterator.hasNext()) {
candidate = fromIterator.next(); return fromIterator.next();
} }
return candidate; return null;
} }
private void initialize() { private void initialize() {
if (list == null) { if (list == null) {
list = new ArrayList<>(); list = new ArrayList<>();
Iterator<E> newIterator = iterable.iterator(); iterable.forEach(list::add);
while (newIterator.hasNext()) {
list.add(newIterator.next());
}
totalElementsCount = list.size(); totalElementsCount = list.size();
stopIndex = totalElementsCount - count; stopIndex = totalElementsCount - count;
} }

View File

@ -62,9 +62,9 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public final FluentIterable<E> filter(Predicate<? super E> predicate) { public final FluentIterable<E> filter(Predicate<? super E> predicate) {
Iterator<E> iterator = iterator(); var iterator = iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
E nextElement = iterator.next(); var nextElement = iterator.next();
if (!predicate.test(nextElement)) { if (!predicate.test(nextElement)) {
iterator.remove(); iterator.remove();
} }
@ -79,7 +79,7 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public final Optional<E> first() { public final Optional<E> first() {
Iterator<E> resultIterator = first(1).iterator(); var resultIterator = first(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
} }
@ -92,8 +92,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public final FluentIterable<E> first(int count) { public final FluentIterable<E> first(int count) {
Iterator<E> iterator = iterator(); var iterator = iterator();
int currentCount = 0; var currentCount = 0;
while (iterator.hasNext()) { while (iterator.hasNext()) {
iterator.next(); iterator.next();
if (currentCount >= count) { if (currentCount >= count) {
@ -111,7 +111,7 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public final Optional<E> last() { public final Optional<E> last() {
List<E> list = last(1).asList(); var list = last(1).asList();
if (list.isEmpty()) { if (list.isEmpty()) {
return Optional.empty(); return Optional.empty();
} }
@ -127,9 +127,9 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public final FluentIterable<E> last(int count) { public final FluentIterable<E> last(int count) {
int remainingElementsCount = getRemainingElementsCount(); var remainingElementsCount = getRemainingElementsCount();
Iterator<E> iterator = iterator(); var iterator = iterator();
int currentIndex = 0; var currentIndex = 0;
while (iterator.hasNext()) { while (iterator.hasNext()) {
iterator.next(); iterator.next();
if (currentIndex < remainingElementsCount - count) { if (currentIndex < remainingElementsCount - count) {
@ -150,11 +150,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/ */
@Override @Override
public final <T> FluentIterable<T> map(Function<? super E, T> function) { public final <T> FluentIterable<T> map(Function<? super E, T> function) {
List<T> temporaryList = new ArrayList<>(); var temporaryList = new ArrayList<T>();
Iterator<E> iterator = iterator(); this.forEach(e -> temporaryList.add(function.apply(e)));
while (iterator.hasNext()) {
temporaryList.add(function.apply(iterator.next()));
}
return from(temporaryList); return from(temporaryList);
} }
@ -178,7 +175,7 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
} }
public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) { public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) {
List<E> copy = FluentIterable.copyToList(iterable); var copy = FluentIterable.copyToList(iterable);
return new SimpleFluentIterable<>(copy); return new SimpleFluentIterable<>(copy);
} }
@ -204,10 +201,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
* @return the count of remaining objects of the current Iterable * @return the count of remaining objects of the current Iterable
*/ */
public final int getRemainingElementsCount() { public final int getRemainingElementsCount() {
int counter = 0; var counter = 0;
Iterator<E> iterator = iterator(); for (var ignored : this) {
while (iterator.hasNext()) {
iterator.next();
counter++; counter++;
} }
return counter; return counter;
@ -219,10 +214,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
* @return a new List with the remaining objects. * @return a new List with the remaining objects.
*/ */
public static <E> List<E> toList(Iterator<E> iterator) { public static <E> List<E> toList(Iterator<E> iterator) {
List<E> copy = new ArrayList<>(); var copy = new ArrayList<E>();
while (iterator.hasNext()) { iterator.forEachRemaining(copy::add);
copy.add(iterator.next());
}
return copy; return copy;
} }
} }

View File

@ -32,7 +32,6 @@ public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,16 +23,19 @@
package com.iluwatar.fluentinterface.fluentiterable; package com.iluwatar.fluentinterface.fluentiterable;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/** /**
* Date: 12/12/15 - 7:00 PM * Date: 12/12/15 - 7:00 PM
@ -50,28 +53,28 @@ public abstract class FluentIterableTest {
protected abstract FluentIterable<Integer> createFluentIterable(final Iterable<Integer> integers); protected abstract FluentIterable<Integer> createFluentIterable(final Iterable<Integer> integers);
@Test @Test
public void testFirst() throws Exception { public void testFirst() {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8); final var integers = List.of(1, 2, 3, 10, 9, 8);
final Optional<Integer> first = createFluentIterable(integers).first(); final var first = createFluentIterable(integers).first();
assertNotNull(first); assertNotNull(first);
assertTrue(first.isPresent()); assertTrue(first.isPresent());
assertEquals(integers.get(0), first.get()); assertEquals(integers.get(0), first.get());
} }
@Test @Test
public void testFirstEmptyCollection() throws Exception { public void testFirstEmptyCollection() {
final List<Integer> integers = Collections.emptyList(); final var integers = Collections.<Integer>emptyList();
final Optional<Integer> first = createFluentIterable(integers).first(); final var first = createFluentIterable(integers).first();
assertNotNull(first); assertNotNull(first);
assertFalse(first.isPresent()); assertFalse(first.isPresent());
} }
@Test @Test
public void testFirstCount() throws Exception { public void testFirstCount() {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8); final var integers = List.of(1, 2, 3, 10, 9, 8);
final List<Integer> first4 = createFluentIterable(integers) final var first4 = createFluentIterable(integers)
.first(4) .first(4)
.asList(); .asList();
assertNotNull(first4); assertNotNull(first4);
assertEquals(4, first4.size()); assertEquals(4, first4.size());
@ -83,11 +86,11 @@ public abstract class FluentIterableTest {
} }
@Test @Test
public void testFirstCountLessItems() throws Exception { public void testFirstCountLessItems() {
final List<Integer> integers = List.of(1, 2, 3); final var integers = List.of(1, 2, 3);
final List<Integer> first4 = createFluentIterable(integers) final var first4 = createFluentIterable(integers)
.first(4) .first(4)
.asList(); .asList();
assertNotNull(first4); assertNotNull(first4);
assertEquals(3, first4.size()); assertEquals(3, first4.size());
@ -98,28 +101,28 @@ public abstract class FluentIterableTest {
} }
@Test @Test
public void testLast() throws Exception { public void testLast() {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8); final var integers = List.of(1, 2, 3, 10, 9, 8);
final Optional<Integer> last = createFluentIterable(integers).last(); final var last = createFluentIterable(integers).last();
assertNotNull(last); assertNotNull(last);
assertTrue(last.isPresent()); assertTrue(last.isPresent());
assertEquals(integers.get(integers.size() - 1), last.get()); assertEquals(integers.get(integers.size() - 1), last.get());
} }
@Test @Test
public void testLastEmptyCollection() throws Exception { public void testLastEmptyCollection() {
final List<Integer> integers = Collections.<Integer>emptyList(); final var integers = Collections.<Integer>emptyList();
final Optional<Integer> last = createFluentIterable(integers).last(); final var last = createFluentIterable(integers).last();
assertNotNull(last); assertNotNull(last);
assertFalse(last.isPresent()); assertFalse(last.isPresent());
} }
@Test @Test
public void testLastCount() throws Exception { public void testLastCount() {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8); final var integers = List.of(1, 2, 3, 10, 9, 8);
final List<Integer> last4 = createFluentIterable(integers) final var last4 = createFluentIterable(integers)
.last(4) .last(4)
.asList(); .asList();
assertNotNull(last4); assertNotNull(last4);
assertEquals(4, last4.size()); assertEquals(4, last4.size());
@ -130,11 +133,11 @@ public abstract class FluentIterableTest {
} }
@Test @Test
public void testLastCountLessItems() throws Exception { public void testLastCountLessItems() {
final List<Integer> integers = List.of(1, 2, 3); final var integers = List.of(1, 2, 3);
final List<Integer> last4 = createFluentIterable(integers) final var last4 = createFluentIterable(integers)
.last(4) .last(4)
.asList(); .asList();
assertNotNull(last4); assertNotNull(last4);
assertEquals(3, last4.size()); assertEquals(3, last4.size());
@ -145,11 +148,11 @@ public abstract class FluentIterableTest {
} }
@Test @Test
public void testFilter() throws Exception { public void testFilter() {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8); final var integers = List.of(1, 2, 3, 10, 9, 8);
final List<Integer> evenItems = createFluentIterable(integers) final var evenItems = createFluentIterable(integers)
.filter(i -> i % 2 == 0) .filter(i -> i % 2 == 0)
.asList(); .asList();
assertNotNull(evenItems); assertNotNull(evenItems);
assertEquals(3, evenItems.size()); assertEquals(3, evenItems.size());
@ -159,11 +162,11 @@ public abstract class FluentIterableTest {
} }
@Test @Test
public void testMap() throws Exception { public void testMap() {
final List<Integer> integers = List.of(1, 2, 3); final var integers = List.of(1, 2, 3);
final List<Long> longs = createFluentIterable(integers) final var longs = createFluentIterable(integers)
.map(Integer::longValue) .map(Integer::longValue)
.asList(); .asList();
assertNotNull(longs); assertNotNull(longs);
assertEquals(integers.size(), longs.size()); assertEquals(integers.size(), longs.size());
@ -174,7 +177,7 @@ public abstract class FluentIterableTest {
@Test @Test
public void testForEach() { public void testForEach() {
final List<Integer> integers = List.of(1, 2, 3); final var integers = List.of(1, 2, 3);
final Consumer<Integer> consumer = mock(Consumer.class); final Consumer<Integer> consumer = mock(Consumer.class);
createFluentIterable(integers).forEach(consumer); createFluentIterable(integers).forEach(consumer);
@ -188,8 +191,8 @@ public abstract class FluentIterableTest {
@Test @Test
public void testSpliterator() throws Exception { public void testSpliterator() throws Exception {
final List<Integer> integers = List.of(1, 2, 3); final var integers = List.of(1, 2, 3);
final Spliterator<Integer> split = createFluentIterable(integers).spliterator(); final var split = createFluentIterable(integers).spliterator();
assertNotNull(split); assertNotNull(split);
} }

View File

@ -54,13 +54,13 @@ public class App {
public static void main(String[] args) { public static void main(String[] args) {
// initialize and wire the system // initialize and wire the system
MenuStore menuStore = new MenuStore(); var menuStore = new MenuStore();
Dispatcher.getInstance().registerStore(menuStore); Dispatcher.getInstance().registerStore(menuStore);
ContentStore contentStore = new ContentStore(); var contentStore = new ContentStore();
Dispatcher.getInstance().registerStore(contentStore); Dispatcher.getInstance().registerStore(contentStore);
MenuView menuView = new MenuView(); var menuView = new MenuView();
menuStore.registerView(menuView); menuStore.registerView(menuView);
ContentView contentView = new ContentView(); var contentView = new ContentView();
contentStore.registerView(contentView); contentStore.registerView(contentView);
// render initial view // render initial view

View File

@ -70,6 +70,6 @@ public final class Dispatcher {
} }
private void dispatchAction(Action action) { private void dispatchAction(Action action) {
stores.stream().forEach(store -> store.onAction(action)); stores.forEach(store -> store.onAction(action));
} }
} }

View File

@ -38,7 +38,7 @@ public class ContentStore extends Store {
@Override @Override
public void onAction(Action action) { public void onAction(Action action) {
if (action.getType().equals(ActionType.CONTENT_CHANGED)) { if (action.getType().equals(ActionType.CONTENT_CHANGED)) {
ContentAction contentAction = (ContentAction) action; var contentAction = (ContentAction) action;
content = contentAction.getContent(); content = contentAction.getContent();
notifyChange(); notifyChange();
} }

View File

@ -38,7 +38,7 @@ public class MenuStore extends Store {
@Override @Override
public void onAction(Action action) { public void onAction(Action action) {
if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) { if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
MenuAction menuAction = (MenuAction) action; var menuAction = (MenuAction) action;
selected = menuAction.getMenuItem(); selected = menuAction.getMenuItem();
notifyChange(); notifyChange();
} }

View File

@ -42,6 +42,6 @@ public abstract class Store {
} }
protected void notifyChange() { protected void notifyChange() {
views.stream().forEach(view -> view.storeChanged(this)); views.forEach(view -> view.storeChanged(this));
} }
} }

View File

@ -40,7 +40,7 @@ public class ContentView implements View {
@Override @Override
public void storeChanged(Store store) { public void storeChanged(Store store) {
ContentStore contentStore = (ContentStore) store; var contentStore = (ContentStore) store;
content = contentStore.getContent(); content = contentStore.getContent();
render(); render();
} }

View File

@ -41,14 +41,14 @@ public class MenuView implements View {
@Override @Override
public void storeChanged(Store store) { public void storeChanged(Store store) {
MenuStore menuStore = (MenuStore) store; var menuStore = (MenuStore) store;
selected = menuStore.getSelected(); selected = menuStore.getSelected();
render(); render();
} }
@Override @Override
public void render() { public void render() {
for (MenuItem item : MenuItem.values()) { for (var item : MenuItem.values()) {
if (selected.equals(item)) { if (selected.equals(item)) {
LOGGER.info("* {}", item); LOGGER.info("* {}", item);
} else { } else {

View File

@ -23,11 +23,11 @@
package com.iluwatar.flux.action; package com.iluwatar.flux.action;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/12/15 - 10:11 PM * Date: 12/12/15 - 10:11 PM
* *
@ -36,9 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ContentTest { public class ContentTest {
@Test @Test
public void testToString() throws Exception { public void testToString() {
for (final Content content : Content.values()) { for (final var content : Content.values()) {
final String toString = content.toString(); final var toString = content.toString();
assertNotNull(toString); assertNotNull(toString);
assertFalse(toString.trim().isEmpty()); assertFalse(toString.trim().isEmpty());
} }

View File

@ -23,11 +23,11 @@
package com.iluwatar.flux.action; package com.iluwatar.flux.action;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/12/15 - 10:15 PM * Date: 12/12/15 - 10:15 PM
* *
@ -36,9 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class MenuItemTest { public class MenuItemTest {
@Test @Test
public void testToString() throws Exception { public void testToString() {
for (final MenuItem menuItem : MenuItem.values()) { for (final var menuItem : MenuItem.values()) {
final String toString = menuItem.toString(); final var toString = menuItem.toString();
assertNotNull(toString); assertNotNull(toString);
assertFalse(toString.trim().isEmpty()); assertFalse(toString.trim().isEmpty());
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.flux.app;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -23,22 +23,6 @@
package com.iluwatar.flux.dispatcher; package com.iluwatar.flux.dispatcher;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.ActionType;
import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.action.ContentAction;
import com.iluwatar.flux.action.MenuAction;
import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.store.Store;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
@ -47,6 +31,19 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.ActionType;
import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.action.ContentAction;
import com.iluwatar.flux.action.MenuAction;
import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.store.Store;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
/** /**
* Date: 12/12/15 - 8:22 PM * Date: 12/12/15 - 8:22 PM
* *
@ -61,53 +58,56 @@ public class DispatcherTest {
*/ */
@BeforeEach @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
final Constructor<Dispatcher> constructor; final var constructor = Dispatcher.class.getDeclaredConstructor();
constructor = Dispatcher.class.getDeclaredConstructor();
constructor.setAccessible(true); constructor.setAccessible(true);
final Field field = Dispatcher.class.getDeclaredField("instance"); final var field = Dispatcher.class.getDeclaredField("instance");
field.setAccessible(true); field.setAccessible(true);
field.set(Dispatcher.getInstance(), constructor.newInstance()); field.set(Dispatcher.getInstance(), constructor.newInstance());
} }
@Test @Test
public void testGetInstance() throws Exception { public void testGetInstance() {
assertNotNull(Dispatcher.getInstance()); assertNotNull(Dispatcher.getInstance());
assertSame(Dispatcher.getInstance(), Dispatcher.getInstance()); assertSame(Dispatcher.getInstance(), Dispatcher.getInstance());
} }
@Test @Test
public void testMenuItemSelected() throws Exception { public void testMenuItemSelected() {
final Dispatcher dispatcher = Dispatcher.getInstance(); final var dispatcher = Dispatcher.getInstance();
final Store store = mock(Store.class); final var store = mock(Store.class);
dispatcher.registerStore(store); dispatcher.registerStore(store);
dispatcher.menuItemSelected(MenuItem.HOME); dispatcher.menuItemSelected(MenuItem.HOME);
dispatcher.menuItemSelected(MenuItem.COMPANY); dispatcher.menuItemSelected(MenuItem.COMPANY);
// We expect 4 events, 2 menu selections and 2 content change actions // We expect 4 events, 2 menu selections and 2 content change actions
final ArgumentCaptor<Action> actionCaptor = ArgumentCaptor.forClass(Action.class); final var actionCaptor = ArgumentCaptor.forClass(Action.class);
verify(store, times(4)).onAction(actionCaptor.capture()); verify(store, times(4)).onAction(actionCaptor.capture());
verifyNoMoreInteractions(store); verifyNoMoreInteractions(store);
final List<Action> actions = actionCaptor.getAllValues(); final var actions = actionCaptor.getAllValues();
final List<MenuAction> menuActions = actions.stream() final var menuActions = actions.stream()
.filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED))
.map(a -> (MenuAction) a) .map(a -> (MenuAction) a)
.collect(Collectors.toList()); .collect(Collectors.toList());
final List<ContentAction> contentActions = actions.stream() final var contentActions = actions.stream()
.filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED))
.map(a -> (ContentAction) a) .map(a -> (ContentAction) a)
.collect(Collectors.toList()); .collect(Collectors.toList());
assertEquals(2, menuActions.size()); assertEquals(2, menuActions.size());
assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals)
assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); .count());
assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem)
.filter(MenuItem.COMPANY::equals).count());
assertEquals(2, contentActions.size()); assertEquals(2, contentActions.size());
assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.PRODUCTS::equals).count()); assertEquals(1, contentActions.stream().map(ContentAction::getContent)
assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.COMPANY::equals).count()); .filter(Content.PRODUCTS::equals).count());
assertEquals(1, contentActions.stream().map(ContentAction::getContent)
.filter(Content.COMPANY::equals).count());
} }

View File

@ -23,6 +23,14 @@
package com.iluwatar.flux.store; package com.iluwatar.flux.store;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.ContentAction;
import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuAction;
@ -30,14 +38,6 @@ import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.view.View; import com.iluwatar.flux.view.View;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Date: 12/12/15 - 10:18 PM * Date: 12/12/15 - 10:18 PM
* *
@ -46,10 +46,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class ContentStoreTest { public class ContentStoreTest {
@Test @Test
public void testOnAction() throws Exception { public void testOnAction() {
final ContentStore contentStore = new ContentStore(); final var contentStore = new ContentStore();
final View view = mock(View.class); final var view = mock(View.class);
contentStore.registerView(view); contentStore.registerView(view);
verifyZeroInteractions(view); verifyZeroInteractions(view);

View File

@ -23,6 +23,14 @@
package com.iluwatar.flux.store; package com.iluwatar.flux.store;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.iluwatar.flux.action.Content; import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.action.ContentAction; import com.iluwatar.flux.action.ContentAction;
import com.iluwatar.flux.action.MenuAction; import com.iluwatar.flux.action.MenuAction;
@ -30,14 +38,6 @@ import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.view.View; import com.iluwatar.flux.view.View;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Date: 12/12/15 - 10:18 PM * Date: 12/12/15 - 10:18 PM
* *
@ -46,10 +46,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class MenuStoreTest { public class MenuStoreTest {
@Test @Test
public void testOnAction() throws Exception { public void testOnAction() {
final MenuStore menuStore = new MenuStore(); final var menuStore = new MenuStore();
final View view = mock(View.class); final var view = mock(View.class);
menuStore.registerView(view); menuStore.registerView(view);
verifyZeroInteractions(view); verifyZeroInteractions(view);

View File

@ -23,15 +23,15 @@
package com.iluwatar.flux.view; package com.iluwatar.flux.view;
import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.store.ContentStore;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.store.ContentStore;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/12/15 - 10:31 PM * Date: 12/12/15 - 10:31 PM
@ -41,11 +41,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class ContentViewTest { public class ContentViewTest {
@Test @Test
public void testStoreChanged() throws Exception { public void testStoreChanged() {
final ContentStore store = mock(ContentStore.class); final var store = mock(ContentStore.class);
when(store.getContent()).thenReturn(Content.PRODUCTS); when(store.getContent()).thenReturn(Content.PRODUCTS);
final ContentView view = new ContentView(); final var view = new ContentView();
view.storeChanged(store); view.storeChanged(store);
verify(store, times(1)).getContent(); verify(store, times(1)).getContent();

View File

@ -23,13 +23,6 @@
package com.iluwatar.flux.view; package com.iluwatar.flux.view;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.dispatcher.Dispatcher;
import com.iluwatar.flux.store.MenuStore;
import com.iluwatar.flux.store.Store;
import org.junit.jupiter.api.Test;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -37,6 +30,13 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.dispatcher.Dispatcher;
import com.iluwatar.flux.store.MenuStore;
import com.iluwatar.flux.store.Store;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/12/15 - 10:31 PM * Date: 12/12/15 - 10:31 PM
* *
@ -45,11 +45,11 @@ import static org.mockito.Mockito.when;
public class MenuViewTest { public class MenuViewTest {
@Test @Test
public void testStoreChanged() throws Exception { public void testStoreChanged() {
final MenuStore store = mock(MenuStore.class); final var store = mock(MenuStore.class);
when(store.getSelected()).thenReturn(MenuItem.HOME); when(store.getSelected()).thenReturn(MenuItem.HOME);
final MenuView view = new MenuView(); final var view = new MenuView();
view.storeChanged(store); view.storeChanged(store);
verify(store, times(1)).getSelected(); verify(store, times(1)).getSelected();
@ -57,11 +57,11 @@ public class MenuViewTest {
} }
@Test @Test
public void testItemClicked() throws Exception { public void testItemClicked() {
final Store store = mock(Store.class); final var store = mock(Store.class);
Dispatcher.getInstance().registerStore(store); Dispatcher.getInstance().registerStore(store);
final MenuView view = new MenuView(); final var view = new MenuView();
view.itemClicked(MenuItem.PRODUCTS); view.itemClicked(MenuItem.PRODUCTS);
// We should receive a menu click action and a content changed action // We should receive a menu click action and a content changed action

View File

@ -72,7 +72,7 @@ public class PotionFactory {
} }
Potion createPotion(PotionType type) { Potion createPotion(PotionType type) {
Potion potion = potions.get(type); var potion = potions.get(type);
if (potion == null) { if (potion == null) {
switch (type) { switch (type) {
case HEALING: case HEALING:
@ -99,7 +99,7 @@ public class PotionFactory {
And it can be used as below And it can be used as below
```java ```java
PotionFactory factory = new PotionFactory(); var factory = new PotionFactory();
factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818) factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818)
factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364) factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364)
factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818) factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818)

View File

@ -23,7 +23,6 @@
package com.iluwatar.flyweight; package com.iluwatar.flyweight;
import java.util.Collections;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,7 +41,7 @@ public class AlchemistShop {
* Constructor. * Constructor.
*/ */
public AlchemistShop() { public AlchemistShop() {
PotionFactory factory = new PotionFactory(); var factory = new PotionFactory();
topShelf = List.of( topShelf = List.of(
factory.createPotion(PotionType.INVISIBILITY), factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.INVISIBILITY), factory.createPotion(PotionType.INVISIBILITY),
@ -68,7 +67,7 @@ public class AlchemistShop {
* @return The top shelf potions * @return The top shelf potions
*/ */
public final List<Potion> getTopShelf() { public final List<Potion> getTopShelf() {
return Collections.unmodifiableList(this.topShelf); return List.copyOf(this.topShelf);
} }
/** /**
@ -77,24 +76,16 @@ public class AlchemistShop {
* @return The bottom shelf potions * @return The bottom shelf potions
*/ */
public final List<Potion> getBottomShelf() { public final List<Potion> getBottomShelf() {
return Collections.unmodifiableList(this.bottomShelf); return List.copyOf(this.bottomShelf);
} }
/** /**
* Enumerate potions. * Enumerate potions.
*/ */
public void enumerate() { public void enumerate() {
LOGGER.info("Enumerating top shelf potions\n"); LOGGER.info("Enumerating top shelf potions\n");
topShelf.forEach(Potion::drink);
for (Potion p : topShelf) {
p.drink();
}
LOGGER.info("Enumerating bottom shelf potions\n"); LOGGER.info("Enumerating bottom shelf potions\n");
bottomShelf.forEach(Potion::drink);
for (Potion p : bottomShelf) {
p.drink();
}
} }
} }

View File

@ -43,7 +43,7 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
AlchemistShop alchemistShop = new AlchemistShop(); var alchemistShop = new AlchemistShop();
alchemistShop.enumerate(); alchemistShop.enumerate();
} }
} }

View File

@ -40,7 +40,7 @@ public class PotionFactory {
} }
Potion createPotion(PotionType type) { Potion createPotion(PotionType type) {
Potion potion = potions.get(type); var potion = potions.get(type);
if (potion == null) { if (potion == null) {
switch (type) { switch (type) {
case HEALING: case HEALING:

View File

@ -23,14 +23,12 @@
package com.iluwatar.flyweight; package com.iluwatar.flyweight;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/12/15 - 10:54 PM * Date: 12/12/15 - 10:54 PM
* *
@ -39,18 +37,18 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class AlchemistShopTest { public class AlchemistShopTest {
@Test @Test
public void testShop() throws Exception { public void testShop() {
final AlchemistShop shop = new AlchemistShop(); final var shop = new AlchemistShop();
final List<Potion> bottomShelf = shop.getBottomShelf(); final var bottomShelf = shop.getBottomShelf();
assertNotNull(bottomShelf); assertNotNull(bottomShelf);
assertEquals(5, bottomShelf.size()); assertEquals(5, bottomShelf.size());
final List<Potion> topShelf = shop.getTopShelf(); final var topShelf = shop.getTopShelf();
assertNotNull(topShelf); assertNotNull(topShelf);
assertEquals(8, topShelf.size()); assertEquals(8, topShelf.size());
final List<Potion> allPotions = new ArrayList<>(); final var allPotions = new ArrayList<Potion>();
allPotions.addAll(topShelf); allPotions.addAll(topShelf);
allPotions.addAll(bottomShelf); allPotions.addAll(bottomShelf);

View File

@ -26,15 +26,12 @@ package com.iluwatar.flyweight;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -47,7 +47,7 @@ public class App {
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
FrontController controller = new FrontController(); var controller = new FrontController();
controller.handleRequest("Archer"); controller.handleRequest("Archer");
controller.handleRequest("Catapult"); controller.handleRequest("Catapult");
controller.handleRequest("foobar"); controller.handleRequest("foobar");

View File

@ -30,12 +30,12 @@ package com.iluwatar.front.controller;
public class FrontController { public class FrontController {
public void handleRequest(String request) { public void handleRequest(String request) {
Command command = getCommand(request); var command = getCommand(request);
command.process(); command.process();
} }
private Command getCommand(String request) { private Command getCommand(String request) {
Class<?> commandClass = getCommandClass(request); var commandClass = getCommandClass(request);
try { try {
return (Command) commandClass.newInstance(); return (Command) commandClass.newInstance();
} catch (Exception e) { } catch (Exception e) {
@ -44,12 +44,10 @@ public class FrontController {
} }
private static Class<?> getCommandClass(String request) { private static Class<?> getCommandClass(String request) {
Class<?> result;
try { try {
result = Class.forName("com.iluwatar.front.controller." + request + "Command"); return Class.forName("com.iluwatar.front.controller." + request + "Command");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
result = UnknownCommand.class; return UnknownCommand.class;
} }
return result;
} }
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.front.controller;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
*
* Application test * Application test
*
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -36,7 +36,7 @@ public class ApplicationExceptionTest {
@Test @Test
public void testCause() { public void testCause() {
final Exception cause = new Exception(); final var cause = new Exception();
assertSame(cause, new ApplicationException(cause).getCause()); assertSame(cause, new ApplicationException(cause).getCause());
} }

View File

@ -23,17 +23,15 @@
package com.iluwatar.front.controller; package com.iluwatar.front.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.front.controller.utils.InMemoryAppender; import com.iluwatar.front.controller.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 12/13/15 - 1:39 PM * Date: 12/13/15 - 1:39 PM
* *
@ -54,11 +52,11 @@ public class CommandTest {
} }
static List<Object[]> dataProvider() { static List<Object[]> dataProvider() {
final List<Object[]> parameters = new ArrayList<>(); return List.of(
parameters.add(new Object[]{"Archer", "Displaying archers"}); new Object[]{"Archer", "Displaying archers"},
parameters.add(new Object[]{"Catapult", "Displaying catapults"}); new Object[]{"Catapult", "Displaying catapults"},
parameters.add(new Object[]{"NonExistentCommand", "Error 500"}); new Object[]{"NonExistentCommand", "Error 500"}
return parameters; );
} }
/** /**
@ -68,7 +66,7 @@ public class CommandTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("dataProvider") @MethodSource("dataProvider")
public void testDisplay(String request, String displayMessage) { public void testDisplay(String request, String displayMessage) {
final FrontController frontController = new FrontController(); final var frontController = new FrontController();
assertEquals(0, appender.getLogSize()); assertEquals(0, appender.getLogSize());
frontController.handleRequest(request); frontController.handleRequest(request);
assertEquals(displayMessage, appender.getLastMessage()); assertEquals(displayMessage, appender.getLastMessage());

View File

@ -23,17 +23,15 @@
package com.iluwatar.front.controller; package com.iluwatar.front.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.front.controller.utils.InMemoryAppender; import com.iluwatar.front.controller.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 12/13/15 - 1:39 PM * Date: 12/13/15 - 1:39 PM
* *
@ -54,11 +52,11 @@ public class FrontControllerTest {
} }
static List<Object[]> dataProvider() { static List<Object[]> dataProvider() {
final List<Object[]> parameters = new ArrayList<>(); return List.of(
parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"}); new Object[]{new ArcherCommand(), "Displaying archers"},
parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"}); new Object[]{new CatapultCommand(), "Displaying catapults"},
parameters.add(new Object[]{new UnknownCommand(), "Error 500"}); new Object[]{new UnknownCommand(), "Error 500"}
return parameters; );
} }
/** /**

View File

@ -23,17 +23,15 @@
package com.iluwatar.front.controller; package com.iluwatar.front.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.front.controller.utils.InMemoryAppender; import com.iluwatar.front.controller.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 12/13/15 - 1:39 PM * Date: 12/13/15 - 1:39 PM
* *
@ -54,11 +52,11 @@ public class ViewTest {
} }
static List<Object[]> dataProvider() { static List<Object[]> dataProvider() {
final List<Object[]> parameters = new ArrayList<>(); return List.of(
parameters.add(new Object[]{new ArcherView(), "Displaying archers"}); new Object[]{new ArcherView(), "Displaying archers"},
parameters.add(new Object[]{new CatapultView(), "Displaying catapults"}); new Object[]{new CatapultView(), "Displaying catapults"},
parameters.add(new Object[]{new ErrorView(), "Error 500"}); new Object[]{new ErrorView(), "Error 500"}
return parameters; );
} }
/** /**