提交 670c4e43 编写于 作者: A Anurag Agarwal 提交者: Ilkka Seppälä

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
上级 f835d3d5
......@@ -76,9 +76,7 @@ public abstract class DwarvenMineWorker {
}
public void action(Action... actions) {
for (Action action : actions) {
action(action);
}
Arrays.stream(actions).forEach(this::action);
}
public abstract void work();
......@@ -165,9 +163,7 @@ public class DwarvenGoldmineFacade {
private static void makeActions(Collection<DwarvenMineWorker> workers,
DwarvenMineWorker.Action... actions) {
for (DwarvenMineWorker worker : workers) {
worker.action(actions);
}
workers.forEach(worker -> worker.action(actions));
}
}
```
......
......@@ -42,7 +42,7 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
var facade = new DwarvenGoldmineFacade();
facade.startNewDay();
facade.digOutGold();
facade.endDay();
......
......@@ -63,8 +63,6 @@ public class DwarvenGoldmineFacade {
Collection<DwarvenMineWorker> workers,
DwarvenMineWorker.Action... actions
) {
for (DwarvenMineWorker worker : workers) {
worker.action(actions);
}
workers.forEach(worker -> worker.action(actions));
}
}
......@@ -23,6 +23,7 @@
package com.iluwatar.facade;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -76,9 +77,7 @@ public abstract class DwarvenMineWorker {
* Perform actions.
*/
public void action(Action... actions) {
for (Action action : actions) {
action(action);
}
Arrays.stream(actions).forEach(this::action);
}
public abstract void work();
......
......@@ -26,15 +26,12 @@ package com.iluwatar.facade;
import org.junit.jupiter.api.Test;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
......@@ -23,20 +23,19 @@
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.spi.ILoggingEvent;
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.BeforeEach;
import org.junit.jupiter.api.Test;
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
*
......@@ -56,16 +55,16 @@ public class DwarvenGoldmineFacadeTest {
appender.stop();
}
/**
/**
* Test a complete day cycle in the gold mine by executing all three different steps: {@link
* DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link
* DwarvenGoldmineFacade#endDay()}.
*
* <p>
* See if the workers are doing what's expected from them on each step.
*/
@Test
public void testFullWorkDay() {
final DwarvenGoldmineFacade goldMine = new DwarvenGoldmineFacade();
final var goldMine = new DwarvenGoldmineFacade();
goldMine.startNewDay();
// On the start of a day, all workers should wake up ...
......@@ -128,7 +127,9 @@ public class DwarvenGoldmineFacadeTest {
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
return log.stream()
.map(ILoggingEvent::getFormattedMessage)
.anyMatch(message::equals);
}
}
......
......@@ -48,13 +48,13 @@ public class App {
* @param args command line 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.AXE, Axe::new);
builder.add(WeaponType.SPEAR, Spear::new);
builder.add(WeaponType.BOW, Bow::new);
});
Weapon axe = factory.create(WeaponType.AXE);
var axe = factory.create(WeaponType.AXE);
LOGGER.info(axe.toString());
}
}
......@@ -24,7 +24,6 @@
package com.iluwatar.factorykit;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
......@@ -52,7 +51,7 @@ public interface WeaponFactory {
* @return factory with specified {@link Builder}s
*/
static WeaponFactory factory(Consumer<Builder> consumer) {
Map<WeaponType, Supplier<Weapon>> map = new HashMap<>();
var map = new HashMap<WeaponType, Supplier<Weapon>>();
consumer.accept(map::put);
return name -> map.get(name).get();
}
......
......@@ -33,8 +33,7 @@ public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
......@@ -23,6 +23,8 @@
package com.iluwatar.factorykit.factorykit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.factorykit.Axe;
import com.iluwatar.factorykit.Spear;
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.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test Factory Kit Pattern
/**
* Test Factory Kit Pattern
*/
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
public void testSpearWeapon() {
Weapon weapon = factory.create(WeaponType.SPEAR);
var weapon = factory.create(WeaponType.SPEAR);
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
public void testAxeWeapon() {
Weapon weapon = factory.create(WeaponType.AXE);
var weapon = factory.create(WeaponType.AXE);
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
public void testWeapon() {
Weapon weapon = factory.create(WeaponType.SWORD);
var weapon = factory.create(WeaponType.SWORD);
verifyWeapon(weapon, Sword.class);
}
......
......@@ -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
```java
Blacksmith blacksmith = new ElfBlacksmith();
var blacksmith = new ElfBlacksmith();
blacksmith.manufactureWeapon(WeaponType.SPEAR);
blacksmith.manufactureWeapon(WeaponType.AXE);
// Elvish weapons are created
......
......@@ -64,7 +64,7 @@ public class App {
*/
public static void main(String[] args) {
// Lets go to war with Orc weapons
App app = new App(new OrcBlacksmith());
var app = new App(new OrcBlacksmith());
app.manufactureWeapons();
// Lets go to war with Elf weapons
......@@ -73,8 +73,7 @@ public class App {
}
private void manufactureWeapons() {
Weapon weapon;
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info(weapon.toString());
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info(weapon.toString());
......
......@@ -23,6 +23,7 @@
package com.iluwatar.factory.method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
......@@ -35,14 +36,12 @@ public class ElfBlacksmith implements Blacksmith {
static {
ELFARSENAL = new HashMap<>(WeaponType.values().length);
for (WeaponType type : WeaponType.values()) {
ELFARSENAL.put(type, new ElfWeapon(type));
}
Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAL.put(type, new ElfWeapon(type)));
}
@Override
public Weapon manufactureWeapon(WeaponType weaponType) {
return ELFARSENAL.get(weaponType);
}
}
......@@ -23,6 +23,7 @@
package com.iluwatar.factory.method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
......@@ -35,9 +36,7 @@ public class OrcBlacksmith implements Blacksmith {
static {
ORCARSENAL = new HashMap<>(WeaponType.values().length);
for (WeaponType type : WeaponType.values()) {
ORCARSENAL.put(type, new OrcWeapon(type));
}
Arrays.stream(WeaponType.values()).forEach(type -> ORCARSENAL.put(type, new OrcWeapon(type)));
}
@Override
......
......@@ -25,15 +25,12 @@ package com.iluwatar.factory.method;
import org.junit.jupiter.api.Test;
import java.io.IOException;
/**
* Tests that Factory Method example runs without errors.
*/
public class AppTest {
@Test
public void test() throws IOException {
String[] args = {};
App.main(args);
public void test() {
App.main(new String[]{});
}
}
......@@ -23,79 +23,80 @@
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.assertTrue;
import org.junit.jupiter.api.Test;
/**
* 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.
* 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
* derived classes—rather than by calling a constructor.
*
* <p>Factory produces the object of its liking.
* The weapon {@link Weapon} manufactured by the
* blacksmith depends on the kind of factory implementation it is referring to.
*
* <p>Factory produces the object of its liking.
* The weapon {@link Weapon} manufactured by the blacksmith depends on the kind of factory
* implementation it is referring to.
* </p>
*/
public class FactoryMethodTest {
/**
* Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance
* of {@link OrcWeapon}.
* Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of
* {@link OrcWeapon}.
*/
@Test
public void testOrcBlacksmithWithSpear() {
Blacksmith blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
var blacksmith = new OrcBlacksmith();
var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class);
}
/**
* Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance
* of {@link OrcWeapon}.
* Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance of
* {@link OrcWeapon}.
*/
@Test
public void testOrcBlacksmithWithAxe() {
Blacksmith blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
var blacksmith = new OrcBlacksmith();
var weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class);
}
/**
* Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an
* instance of {@link ElfWeapon}.
* Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an instance
* of {@link ElfWeapon}.
*/
@Test
public void testElfBlacksmithWithShortSword() {
Blacksmith blacksmith = new ElfBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
var blacksmith = new ElfBlacksmith();
var weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class);
}
/**
* Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance
* of {@link ElfWeapon}.
* Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance of
* {@link ElfWeapon}.
*/
@Test
public void testElfBlacksmithWithSpear() {
Blacksmith blacksmith = new ElfBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
var blacksmith = new ElfBlacksmith();
var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class);
}
/**
* This method asserts that the weapon object that is passed is an instance of the clazz and the
* 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 clazz expected class of the weapon
* @param clazz expected class of the weapon
*/
private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class<?> clazz) {
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);
}
}
......@@ -72,33 +72,33 @@ public class App {
*/
public static void main(String[] args) {
final Properties properties = new Properties();
final var properties = new Properties();
properties.put("enhancedWelcome", true);
Service service = new PropertiesFeatureToggleVersion(properties);
final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
var service = new PropertiesFeatureToggleVersion(properties);
final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
LOGGER.info(welcomeMessage);
// ---------------------------------------------
final Properties turnedOff = new Properties();
final var turnedOff = new Properties();
turnedOff.put("enhancedWelcome", false);
Service turnedOffService = new PropertiesFeatureToggleVersion(turnedOff);
final String welcomeMessageturnedOff =
var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff);
final var welcomeMessageturnedOff =
turnedOffService.getWelcomeMessage(new User("Jamie No Code"));
LOGGER.info(welcomeMessageturnedOff);
// --------------------------------------------
Service service2 = new TieredFeatureToggleVersion();
var service2 = new TieredFeatureToggleVersion();
final User paidUser = new User("Jamie Coder");
final User freeUser = new User("Alan Defect");
final var paidUser = new User("Jamie Coder");
final var freeUser = new User("Alan Defect");
UserGroup.addUserToPaidGroup(paidUser);
UserGroup.addUserToFreeGroup(freeUser);
final String welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser);
final String welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser);
final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser);
final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser);
LOGGER.info(welcomeMessageFreeUser);
LOGGER.info(welcomeMessagePaidUser);
}
......
......@@ -23,17 +23,15 @@
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
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
*/
......@@ -49,7 +47,7 @@ public class PropertiesFeatureToggleVersionTest {
@Test
public void testNonBooleanProperty() {
assertThrows(IllegalArgumentException.class, () -> {
final Properties properties = new Properties();
final var properties = new Properties();
properties.setProperty("enhancedWelcome", "Something");
new PropertiesFeatureToggleVersion(properties);
});
......@@ -57,21 +55,21 @@ public class PropertiesFeatureToggleVersionTest {
@Test
public void testFeatureTurnedOn() {
final Properties properties = new Properties();
final var properties = new Properties();
properties.put("enhancedWelcome", true);
Service service = new PropertiesFeatureToggleVersion(properties);
var service = new PropertiesFeatureToggleVersion(properties);
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);
}
@Test
public void testFeatureTurnedOff() {
final Properties properties = new Properties();
final var properties = new Properties();
properties.put("enhancedWelcome", false);
Service service = new PropertiesFeatureToggleVersion(properties);
var service = new PropertiesFeatureToggleVersion(properties);
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);
}
}
......@@ -23,15 +23,15 @@
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.user.User;
import com.iluwatar.featuretoggle.user.UserGroup;
import org.junit.jupiter.api.BeforeEach;
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
*/
......@@ -49,15 +49,15 @@ public class TieredFeatureToggleVersionTest {
@Test
public void testGetWelcomeMessageForPaidUser() {
final String welcomeMessage = service.getWelcomeMessage(paidUser);
final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software.";
final var welcomeMessage = service.getWelcomeMessage(paidUser);
final var expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software.";
assertEquals(expected, welcomeMessage);
}
@Test
public void testGetWelcomeMessageForFreeUser() {
final String welcomeMessage = service.getWelcomeMessage(freeUser);
final String expected = "I suppose you can use this software.";
final var welcomeMessage = service.getWelcomeMessage(freeUser);
final var expected = "I suppose you can use this software.";
assertEquals(expected, welcomeMessage);
}
......
......@@ -23,34 +23,34 @@
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Test User Group specific feature
*/
public class UserGroupTest {
@Test
public void testAddUserToFreeGroup() throws Exception {
User user = new User("Free User");
public void testAddUserToFreeGroup() {
var user = new User("Free User");
UserGroup.addUserToFreeGroup(user);
assertFalse(UserGroup.isPaid(user));
}
@Test
public void testAddUserToPaidGroup() throws Exception {
User user = new User("Paid User");
public void testAddUserToPaidGroup() {
var user = new User("Paid User");
UserGroup.addUserToPaidGroup(user);
assertTrue(UserGroup.isPaid(user));
}
@Test
public void testAddUserToPaidWhenOnFree() throws Exception {
User user = new User("Paid User");
public void testAddUserToPaidWhenOnFree() {
var user = new User("Paid User");
UserGroup.addUserToFreeGroup(user);
assertThrows(IllegalArgumentException.class, () -> {
UserGroup.addUserToPaidGroup(user);
......@@ -58,8 +58,8 @@ public class UserGroupTest {
}
@Test
public void testAddUserToFreeWhenOnPaid() throws Exception {
User user = new User("Free User");
public void testAddUserToFreeWhenOnPaid() {
var user = new User("Free User");
UserGroup.addUserToPaidGroup(user);
assertThrows(IllegalArgumentException.class, () -> {
UserGroup.addUserToFreeGroup(user);
......
......@@ -28,8 +28,6 @@ import static java.lang.String.valueOf;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
import java.util.function.Function;
......@@ -57,19 +55,23 @@ public class App {
*/
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>();
integerList.addAll(List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2,
-68, 45));
var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68);
prettyPrint("The initial list contains: ", integerList);
List<Integer> firstFiveNegatives =
SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).first(3).asList();
var firstFiveNegatives = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(negatives())
.first(3)
.asList();
prettyPrint("The first three negative values are: ", firstFiveNegatives);
List<Integer> lastTwoPositives =
SimpleFluentIterable.fromCopyOf(integerList).filter(positives()).last(2).asList();
var lastTwoPositives = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(positives())
.last(2)
.asList();
prettyPrint("The last two positive values are: ", lastTwoPositives);
SimpleFluentIterable
......@@ -79,15 +81,21 @@ public class App {
.ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber));
List<String> transformedList =
SimpleFluentIterable.fromCopyOf(integerList).filter(negatives()).map(transformToString())
.asList();
var transformedList = SimpleFluentIterable
.fromCopyOf(integerList)
.filter(negatives())
.map(transformToString())
.asList();
prettyPrint("A string-mapped list of negative numbers contains: ", transformedList);
List<String> lastTwoOfFirstFourStringMapped =
LazyFluentIterable.from(integerList).filter(positives()).first(4).last(2)
.map(number -> "String[" + valueOf(number) + "]").asList();
var lastTwoOfFirstFourStringMapped = LazyFluentIterable
.from(integerList)
.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 "
+ "mapped to Strings: ", lastTwoOfFirstFourStringMapped);
......@@ -96,12 +104,11 @@ public class App {
.filter(negatives())
.first(2)
.last()
.ifPresent(lastOfFirstTwo -> LOGGER
.info("The last of the first two negatives is: {}", lastOfFirstTwo));
.ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number));
}
private static Function<Integer, String> transformToString() {
return integer -> "String[" + valueOf(integer) + "]";
return integer -> "String[" + integer + "]";
}
private static Predicate<? super Integer> negatives() {
......@@ -116,14 +123,12 @@ public class App {
prettyPrint(", ", prefix, iterable);
}
private static <E> void prettyPrint(String delimiter, String prefix,
Iterable<E> iterable) {
StringJoiner joiner = new StringJoiner(delimiter, prefix, ".");
Iterator<E> iterator = iterable.iterator();
while (iterator.hasNext()) {
joiner.add(iterator.next().toString());
}
private static <E> void prettyPrint(
String delimiter, String prefix,
Iterable<E> iterable
) {
var joiner = new StringJoiner(delimiter, prefix, ".");
iterable.forEach(e -> joiner.add(e.toString()));
LOGGER.info(joiner.toString());
}
}
......@@ -24,7 +24,6 @@
package com.iluwatar.fluentinterface.fluentiterable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
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
*/
static <E> List<E> copyToList(Iterable<E> iterable) {
List<E> copy = new ArrayList<>();
Iterator<E> iterator = iterable.iterator();
while (iterator.hasNext()) {
copy.add(iterator.next());
}
var copy = new ArrayList<E>();
iterable.forEach(copy::add);
return copy;
}
}
......@@ -65,7 +65,7 @@ public abstract class DecoratingIterator<E> implements Iterator<E> {
if (next == null) {
return fromIterator.next();
} else {
final E result = next;
final var result = next;
next = null;
return result;
}
......
......@@ -67,14 +67,14 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public FluentIterable<E> filter(Predicate<? super E> predicate) {
return new LazyFluentIterable<E>() {
return new LazyFluentIterable<>() {
@Override
public Iterator<E> iterator() {
return new DecoratingIterator<E>(iterable.iterator()) {
@Override
public E computeNext() {
while (fromIterator.hasNext()) {
E candidate = fromIterator.next();
var candidate = fromIterator.next();
if (predicate.test(candidate)) {
return candidate;
}
......@@ -94,7 +94,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public Optional<E> first() {
Iterator<E> resultIterator = first(1).iterator();
var resultIterator = first(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
}
......@@ -116,7 +116,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
@Override
public E computeNext() {
if (currentIndex < count && fromIterator.hasNext()) {
E candidate = fromIterator.next();
var candidate = fromIterator.next();
currentIndex++;
return candidate;
}
......@@ -134,7 +134,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public Optional<E> last() {
Iterator<E> resultIterator = last(1).iterator();
var resultIterator = last(1).iterator();
return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
}
......@@ -162,25 +162,20 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
public E computeNext() {
initialize();
E candidate = null;
while (currentIndex < stopIndex && fromIterator.hasNext()) {
currentIndex++;
fromIterator.next();
}
if (currentIndex >= stopIndex && fromIterator.hasNext()) {
candidate = fromIterator.next();
return fromIterator.next();
}
return candidate;
return null;
}
private void initialize() {
if (list == null) {
list = new ArrayList<>();
Iterator<E> newIterator = iterable.iterator();
while (newIterator.hasNext()) {
list.add(newIterator.next());
}
iterable.forEach(list::add);
totalElementsCount = list.size();
stopIndex = totalElementsCount - count;
}
......
......@@ -62,9 +62,9 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public final FluentIterable<E> filter(Predicate<? super E> predicate) {
Iterator<E> iterator = iterator();
var iterator = iterator();
while (iterator.hasNext()) {
E nextElement = iterator.next();
var nextElement = iterator.next();
if (!predicate.test(nextElement)) {
iterator.remove();
}
......@@ -79,7 +79,7 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/
@Override
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();
}
......@@ -92,8 +92,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public final FluentIterable<E> first(int count) {
Iterator<E> iterator = iterator();
int currentCount = 0;
var iterator = iterator();
var currentCount = 0;
while (iterator.hasNext()) {
iterator.next();
if (currentCount >= count) {
......@@ -111,7 +111,7 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public final Optional<E> last() {
List<E> list = last(1).asList();
var list = last(1).asList();
if (list.isEmpty()) {
return Optional.empty();
}
......@@ -127,9 +127,9 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public final FluentIterable<E> last(int count) {
int remainingElementsCount = getRemainingElementsCount();
Iterator<E> iterator = iterator();
int currentIndex = 0;
var remainingElementsCount = getRemainingElementsCount();
var iterator = iterator();
var currentIndex = 0;
while (iterator.hasNext()) {
iterator.next();
if (currentIndex < remainingElementsCount - count) {
......@@ -150,11 +150,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
*/
@Override
public final <T> FluentIterable<T> map(Function<? super E, T> function) {
List<T> temporaryList = new ArrayList<>();
Iterator<E> iterator = iterator();
while (iterator.hasNext()) {
temporaryList.add(function.apply(iterator.next()));
}
var temporaryList = new ArrayList<T>();
this.forEach(e -> temporaryList.add(function.apply(e)));
return from(temporaryList);
}
......@@ -178,7 +175,7 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
}
public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) {
List<E> copy = FluentIterable.copyToList(iterable);
var copy = FluentIterable.copyToList(iterable);
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
*/
public final int getRemainingElementsCount() {
int counter = 0;
Iterator<E> iterator = iterator();
while (iterator.hasNext()) {
iterator.next();
var counter = 0;
for (var ignored : this) {
counter++;
}
return counter;
......@@ -219,10 +214,8 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
* @return a new List with the remaining objects.
*/
public static <E> List<E> toList(Iterator<E> iterator) {
List<E> copy = new ArrayList<>();
while (iterator.hasNext()) {
copy.add(iterator.next());
}
var copy = new ArrayList<E>();
iterator.forEachRemaining(copy::add);
return copy;
}
}
......@@ -32,7 +32,6 @@ public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
......@@ -23,16 +23,19 @@
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.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 7:00 PM
......@@ -50,28 +53,28 @@ public abstract class FluentIterableTest {
protected abstract FluentIterable<Integer> createFluentIterable(final Iterable<Integer> integers);
@Test
public void testFirst() throws Exception {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8);
final Optional<Integer> first = createFluentIterable(integers).first();
public void testFirst() {
final var integers = List.of(1, 2, 3, 10, 9, 8);
final var first = createFluentIterable(integers).first();
assertNotNull(first);
assertTrue(first.isPresent());
assertEquals(integers.get(0), first.get());
}
@Test
public void testFirstEmptyCollection() throws Exception {
final List<Integer> integers = Collections.emptyList();
final Optional<Integer> first = createFluentIterable(integers).first();
public void testFirstEmptyCollection() {
final var integers = Collections.<Integer>emptyList();
final var first = createFluentIterable(integers).first();
assertNotNull(first);
assertFalse(first.isPresent());
}
@Test
public void testFirstCount() throws Exception {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8);
final List<Integer> first4 = createFluentIterable(integers)
.first(4)
.asList();
public void testFirstCount() {
final var integers = List.of(1, 2, 3, 10, 9, 8);
final var first4 = createFluentIterable(integers)
.first(4)
.asList();
assertNotNull(first4);
assertEquals(4, first4.size());
......@@ -83,11 +86,11 @@ public abstract class FluentIterableTest {
}
@Test
public void testFirstCountLessItems() throws Exception {
final List<Integer> integers = List.of(1, 2, 3);
final List<Integer> first4 = createFluentIterable(integers)
.first(4)
.asList();
public void testFirstCountLessItems() {
final var integers = List.of(1, 2, 3);
final var first4 = createFluentIterable(integers)
.first(4)
.asList();
assertNotNull(first4);
assertEquals(3, first4.size());
......@@ -98,28 +101,28 @@ public abstract class FluentIterableTest {
}
@Test
public void testLast() throws Exception {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8);
final Optional<Integer> last = createFluentIterable(integers).last();
public void testLast() {
final var integers = List.of(1, 2, 3, 10, 9, 8);
final var last = createFluentIterable(integers).last();
assertNotNull(last);
assertTrue(last.isPresent());
assertEquals(integers.get(integers.size() - 1), last.get());
}
@Test
public void testLastEmptyCollection() throws Exception {
final List<Integer> integers = Collections.<Integer>emptyList();
final Optional<Integer> last = createFluentIterable(integers).last();
public void testLastEmptyCollection() {
final var integers = Collections.<Integer>emptyList();
final var last = createFluentIterable(integers).last();
assertNotNull(last);
assertFalse(last.isPresent());
}
@Test
public void testLastCount() throws Exception {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8);
final List<Integer> last4 = createFluentIterable(integers)
.last(4)
.asList();
public void testLastCount() {
final var integers = List.of(1, 2, 3, 10, 9, 8);
final var last4 = createFluentIterable(integers)
.last(4)
.asList();
assertNotNull(last4);
assertEquals(4, last4.size());
......@@ -130,11 +133,11 @@ public abstract class FluentIterableTest {
}
@Test
public void testLastCountLessItems() throws Exception {
final List<Integer> integers = List.of(1, 2, 3);
final List<Integer> last4 = createFluentIterable(integers)
.last(4)
.asList();
public void testLastCountLessItems() {
final var integers = List.of(1, 2, 3);
final var last4 = createFluentIterable(integers)
.last(4)
.asList();
assertNotNull(last4);
assertEquals(3, last4.size());
......@@ -145,11 +148,11 @@ public abstract class FluentIterableTest {
}
@Test
public void testFilter() throws Exception {
final List<Integer> integers = List.of(1, 2, 3, 10, 9, 8);
final List<Integer> evenItems = createFluentIterable(integers)
.filter(i -> i % 2 == 0)
.asList();
public void testFilter() {
final var integers = List.of(1, 2, 3, 10, 9, 8);
final var evenItems = createFluentIterable(integers)
.filter(i -> i % 2 == 0)
.asList();
assertNotNull(evenItems);
assertEquals(3, evenItems.size());
......@@ -159,11 +162,11 @@ public abstract class FluentIterableTest {
}
@Test
public void testMap() throws Exception {
final List<Integer> integers = List.of(1, 2, 3);
final List<Long> longs = createFluentIterable(integers)
.map(Integer::longValue)
.asList();
public void testMap() {
final var integers = List.of(1, 2, 3);
final var longs = createFluentIterable(integers)
.map(Integer::longValue)
.asList();
assertNotNull(longs);
assertEquals(integers.size(), longs.size());
......@@ -174,7 +177,7 @@ public abstract class FluentIterableTest {
@Test
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);
createFluentIterable(integers).forEach(consumer);
......@@ -188,8 +191,8 @@ public abstract class FluentIterableTest {
@Test
public void testSpliterator() throws Exception {
final List<Integer> integers = List.of(1, 2, 3);
final Spliterator<Integer> split = createFluentIterable(integers).spliterator();
final var integers = List.of(1, 2, 3);
final var split = createFluentIterable(integers).spliterator();
assertNotNull(split);
}
......
......@@ -54,13 +54,13 @@ public class App {
public static void main(String[] args) {
// initialize and wire the system
MenuStore menuStore = new MenuStore();
var menuStore = new MenuStore();
Dispatcher.getInstance().registerStore(menuStore);
ContentStore contentStore = new ContentStore();
var contentStore = new ContentStore();
Dispatcher.getInstance().registerStore(contentStore);
MenuView menuView = new MenuView();
var menuView = new MenuView();
menuStore.registerView(menuView);
ContentView contentView = new ContentView();
var contentView = new ContentView();
contentStore.registerView(contentView);
// render initial view
......
......@@ -70,6 +70,6 @@ public final class Dispatcher {
}
private void dispatchAction(Action action) {
stores.stream().forEach(store -> store.onAction(action));
stores.forEach(store -> store.onAction(action));
}
}
......@@ -38,7 +38,7 @@ public class ContentStore extends Store {
@Override
public void onAction(Action action) {
if (action.getType().equals(ActionType.CONTENT_CHANGED)) {
ContentAction contentAction = (ContentAction) action;
var contentAction = (ContentAction) action;
content = contentAction.getContent();
notifyChange();
}
......
......@@ -38,7 +38,7 @@ public class MenuStore extends Store {
@Override
public void onAction(Action action) {
if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
MenuAction menuAction = (MenuAction) action;
var menuAction = (MenuAction) action;
selected = menuAction.getMenuItem();
notifyChange();
}
......
......@@ -42,6 +42,6 @@ public abstract class Store {
}
protected void notifyChange() {
views.stream().forEach(view -> view.storeChanged(this));
views.forEach(view -> view.storeChanged(this));
}
}
......@@ -40,7 +40,7 @@ public class ContentView implements View {
@Override
public void storeChanged(Store store) {
ContentStore contentStore = (ContentStore) store;
var contentStore = (ContentStore) store;
content = contentStore.getContent();
render();
}
......
......@@ -41,14 +41,14 @@ public class MenuView implements View {
@Override
public void storeChanged(Store store) {
MenuStore menuStore = (MenuStore) store;
var menuStore = (MenuStore) store;
selected = menuStore.getSelected();
render();
}
@Override
public void render() {
for (MenuItem item : MenuItem.values()) {
for (var item : MenuItem.values()) {
if (selected.equals(item)) {
LOGGER.info("* {}", item);
} else {
......
......@@ -23,11 +23,11 @@
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.assertNotNull;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 10:11 PM
*
......@@ -36,9 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ContentTest {
@Test
public void testToString() throws Exception {
for (final Content content : Content.values()) {
final String toString = content.toString();
public void testToString() {
for (final var content : Content.values()) {
final var toString = content.toString();
assertNotNull(toString);
assertFalse(toString.trim().isEmpty());
}
......
......@@ -23,11 +23,11 @@
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.assertNotNull;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 10:15 PM
*
......@@ -36,9 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class MenuItemTest {
@Test
public void testToString() throws Exception {
for (final MenuItem menuItem : MenuItem.values()) {
final String toString = menuItem.toString();
public void testToString() {
for (final var menuItem : MenuItem.values()) {
final var toString = menuItem.toString();
assertNotNull(toString);
assertFalse(toString.trim().isEmpty());
}
......
......@@ -26,15 +26,12 @@ package com.iluwatar.flux.app;
import org.junit.jupiter.api.Test;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
......@@ -23,6 +23,14 @@
package com.iluwatar.flux.dispatcher;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
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 com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.ActionType;
import com.iluwatar.flux.action.Content;
......@@ -30,23 +38,12 @@ 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;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Date: 12/12/15 - 8:22 PM
*
......@@ -61,53 +58,56 @@ public class DispatcherTest {
*/
@BeforeEach
public void setUp() throws Exception {
final Constructor<Dispatcher> constructor;
constructor = Dispatcher.class.getDeclaredConstructor();
final var constructor = Dispatcher.class.getDeclaredConstructor();
constructor.setAccessible(true);
final Field field = Dispatcher.class.getDeclaredField("instance");
final var field = Dispatcher.class.getDeclaredField("instance");
field.setAccessible(true);
field.set(Dispatcher.getInstance(), constructor.newInstance());
}
@Test
public void testGetInstance() throws Exception {
public void testGetInstance() {
assertNotNull(Dispatcher.getInstance());
assertSame(Dispatcher.getInstance(), Dispatcher.getInstance());
}
@Test
public void testMenuItemSelected() throws Exception {
final Dispatcher dispatcher = Dispatcher.getInstance();
public void testMenuItemSelected() {
final var dispatcher = Dispatcher.getInstance();
final Store store = mock(Store.class);
final var store = mock(Store.class);
dispatcher.registerStore(store);
dispatcher.menuItemSelected(MenuItem.HOME);
dispatcher.menuItemSelected(MenuItem.COMPANY);
// 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());
verifyNoMoreInteractions(store);
final List<Action> actions = actionCaptor.getAllValues();
final List<MenuAction> menuActions = actions.stream()
.filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED))
.map(a -> (MenuAction) a)
.collect(Collectors.toList());
final var actions = actionCaptor.getAllValues();
final var menuActions = actions.stream()
.filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED))
.map(a -> (MenuAction) a)
.collect(Collectors.toList());
final List<ContentAction> contentActions = actions.stream()
.filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED))
.map(a -> (ContentAction) a)
.collect(Collectors.toList());
final var contentActions = actions.stream()
.filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED))
.map(a -> (ContentAction) a)
.collect(Collectors.toList());
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.COMPANY::equals).count());
assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals)
.count());
assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem)
.filter(MenuItem.COMPANY::equals).count());
assertEquals(2, contentActions.size());
assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.PRODUCTS::equals).count());
assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.COMPANY::equals).count());
assertEquals(1, contentActions.stream().map(ContentAction::getContent)
.filter(Content.PRODUCTS::equals).count());
assertEquals(1, contentActions.stream().map(ContentAction::getContent)
.filter(Content.COMPANY::equals).count());
}
......
......@@ -23,20 +23,20 @@
package com.iluwatar.flux.store;
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.view.View;
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;
import static org.mockito.Mockito.verifyZeroInteractions;
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.view.View;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 10:18 PM
......@@ -46,10 +46,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class ContentStoreTest {
@Test
public void testOnAction() throws Exception {
final ContentStore contentStore = new ContentStore();
public void testOnAction() {
final var contentStore = new ContentStore();
final View view = mock(View.class);
final var view = mock(View.class);
contentStore.registerView(view);
verifyZeroInteractions(view);
......
......@@ -23,20 +23,20 @@
package com.iluwatar.flux.store;
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.view.View;
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;
import static org.mockito.Mockito.verifyZeroInteractions;
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.view.View;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 10:18 PM
......@@ -46,10 +46,10 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class MenuStoreTest {
@Test
public void testOnAction() throws Exception {
final MenuStore menuStore = new MenuStore();
public void testOnAction() {
final var menuStore = new MenuStore();
final View view = mock(View.class);
final var view = mock(View.class);
menuStore.registerView(view);
verifyZeroInteractions(view);
......
......@@ -23,15 +23,15 @@
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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
......@@ -41,11 +41,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class ContentViewTest {
@Test
public void testStoreChanged() throws Exception {
final ContentStore store = mock(ContentStore.class);
public void testStoreChanged() {
final var store = mock(ContentStore.class);
when(store.getContent()).thenReturn(Content.PRODUCTS);
final ContentView view = new ContentView();
final var view = new ContentView();
view.storeChanged(store);
verify(store, times(1)).getContent();
......
......@@ -23,13 +23,6 @@
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.Mockito.mock;
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.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
*
......@@ -45,11 +45,11 @@ import static org.mockito.Mockito.when;
public class MenuViewTest {
@Test
public void testStoreChanged() throws Exception {
final MenuStore store = mock(MenuStore.class);
public void testStoreChanged() {
final var store = mock(MenuStore.class);
when(store.getSelected()).thenReturn(MenuItem.HOME);
final MenuView view = new MenuView();
final var view = new MenuView();
view.storeChanged(store);
verify(store, times(1)).getSelected();
......@@ -57,11 +57,11 @@ public class MenuViewTest {
}
@Test
public void testItemClicked() throws Exception {
final Store store = mock(Store.class);
public void testItemClicked() {
final var store = mock(Store.class);
Dispatcher.getInstance().registerStore(store);
final MenuView view = new MenuView();
final var view = new MenuView();
view.itemClicked(MenuItem.PRODUCTS);
// We should receive a menu click action and a content changed action
......
......@@ -72,7 +72,7 @@ public class PotionFactory {
}
Potion createPotion(PotionType type) {
Potion potion = potions.get(type);
var potion = potions.get(type);
if (potion == null) {
switch (type) {
case HEALING:
......@@ -99,7 +99,7 @@ public class PotionFactory {
And it can be used as below
```java
PotionFactory factory = new PotionFactory();
var factory = new PotionFactory();
factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818)
factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364)
factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818)
......
......@@ -23,7 +23,6 @@
package com.iluwatar.flyweight;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -42,7 +41,7 @@ public class AlchemistShop {
* Constructor.
*/
public AlchemistShop() {
PotionFactory factory = new PotionFactory();
var factory = new PotionFactory();
topShelf = List.of(
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.INVISIBILITY),
......@@ -68,7 +67,7 @@ public class AlchemistShop {
* @return The top shelf potions
*/
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
*/
public final List<Potion> getBottomShelf() {
return Collections.unmodifiableList(this.bottomShelf);
return List.copyOf(this.bottomShelf);
}
/**
* Enumerate potions.
*/
public void enumerate() {
LOGGER.info("Enumerating top shelf potions\n");
for (Potion p : topShelf) {
p.drink();
}
topShelf.forEach(Potion::drink);
LOGGER.info("Enumerating bottom shelf potions\n");
for (Potion p : bottomShelf) {
p.drink();
}
bottomShelf.forEach(Potion::drink);
}
}
......@@ -43,7 +43,7 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
AlchemistShop alchemistShop = new AlchemistShop();
var alchemistShop = new AlchemistShop();
alchemistShop.enumerate();
}
}
......@@ -40,7 +40,7 @@ public class PotionFactory {
}
Potion createPotion(PotionType type) {
Potion potion = potions.get(type);
var potion = potions.get(type);
if (potion == null) {
switch (type) {
case HEALING:
......
......@@ -23,14 +23,12 @@
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.assertNotNull;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
/**
* Date: 12/12/15 - 10:54 PM
*
......@@ -39,18 +37,18 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class AlchemistShopTest {
@Test
public void testShop() throws Exception {
final AlchemistShop shop = new AlchemistShop();
public void testShop() {
final var shop = new AlchemistShop();
final List<Potion> bottomShelf = shop.getBottomShelf();
final var bottomShelf = shop.getBottomShelf();
assertNotNull(bottomShelf);
assertEquals(5, bottomShelf.size());
final List<Potion> topShelf = shop.getTopShelf();
final var topShelf = shop.getTopShelf();
assertNotNull(topShelf);
assertEquals(8, topShelf.size());
final List<Potion> allPotions = new ArrayList<>();
final var allPotions = new ArrayList<Potion>();
allPotions.addAll(topShelf);
allPotions.addAll(bottomShelf);
......
......@@ -26,15 +26,12 @@ package com.iluwatar.flyweight;
import org.junit.jupiter.api.Test;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
......@@ -47,7 +47,7 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
FrontController controller = new FrontController();
var controller = new FrontController();
controller.handleRequest("Archer");
controller.handleRequest("Catapult");
controller.handleRequest("foobar");
......
......@@ -30,12 +30,12 @@ package com.iluwatar.front.controller;
public class FrontController {
public void handleRequest(String request) {
Command command = getCommand(request);
var command = getCommand(request);
command.process();
}
private Command getCommand(String request) {
Class<?> commandClass = getCommandClass(request);
var commandClass = getCommandClass(request);
try {
return (Command) commandClass.newInstance();
} catch (Exception e) {
......@@ -44,12 +44,10 @@ public class FrontController {
}
private static Class<?> getCommandClass(String request) {
Class<?> result;
try {
result = Class.forName("com.iluwatar.front.controller." + request + "Command");
return Class.forName("com.iluwatar.front.controller." + request + "Command");
} catch (ClassNotFoundException e) {
result = UnknownCommand.class;
return UnknownCommand.class;
}
return result;
}
}
......@@ -26,15 +26,12 @@ package com.iluwatar.front.controller;
import org.junit.jupiter.api.Test;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
......@@ -36,7 +36,7 @@ public class ApplicationExceptionTest {
@Test
public void testCause() {
final Exception cause = new Exception();
final var cause = new Exception();
assertSame(cause, new ApplicationException(cause).getCause());
}
......
......@@ -23,17 +23,15 @@
package com.iluwatar.front.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.front.controller.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
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
*
......@@ -54,11 +52,11 @@ public class CommandTest {
}
static List<Object[]> dataProvider() {
final List<Object[]> parameters = new ArrayList<>();
parameters.add(new Object[]{"Archer", "Displaying archers"});
parameters.add(new Object[]{"Catapult", "Displaying catapults"});
parameters.add(new Object[]{"NonExistentCommand", "Error 500"});
return parameters;
return List.of(
new Object[]{"Archer", "Displaying archers"},
new Object[]{"Catapult", "Displaying catapults"},
new Object[]{"NonExistentCommand", "Error 500"}
);
}
/**
......@@ -68,7 +66,7 @@ public class CommandTest {
@ParameterizedTest
@MethodSource("dataProvider")
public void testDisplay(String request, String displayMessage) {
final FrontController frontController = new FrontController();
final var frontController = new FrontController();
assertEquals(0, appender.getLogSize());
frontController.handleRequest(request);
assertEquals(displayMessage, appender.getLastMessage());
......
......@@ -23,17 +23,15 @@
package com.iluwatar.front.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.front.controller.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
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
*
......@@ -54,11 +52,11 @@ public class FrontControllerTest {
}
static List<Object[]> dataProvider() {
final List<Object[]> parameters = new ArrayList<>();
parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"});
parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"});
parameters.add(new Object[]{new UnknownCommand(), "Error 500"});
return parameters;
return List.of(
new Object[]{new ArcherCommand(), "Displaying archers"},
new Object[]{new CatapultCommand(), "Displaying catapults"},
new Object[]{new UnknownCommand(), "Error 500"}
);
}
/**
......
......@@ -23,17 +23,15 @@
package com.iluwatar.front.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.front.controller.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
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
*
......@@ -54,11 +52,11 @@ public class ViewTest {
}
static List<Object[]> dataProvider() {
final List<Object[]> parameters = new ArrayList<>();
parameters.add(new Object[]{new ArcherView(), "Displaying archers"});
parameters.add(new Object[]{new CatapultView(), "Displaying catapults"});
parameters.add(new Object[]{new ErrorView(), "Error 500"});
return parameters;
return List.of(
new Object[]{new ArcherView(), "Displaying archers"},
new Object[]{new CatapultView(), "Displaying catapults"},
new Object[]{new ErrorView(), "Error 500"}
);
}
/**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册