Java 11 migrate c-d (remaining) (#1111)

* Moves converter pattern to Java 11

* Moves cqrs pattern to Java 11

* Moves dao pattern to Java 11

* Moves data-bus pattern to Java 11

* Moves data-locality pattern to Java 11

* Moves data-mapper pattern to Java 11

* Moves data-transfer-object pattern to Java 11

* Moves decorator pattern to Java 11

* Moves delegation pattern to Java 11

* Moves dependency-injection to Java 11

* Moves dirty-flag to Java 11

* Moves double-buffer to Java 11

* Moves double-checked-locking to Java 11

* Moves double-dispatch to Java 11

* Corrects with changes thats breaking test cases
This commit is contained in:
Anurag Agarwal 2019-12-15 00:02:45 +05:30 committed by Ilkka Seppälä
parent 5681684157
commit ea57934db6
75 changed files with 576 additions and 713 deletions

View File

@ -63,20 +63,26 @@ The specialized converters inherit from this base class as follows.
public class UserConverter extends Converter<UserDto, User> { public class UserConverter extends Converter<UserDto, User> {
public UserConverter() { public UserConverter() {
super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), super(UserConverter::convertToEntity, UserConverter::convertToDto);
userDto.getEmail()),
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(),
user.getUserId()));
} }
private static UserDto convertToDto(User user) {
return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId());
}
private static User convertToEntity(UserDto dto) {
return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail());
}
} }
``` ```
Now mapping between User and UserDto becomes trivial. Now mapping between User and UserDto becomes trivial.
```java ```java
Converter<UserDto, User> userConverter = new UserConverter(); var userConverter = new UserConverter();
UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); var dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
User user = userConverter.convertFromDto(dtoUser); var user = userConverter.convertFromDto(dtoUser);
``` ```
## Class diagram ## Class diagram

View File

@ -49,8 +49,11 @@ public class App {
User user = userConverter.convertFromDto(dtoUser); User user = userConverter.convertFromDto(dtoUser);
LOGGER.info("Entity converted from DTO:" + user); LOGGER.info("Entity converted from DTO:" + user);
var users = List.of(new User("Camile", "Tough", false, "124sad"), var users = List.of(
new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); new User("Camile", "Tough", false, "124sad"),
new User("Marti", "Luther", true, "42309fd"),
new User("Kate", "Smith", true, "if0243")
);
LOGGER.info("Domain entities:"); LOGGER.info("Domain entities:");
users.stream().map(User::toString).forEach(LOGGER::info); users.stream().map(User::toString).forEach(LOGGER::info);

View File

@ -73,7 +73,7 @@ public class User {
if (o == null || getClass() != o.getClass()) { if (o == null || getClass() != o.getClass()) {
return false; return false;
} }
User user = (User) o; var user = (User) o;
return isActive == user.isActive && Objects.equals(firstName, user.firstName) && Objects return isActive == user.isActive && Objects.equals(firstName, user.firstName) && Objects
.equals(lastName, user.lastName) && Objects.equals(userId, user.userId); .equals(lastName, user.lastName) && Objects.equals(userId, user.userId);
} }

View File

@ -28,13 +28,16 @@ package com.iluwatar.converter;
*/ */
public class UserConverter extends Converter<UserDto, User> { public class UserConverter extends Converter<UserDto, User> {
/**
* Constructor.
*/
public UserConverter() { public UserConverter() {
super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), super(UserConverter::convertToEntity, UserConverter::convertToDto);
userDto.getEmail()),
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(),
user.getUserId()));
} }
private static UserDto convertToDto(User user) {
return new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), user.getUserId());
}
private static User convertToEntity(UserDto dto) {
return new User(dto.getFirstName(), dto.getLastName(), dto.isActive(), dto.getEmail());
}
} }

View File

@ -74,7 +74,7 @@ public class UserDto {
if (o == null || getClass() != o.getClass()) { if (o == null || getClass() != o.getClass()) {
return false; return false;
} }
UserDto userDto = (UserDto) o; var userDto = (UserDto) o;
return isActive == userDto.isActive && Objects.equals(firstName, userDto.firstName) && Objects return isActive == userDto.isActive && Objects.equals(firstName, userDto.firstName) && Objects
.equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email); .equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email);
} }

View File

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

View File

@ -23,12 +23,11 @@
package com.iluwatar.converter; package com.iluwatar.converter;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Tests for {@link Converter} * Tests for {@link Converter}
@ -42,8 +41,8 @@ public class ConverterTest {
*/ */
@Test @Test
public void testConversionsStartingFromDomain() { public void testConversionsStartingFromDomain() {
User u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); var u1 = new User("Tom", "Hanks", true, "tom@hanks.com");
User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); var u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1));
assertEquals(u1, u2); assertEquals(u1, u2);
} }
@ -52,37 +51,47 @@ public class ConverterTest {
*/ */
@Test @Test
public void testConversionsStartingFromDto() { public void testConversionsStartingFromDto() {
UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); var u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com");
UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); var u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1));
assertEquals(u1, u2); assertEquals(u1, u2);
} }
/** /**
* Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and cleanly
* cleanly instantiated allowing various different conversion strategies to be implemented. * instantiated allowing various different conversion strategies to be implemented.
*/ */
@Test @Test
public void testCustomConverter() { public void testCustomConverter() {
Converter<UserDto, User> converter = new Converter<>( var converter = new Converter<UserDto, User>(
userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), userDto -> new User(
String.valueOf(new Random().nextInt())), userDto.getFirstName(),
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), userDto.getLastName(),
user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")); userDto.isActive(),
User u1 = new User("John", "Doe", false, "12324"); String.valueOf(new Random().nextInt())
UserDto userDto = converter.convertFromEntity(u1); ),
user -> new UserDto(
user.getFirstName(),
user.getLastName(),
user.isActive(),
user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")
);
var u1 = new User("John", "Doe", false, "12324");
var userDto = converter.convertFromEntity(u1);
assertEquals("johndoe@whatever.com", userDto.getEmail()); assertEquals("johndoe@whatever.com", userDto.getEmail());
} }
/** /**
* Test whether converting a collection of Users to DTO Users and then converting them back to domain * Test whether converting a collection of Users to DTO Users and then converting them back to
* users returns an equal collection. * domain users returns an equal collection.
*/ */
@Test @Test
public void testCollectionConversion() { public void testCollectionConversion() {
List<User> users = List.of(new User("Camile", "Tough", false, "124sad"), var users = List.of(
new User("Marti", "Luther", true, "42309fd"), new User("Camile", "Tough", false, "124sad"),
new User("Kate", "Smith", true, "if0243")); new User("Marti", "Luther", true, "42309fd"),
List<User> fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); new User("Kate", "Smith", true, "if0243")
);
var fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users));
assertEquals(users, fromDtos); assertEquals(users, fromDtos);
} }
} }

View File

@ -24,15 +24,9 @@
package com.iluwatar.cqrs.app; package com.iluwatar.cqrs.app;
import com.iluwatar.cqrs.commandes.CommandServiceImpl; import com.iluwatar.cqrs.commandes.CommandServiceImpl;
import com.iluwatar.cqrs.commandes.ICommandService;
import com.iluwatar.cqrs.constants.AppConstants; import com.iluwatar.cqrs.constants.AppConstants;
import com.iluwatar.cqrs.dto.Author;
import com.iluwatar.cqrs.dto.Book;
import com.iluwatar.cqrs.queries.IQueryService;
import com.iluwatar.cqrs.queries.QueryServiceImpl; import com.iluwatar.cqrs.queries.QueryServiceImpl;
import com.iluwatar.cqrs.util.HibernateUtil; import com.iluwatar.cqrs.util.HibernateUtil;
import java.math.BigInteger;
import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -56,7 +50,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) {
ICommandService commands = new CommandServiceImpl(); var commands = new CommandServiceImpl();
// Create Authors and Books using CommandService // Create Authors and Books using CommandService
commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com"); commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com");
@ -72,15 +66,15 @@ public class App {
commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER); commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER);
commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans"); commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans");
IQueryService queries = new QueryServiceImpl(); var queries = new QueryServiceImpl();
// Query the database using QueryService // Query the database using QueryService
Author nullAuthor = queries.getAuthorByUsername("username"); var nullAuthor = queries.getAuthorByUsername("username");
Author evans = queries.getAuthorByUsername(AppConstants.E_EVANS); var evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
BigInteger blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH); var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
BigInteger authorsCount = queries.getAuthorsCount(); var authorsCount = queries.getAuthorsCount();
Book dddBook = queries.getBook("Domain-Driven Design"); var dddBook = queries.getBook("Domain-Driven Design");
List<Book> blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH); var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);
LOGGER.info("Author username : {}", nullAuthor); LOGGER.info("Author username : {}", nullAuthor);
LOGGER.info("Author evans : {}", evans); LOGGER.info("Author evans : {}", evans);

View File

@ -26,8 +26,6 @@ package com.iluwatar.cqrs.commandes;
import com.iluwatar.cqrs.domain.model.Author; import com.iluwatar.cqrs.domain.model.Author;
import com.iluwatar.cqrs.domain.model.Book; import com.iluwatar.cqrs.domain.model.Book;
import com.iluwatar.cqrs.util.HibernateUtil; import com.iluwatar.cqrs.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
/** /**
@ -39,9 +37,9 @@ public class CommandServiceImpl implements ICommandService {
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private Author getAuthorByUsername(String username) { private Author getAuthorByUsername(String username) {
Author author = null; Author author;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
Query query = session.createQuery("from Author where username=:username"); var query = session.createQuery("from Author where username=:username");
query.setParameter("username", username); query.setParameter("username", username);
author = (Author) query.uniqueResult(); author = (Author) query.uniqueResult();
} }
@ -53,9 +51,9 @@ public class CommandServiceImpl implements ICommandService {
} }
private Book getBookByTitle(String title) { private Book getBookByTitle(String title) {
Book book = null; Book book;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
Query query = session.createQuery("from Book where title=:title"); var query = session.createQuery("from Book where title=:title");
query.setParameter("title", title); query.setParameter("title", title);
book = (Book) query.uniqueResult(); book = (Book) query.uniqueResult();
} }
@ -68,8 +66,8 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void authorCreated(String username, String name, String email) { public void authorCreated(String username, String name, String email) {
Author author = new Author(username, name, email); var author = new Author(username, name, email);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.save(author); session.save(author);
session.getTransaction().commit(); session.getTransaction().commit();
@ -78,9 +76,9 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void bookAddedToAuthor(String title, double price, String username) { public void bookAddedToAuthor(String title, double price, String username) {
Author author = getAuthorByUsername(username); var author = getAuthorByUsername(username);
Book book = new Book(title, price, author); var book = new Book(title, price, author);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.save(book); session.save(book);
session.getTransaction().commit(); session.getTransaction().commit();
@ -89,9 +87,9 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void authorNameUpdated(String username, String name) { public void authorNameUpdated(String username, String name) {
Author author = getAuthorByUsername(username); var author = getAuthorByUsername(username);
author.setName(name); author.setName(name);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.update(author); session.update(author);
session.getTransaction().commit(); session.getTransaction().commit();
@ -100,9 +98,9 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void authorUsernameUpdated(String oldUsername, String newUsername) { public void authorUsernameUpdated(String oldUsername, String newUsername) {
Author author = getAuthorByUsername(oldUsername); var author = getAuthorByUsername(oldUsername);
author.setUsername(newUsername); author.setUsername(newUsername);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.update(author); session.update(author);
session.getTransaction().commit(); session.getTransaction().commit();
@ -111,9 +109,9 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void authorEmailUpdated(String username, String email) { public void authorEmailUpdated(String username, String email) {
Author author = getAuthorByUsername(username); var author = getAuthorByUsername(username);
author.setEmail(email); author.setEmail(email);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.update(author); session.update(author);
session.getTransaction().commit(); session.getTransaction().commit();
@ -122,9 +120,9 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void bookTitleUpdated(String oldTitle, String newTitle) { public void bookTitleUpdated(String oldTitle, String newTitle) {
Book book = getBookByTitle(oldTitle); var book = getBookByTitle(oldTitle);
book.setTitle(newTitle); book.setTitle(newTitle);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.update(book); session.update(book);
session.getTransaction().commit(); session.getTransaction().commit();
@ -133,9 +131,9 @@ public class CommandServiceImpl implements ICommandService {
@Override @Override
public void bookPriceUpdated(String title, double price) { public void bookPriceUpdated(String title, double price) {
Book book = getBookByTitle(title); var book = getBookByTitle(title);
book.setPrice(price); book.setPrice(price);
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
session.beginTransaction(); session.beginTransaction();
session.update(book); session.update(book);
session.getTransaction().commit(); session.getTransaction().commit();

View File

@ -80,7 +80,7 @@ public class Author {
if (!(obj instanceof Author)) { if (!(obj instanceof Author)) {
return false; return false;
} }
Author other = (Author) obj; var other = (Author) obj;
return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name
.equals(other.getName()); .equals(other.getName());

View File

@ -73,7 +73,7 @@ public class Book {
if (!(obj instanceof Book)) { if (!(obj instanceof Book)) {
return false; return false;
} }
Book book = (Book) obj; var book = (Book) obj;
return title.equals(book.getTitle()) && price == book.getPrice(); return title.equals(book.getTitle()) && price == book.getPrice();
} }

View File

@ -29,8 +29,6 @@ import com.iluwatar.cqrs.dto.Book;
import com.iluwatar.cqrs.util.HibernateUtil; import com.iluwatar.cqrs.util.HibernateUtil;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.List; import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers; import org.hibernate.transform.Transformers;
@ -44,9 +42,9 @@ public class QueryServiceImpl implements IQueryService {
@Override @Override
public Author getAuthorByUsername(String username) { public Author getAuthorByUsername(String username) {
Author authorDTo = null; Author authorDTo;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
SQLQuery sqlQuery = session.createSQLQuery("SELECT a.username as \"username\"," var sqlQuery = session.createSQLQuery("SELECT a.username as \"username\","
+ " a.name as \"name\", a.email as \"email\"" + " a.name as \"name\", a.email as \"email\""
+ "FROM Author a where a.username=:username"); + "FROM Author a where a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username); sqlQuery.setParameter(AppConstants.USER_NAME, username);
@ -58,9 +56,9 @@ public class QueryServiceImpl implements IQueryService {
@Override @Override
public Book getBook(String title) { public Book getBook(String title) {
Book bookDTo = null; Book bookDTo;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\"," var sqlQuery = session.createSQLQuery("SELECT b.title as \"title\","
+ " b.price as \"price\"" + " FROM Book b where b.title=:title"); + " b.price as \"price\"" + " FROM Book b where b.title=:title");
sqlQuery.setParameter("title", title); sqlQuery.setParameter("title", title);
bookDTo = bookDTo =
@ -71,9 +69,9 @@ public class QueryServiceImpl implements IQueryService {
@Override @Override
public List<Book> getAuthorBooks(String username) { public List<Book> getAuthorBooks(String username) {
List<Book> bookDTos = null; List<Book> bookDTos;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\", b.price as \"price\"" var sqlQuery = session.createSQLQuery("SELECT b.title as \"title\", b.price as \"price\""
+ " FROM Author a , Book b where b.author_id = a.id and a.username=:username"); + " FROM Author a , Book b where b.author_id = a.id and a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username); sqlQuery.setParameter(AppConstants.USER_NAME, username);
bookDTos = sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).list(); bookDTos = sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).list();
@ -83,9 +81,9 @@ public class QueryServiceImpl implements IQueryService {
@Override @Override
public BigInteger getAuthorBooksCount(String username) { public BigInteger getAuthorBooksCount(String username) {
BigInteger bookcount = null; BigInteger bookcount;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
SQLQuery sqlQuery = session.createSQLQuery( var sqlQuery = session.createSQLQuery(
"SELECT count(b.title)" + " FROM Book b, Author a" "SELECT count(b.title)" + " FROM Book b, Author a"
+ " where b.author_id = a.id and a.username=:username"); + " where b.author_id = a.id and a.username=:username");
sqlQuery.setParameter(AppConstants.USER_NAME, username); sqlQuery.setParameter(AppConstants.USER_NAME, username);
@ -96,9 +94,9 @@ public class QueryServiceImpl implements IQueryService {
@Override @Override
public BigInteger getAuthorsCount() { public BigInteger getAuthorsCount() {
BigInteger authorcount = null; BigInteger authorcount;
try (Session session = sessionFactory.openSession()) { try (var session = sessionFactory.openSession()) {
SQLQuery sqlQuery = session.createSQLQuery("SELECT count(id) from Author"); var sqlQuery = session.createSQLQuery("SELECT count(id) from Author");
authorcount = (BigInteger) sqlQuery.uniqueResult(); authorcount = (BigInteger) sqlQuery.uniqueResult();
} }
return authorcount; return authorcount;

View File

@ -25,7 +25,6 @@ package com.iluwatar.cqrs.util;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,8 +41,7 @@ public class HibernateUtil {
private static SessionFactory buildSessionFactory() { private static SessionFactory buildSessionFactory() {
// configures settings from hibernate.cfg.xml // configures settings from hibernate.cfg.xml
final StandardServiceRegistry registry = final var registry = new StandardServiceRegistryBuilder().configure().build();
new StandardServiceRegistryBuilder().configure().build();
try { try {
return new MetadataSources(registry).buildMetadata().buildSessionFactory(); return new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) { } catch (Exception ex) {

View File

@ -23,33 +23,28 @@
package com.iluwatar.cqrs; package com.iluwatar.cqrs;
import java.math.BigInteger; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.cqrs.commandes.CommandServiceImpl; import com.iluwatar.cqrs.commandes.CommandServiceImpl;
import com.iluwatar.cqrs.commandes.ICommandService;
import com.iluwatar.cqrs.dto.Author; import com.iluwatar.cqrs.dto.Author;
import com.iluwatar.cqrs.dto.Book; import com.iluwatar.cqrs.dto.Book;
import com.iluwatar.cqrs.queries.IQueryService; import com.iluwatar.cqrs.queries.IQueryService;
import com.iluwatar.cqrs.queries.QueryServiceImpl; import com.iluwatar.cqrs.queries.QueryServiceImpl;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
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;
/** /**
* Integration test of IQueryService and ICommandService with h2 data * Integration test of IQueryService and ICommandService with h2 data
*
*/ */
public class IntegrationTest { public class IntegrationTest {
private static IQueryService queryService; private static IQueryService queryService;
private static ICommandService commandService;
@BeforeAll @BeforeAll
public static void initializeAndPopulateDatabase() { public static void initializeAndPopulateDatabase() {
commandService = new CommandServiceImpl(); var commandService = new CommandServiceImpl();
queryService = new QueryServiceImpl(); queryService = new QueryServiceImpl();
// create first author1 // create first author1
@ -73,7 +68,7 @@ public class IntegrationTest {
@Test @Test
public void testGetAuthorByUsername() { public void testGetAuthorByUsername() {
Author author = queryService.getAuthorByUsername("username1"); var author = queryService.getAuthorByUsername("username1");
assertEquals("username1", author.getUsername()); assertEquals("username1", author.getUsername());
assertEquals("name1", author.getName()); assertEquals("name1", author.getName());
assertEquals("email1", author.getEmail()); assertEquals("email1", author.getEmail());
@ -81,22 +76,22 @@ public class IntegrationTest {
@Test @Test
public void testGetUpdatedAuthorByUsername() { public void testGetUpdatedAuthorByUsername() {
Author author = queryService.getAuthorByUsername("new_username2"); var author = queryService.getAuthorByUsername("new_username2");
Author expectedAuthor = new Author("new_name2", "new_email2", "new_username2"); var expectedAuthor = new Author("new_name2", "new_email2", "new_username2");
assertEquals(expectedAuthor, author); assertEquals(expectedAuthor, author);
} }
@Test @Test
public void testGetBook() { public void testGetBook() {
Book book = queryService.getBook("title1"); var book = queryService.getBook("title1");
assertEquals("title1", book.getTitle()); assertEquals("title1", book.getTitle());
assertEquals(10, book.getPrice(), 0.01); assertEquals(10, book.getPrice(), 0.01);
} }
@Test @Test
public void testGetAuthorBooks() { public void testGetAuthorBooks() {
List<Book> books = queryService.getAuthorBooks("username1"); var books = queryService.getAuthorBooks("username1");
assertEquals(2, books.size()); assertEquals(2, books.size());
assertTrue(books.contains(new Book("title1", 10))); assertTrue(books.contains(new Book("title1", 10)));
assertTrue(books.contains(new Book("new_title2", 30))); assertTrue(books.contains(new Book("new_title2", 30)));
@ -104,13 +99,13 @@ public class IntegrationTest {
@Test @Test
public void testGetAuthorBooksCount() { public void testGetAuthorBooksCount() {
BigInteger bookCount = queryService.getAuthorBooksCount("username1"); var bookCount = queryService.getAuthorBooksCount("username1");
assertEquals(new BigInteger("2"), bookCount); assertEquals(new BigInteger("2"), bookCount);
} }
@Test @Test
public void testGetAuthorsCount() { public void testGetAuthorsCount() {
BigInteger authorCount = queryService.getAuthorsCount(); var authorCount = queryService.getAuthorsCount();
assertEquals(new BigInteger("2"), authorCount); assertEquals(new BigInteger("2"), authorCount);
} }

View File

@ -23,11 +23,8 @@
package com.iluwatar.dao; package com.iluwatar.dao;
import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement;
import java.util.List; import java.util.List;
import java.util.stream.Stream;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource; import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -57,32 +54,32 @@ public class App {
* @throws Exception if any error occurs. * @throws Exception if any error occurs.
*/ */
public static void main(final String[] args) throws Exception { public static void main(final String[] args) throws Exception {
final CustomerDao inMemoryDao = new InMemoryCustomerDao(); final var inMemoryDao = new InMemoryCustomerDao();
performOperationsUsing(inMemoryDao); performOperationsUsing(inMemoryDao);
final DataSource dataSource = createDataSource(); final var dataSource = createDataSource();
createSchema(dataSource); createSchema(dataSource);
final CustomerDao dbDao = new DbCustomerDao(dataSource); final var dbDao = new DbCustomerDao(dataSource);
performOperationsUsing(dbDao); performOperationsUsing(dbDao);
deleteSchema(dataSource); deleteSchema(dataSource);
} }
private static void deleteSchema(DataSource dataSource) throws SQLException { private static void deleteSchema(DataSource dataSource) throws SQLException {
try (Connection connection = dataSource.getConnection(); try (var connection = dataSource.getConnection();
Statement statement = connection.createStatement()) { var statement = connection.createStatement()) {
statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL);
} }
} }
private static void createSchema(DataSource dataSource) throws SQLException { private static void createSchema(DataSource dataSource) throws SQLException {
try (Connection connection = dataSource.getConnection(); try (var connection = dataSource.getConnection();
Statement statement = connection.createStatement()) { var statement = connection.createStatement()) {
statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL);
} }
} }
private static DataSource createDataSource() { private static DataSource createDataSource() {
JdbcDataSource dataSource = new JdbcDataSource(); var dataSource = new JdbcDataSource();
dataSource.setURL(DB_URL); dataSource.setURL(DB_URL);
return dataSource; return dataSource;
} }
@ -90,18 +87,18 @@ public class App {
private static void performOperationsUsing(final CustomerDao customerDao) throws Exception { private static void performOperationsUsing(final CustomerDao customerDao) throws Exception {
addCustomers(customerDao); addCustomers(customerDao);
log.info(ALL_CUSTOMERS); log.info(ALL_CUSTOMERS);
try (Stream<Customer> customerStream = customerDao.getAll()) { try (var customerStream = customerDao.getAll()) {
customerStream.forEach((customer) -> log.info(customer.toString())); customerStream.forEach((customer) -> log.info(customer.toString()));
} }
log.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); log.info("customerDao.getCustomerById(2): " + customerDao.getById(2));
final Customer customer = new Customer(4, "Dan", "Danson"); final var customer = new Customer(4, "Dan", "Danson");
customerDao.add(customer); customerDao.add(customer);
log.info(ALL_CUSTOMERS + customerDao.getAll()); log.info(ALL_CUSTOMERS + customerDao.getAll());
customer.setFirstName("Daniel"); customer.setFirstName("Daniel");
customer.setLastName("Danielson"); customer.setLastName("Danielson");
customerDao.update(customer); customerDao.update(customer);
log.info(ALL_CUSTOMERS); log.info(ALL_CUSTOMERS);
try (Stream<Customer> customerStream = customerDao.getAll()) { try (var customerStream = customerDao.getAll()) {
customerStream.forEach((cust) -> log.info(cust.toString())); customerStream.forEach((cust) -> log.info(cust.toString()));
} }
customerDao.delete(customer); customerDao.delete(customer);
@ -109,7 +106,7 @@ public class App {
} }
private static void addCustomers(CustomerDao customerDao) throws Exception { private static void addCustomers(CustomerDao customerDao) throws Exception {
for (Customer customer : generateSampleCustomers()) { for (var customer : generateSampleCustomers()) {
customerDao.add(customer); customerDao.add(customer);
} }
} }
@ -120,9 +117,9 @@ public class App {
* @return list of customers. * @return list of customers.
*/ */
public static List<Customer> generateSampleCustomers() { public static List<Customer> generateSampleCustomers() {
final Customer customer1 = new Customer(1, "Adam", "Adamson"); final var customer1 = new Customer(1, "Adam", "Adamson");
final Customer customer2 = new Customer(2, "Bob", "Bobson"); final var customer2 = new Customer(2, "Bob", "Bobson");
final Customer customer3 = new Customer(3, "Carl", "Carlson"); final var customer3 = new Customer(3, "Carl", "Carlson");
return List.of(customer1, customer2, customer3); return List.of(customer1, customer2, customer3);
} }
} }

View File

@ -73,11 +73,11 @@ public class Customer {
@Override @Override
public boolean equals(final Object that) { public boolean equals(final Object that) {
boolean isEqual = false; var isEqual = false;
if (this == that) { if (this == that) {
isEqual = true; isEqual = true;
} else if (that != null && getClass() == that.getClass()) { } else if (that != null && getClass() == that.getClass()) {
final Customer customer = (Customer) that; final var customer = (Customer) that;
if (getId() == customer.getId()) { if (getId() == customer.getId()) {
isEqual = true; isEqual = true;
} }

View File

@ -65,13 +65,10 @@ public class DbCustomerDao implements CustomerDao {
*/ */
@Override @Override
public Stream<Customer> getAll() throws Exception { public Stream<Customer> getAll() throws Exception {
Connection connection;
try { try {
connection = getConnection(); var connection = getConnection();
PreparedStatement statement = var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS");
connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR
ResultSet resultSet = statement.executeQuery(); // NOSONAR
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE, return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE,
Spliterator.ORDERED) { Spliterator.ORDERED) {
@ -121,9 +118,8 @@ public class DbCustomerDao implements CustomerDao {
ResultSet resultSet = null; ResultSet resultSet = null;
try (Connection connection = getConnection(); try (var connection = getConnection();
PreparedStatement statement = var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) {
connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) {
statement.setInt(1, id); statement.setInt(1, id);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
@ -150,9 +146,8 @@ public class DbCustomerDao implements CustomerDao {
return false; return false;
} }
try (Connection connection = getConnection(); try (var connection = getConnection();
PreparedStatement statement = var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) {
connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) {
statement.setInt(1, customer.getId()); statement.setInt(1, customer.getId());
statement.setString(2, customer.getFirstName()); statement.setString(2, customer.getFirstName());
statement.setString(3, customer.getLastName()); statement.setString(3, customer.getLastName());
@ -168,8 +163,8 @@ public class DbCustomerDao implements CustomerDao {
*/ */
@Override @Override
public boolean update(Customer customer) throws Exception { public boolean update(Customer customer) throws Exception {
try (Connection connection = getConnection(); try (var connection = getConnection();
PreparedStatement statement = var statement =
connection connection
.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) { .prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) {
statement.setString(1, customer.getFirstName()); statement.setString(1, customer.getFirstName());
@ -186,9 +181,8 @@ public class DbCustomerDao implements CustomerDao {
*/ */
@Override @Override
public boolean delete(Customer customer) throws Exception { public boolean delete(Customer customer) throws Exception {
try (Connection connection = getConnection(); try (var connection = getConnection();
PreparedStatement statement = var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
statement.setInt(1, customer.getId()); statement.setInt(1, customer.getId());
return statement.executeUpdate() > 0; return statement.executeUpdate() > 0;
} catch (SQLException ex) { } catch (SQLException ex) {

View File

@ -31,7 +31,6 @@ import org.junit.jupiter.api.Test;
public class AppTest { public class AppTest {
@Test @Test
public void test() throws Exception { public void test() throws Exception {
String[] args = {}; App.main(new String[]{});
App.main(args);
} }
} }

View File

@ -46,36 +46,36 @@ public class CustomerTest {
@Test @Test
public void getAndSetId() { public void getAndSetId() {
final int newId = 2; final var newId = 2;
customer.setId(newId); customer.setId(newId);
assertEquals(newId, customer.getId()); assertEquals(newId, customer.getId());
} }
@Test @Test
public void getAndSetFirstname() { public void getAndSetFirstname() {
final String newFirstname = "Bill"; final var newFirstname = "Bill";
customer.setFirstName(newFirstname); customer.setFirstName(newFirstname);
assertEquals(newFirstname, customer.getFirstName()); assertEquals(newFirstname, customer.getFirstName());
} }
@Test @Test
public void getAndSetLastname() { public void getAndSetLastname() {
final String newLastname = "Clinton"; final var newLastname = "Clinton";
customer.setLastName(newLastname); customer.setLastName(newLastname);
assertEquals(newLastname, customer.getLastName()); assertEquals(newLastname, customer.getLastName());
} }
@Test @Test
public void notEqualWithDifferentId() { public void notEqualWithDifferentId() {
final int newId = 2; final var newId = 2;
final Customer otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME); final var otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME);
assertNotEquals(customer, otherCustomer); assertNotEquals(customer, otherCustomer);
assertNotEquals(customer.hashCode(), otherCustomer.hashCode()); assertNotEquals(customer.hashCode(), otherCustomer.hashCode());
} }
@Test @Test
public void equalsWithSameObjectValues() { public void equalsWithSameObjectValues() {
final Customer otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME); final var otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME);
assertEquals(customer, otherCustomer); assertEquals(customer, otherCustomer);
assertEquals(customer.hashCode(), otherCustomer.hashCode()); assertEquals(customer.hashCode(), otherCustomer.hashCode());
} }

View File

@ -23,20 +23,6 @@
package com.iluwatar.dao; package com.iluwatar.dao;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.stream.Stream;
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;
@ -46,6 +32,17 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/** /**
* Tests {@link DbCustomerDao}. * Tests {@link DbCustomerDao}.
*/ */
@ -57,12 +54,13 @@ public class DbCustomerDaoTest {
/** /**
* Creates customers schema. * Creates customers schema.
*
* @throws SQLException if there is any error while creating schema. * @throws SQLException if there is any error while creating schema.
*/ */
@BeforeEach @BeforeEach
public void createSchema() throws SQLException { public void createSchema() throws SQLException {
try (Connection connection = DriverManager.getConnection(DB_URL); try (var connection = DriverManager.getConnection(DB_URL);
Statement statement = connection.createStatement()) { var statement = connection.createStatement()) {
statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL);
} }
} }
@ -75,14 +73,15 @@ public class DbCustomerDaoTest {
/** /**
* Setup for connection success scenario. * Setup for connection success scenario.
*
* @throws Exception if any error occurs. * @throws Exception if any error occurs.
*/ */
@BeforeEach @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
JdbcDataSource dataSource = new JdbcDataSource(); var dataSource = new JdbcDataSource();
dataSource.setURL(DB_URL); dataSource.setURL(DB_URL);
dao = new DbCustomerDao(dataSource); dao = new DbCustomerDao(dataSource);
boolean result = dao.add(existingCustomer); var result = dao.add(existingCustomer);
assertTrue(result); assertTrue(result);
} }
@ -94,12 +93,12 @@ public class DbCustomerDaoTest {
@Test @Test
public void addingShouldResultInSuccess() throws Exception { public void addingShouldResultInSuccess() throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) { try (var allCustomers = dao.getAll()) {
assumeTrue(allCustomers.count() == 1); assumeTrue(allCustomers.count() == 1);
} }
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
boolean result = dao.add(nonExistingCustomer); var result = dao.add(nonExistingCustomer);
assertTrue(result); assertTrue(result);
assertCustomerCountIs(2); assertCustomerCountIs(2);
@ -108,8 +107,8 @@ public class DbCustomerDaoTest {
@Test @Test
public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
boolean result = dao.delete(nonExistingCustomer); var result = dao.delete(nonExistingCustomer);
assertFalse(result); assertFalse(result);
assertCustomerCountIs(1); assertCustomerCountIs(1);
@ -117,11 +116,11 @@ public class DbCustomerDaoTest {
@Test @Test
public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
final int nonExistingId = getNonExistingCustomerId(); final var nonExistingId = getNonExistingCustomerId();
final String newFirstname = "Douglas"; final var newFirstname = "Douglas";
final String newLastname = "MacArthur"; final var newLastname = "MacArthur";
final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); final var customer = new Customer(nonExistingId, newFirstname, newLastname);
boolean result = dao.update(customer); var result = dao.update(customer);
assertFalse(result); assertFalse(result);
assertFalse(dao.getById(nonExistingId).isPresent()); assertFalse(dao.getById(nonExistingId).isPresent());
@ -136,16 +135,14 @@ public class DbCustomerDaoTest {
/** /**
* Represents a scenario where DAO operations are being performed on an already existing * Represents a scenario where DAO operations are being performed on an already existing
* customer. * customer.
*
*/ */
@Nested @Nested
public class ExistingCustomer { public class ExistingCustomer {
@Test @Test
public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); var existingCustomer = new Customer(1, "Freddy", "Krueger");
var result = dao.add(existingCustomer);
boolean result = dao.add(existingCustomer);
assertFalse(result); assertFalse(result);
assertCustomerCountIs(1); assertCustomerCountIs(1);
@ -154,7 +151,7 @@ public class DbCustomerDaoTest {
@Test @Test
public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
boolean result = dao.delete(existingCustomer); var result = dao.delete(existingCustomer);
assertTrue(result); assertTrue(result);
assertCustomerCountIs(0); assertCustomerCountIs(0);
@ -162,15 +159,16 @@ public class DbCustomerDaoTest {
} }
@Test @Test
public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws
final String newFirstname = "Bernard"; Exception {
final String newLastname = "Montgomery"; final var newFirstname = "Bernard";
final Customer customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); final var newLastname = "Montgomery";
boolean result = dao.update(customer); final var customer = new Customer(existingCustomer.getId(), newFirstname, newLastname);
var result = dao.update(customer);
assertTrue(result); assertTrue(result);
final Customer cust = dao.getById(existingCustomer.getId()).get(); final var cust = dao.getById(existingCustomer.getId()).get();
assertEquals(newFirstname, cust.getFirstName()); assertEquals(newFirstname, cust.getFirstName());
assertEquals(newLastname, cust.getLastName()); assertEquals(newLastname, cust.getLastName());
} }
@ -178,28 +176,28 @@ public class DbCustomerDaoTest {
} }
/** /**
* Represents a scenario where DB connectivity is not present due to network issue, or * Represents a scenario where DB connectivity is not present due to network issue, or DB service
* DB service unavailable. * unavailable.
*
*/ */
@Nested @Nested
public class ConnectivityIssue { public class ConnectivityIssue {
private static final String EXCEPTION_CAUSE = "Connection not available"; private static final String EXCEPTION_CAUSE = "Connection not available";
/** /**
* setup a connection failure scenario. * setup a connection failure scenario.
*
* @throws SQLException if any error occurs. * @throws SQLException if any error occurs.
*/ */
@BeforeEach @BeforeEach
public void setUp() throws SQLException { public void setUp() throws SQLException {
dao = new DbCustomerDao(mockedDatasource()); dao = new DbCustomerDao(mockedDatasource());
} }
private DataSource mockedDatasource() throws SQLException { private DataSource mockedDatasource() throws SQLException {
DataSource mockedDataSource = mock(DataSource.class); var mockedDataSource = mock(DataSource.class);
Connection mockedConnection = mock(Connection.class); var mockedConnection = mock(Connection.class);
SQLException exception = new SQLException(EXCEPTION_CAUSE); var exception = new SQLException(EXCEPTION_CAUSE);
doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString());
doReturn(mockedConnection).when(mockedDataSource).getConnection(); doReturn(mockedConnection).when(mockedDataSource).getConnection();
return mockedDataSource; return mockedDataSource;
@ -211,30 +209,30 @@ public class DbCustomerDaoTest {
dao.add(new Customer(2, "Bernard", "Montgomery")); dao.add(new Customer(2, "Bernard", "Montgomery"));
}); });
} }
@Test @Test
public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() { public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() {
assertThrows(Exception.class, () -> { assertThrows(Exception.class, () -> {
dao.delete(existingCustomer); dao.delete(existingCustomer);
}); });
} }
@Test @Test
public void updatingACustomerFailsWithFeedbackToTheClient() { public void updatingACustomerFailsWithFeedbackToTheClient() {
final String newFirstname = "Bernard"; final var newFirstname = "Bernard";
final String newLastname = "Montgomery"; final var newLastname = "Montgomery";
assertThrows(Exception.class, () -> { assertThrows(Exception.class, () -> {
dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname));
}); });
} }
@Test @Test
public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() { public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() {
assertThrows(Exception.class, () -> { assertThrows(Exception.class, () -> {
dao.getById(existingCustomer.getId()); dao.getById(existingCustomer.getId());
}); });
} }
@Test @Test
public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() {
assertThrows(Exception.class, () -> { assertThrows(Exception.class, () -> {
@ -246,18 +244,19 @@ public class DbCustomerDaoTest {
/** /**
* Delete customer schema for fresh setup per test. * Delete customer schema for fresh setup per test.
*
* @throws SQLException if any error occurs. * @throws SQLException if any error occurs.
*/ */
@AfterEach @AfterEach
public void deleteSchema() throws SQLException { public void deleteSchema() throws SQLException {
try (Connection connection = DriverManager.getConnection(DB_URL); try (var connection = DriverManager.getConnection(DB_URL);
Statement statement = connection.createStatement()) { var statement = connection.createStatement()) {
statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL);
} }
} }
private void assertCustomerCountIs(int count) throws Exception { private void assertCustomerCountIs(int count) throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) { try (var allCustomers = dao.getAll()) {
assertEquals(count, allCustomers.count()); assertEquals(count, allCustomers.count());
} }
} }
@ -265,7 +264,7 @@ public class DbCustomerDaoTest {
/** /**
* An arbitrary number which does not correspond to an active Customer id. * An arbitrary number which does not correspond to an active Customer id.
* *
* @return an int of a customer id which doesn't exist * @return an int of a customer id which doesn't exist
*/ */
private int getNonExistingCustomerId() { private int getNonExistingCustomerId() {

View File

@ -23,18 +23,15 @@
package com.iluwatar.dao; package com.iluwatar.dao;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.stream.Stream;
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.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/** /**
* Tests {@link InMemoryCustomerDao}. * Tests {@link InMemoryCustomerDao}.
*/ */
@ -50,20 +47,20 @@ public class InMemoryCustomerDaoTest {
} }
/** /**
* Represents the scenario when the DAO operations are being performed on a non existent * Represents the scenario when the DAO operations are being performed on a non existent
* customer. * customer.
*/ */
@Nested @Nested
public class NonExistingCustomer { public class NonExistingCustomer {
@Test @Test
public void addingShouldResultInSuccess() throws Exception { public void addingShouldResultInSuccess() throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) { try (var allCustomers = dao.getAll()) {
assumeTrue(allCustomers.count() == 1); assumeTrue(allCustomers.count() == 1);
} }
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
boolean result = dao.add(nonExistingCustomer); var result = dao.add(nonExistingCustomer);
assertTrue(result); assertTrue(result);
assertCustomerCountIs(2); assertCustomerCountIs(2);
@ -72,8 +69,8 @@ public class InMemoryCustomerDaoTest {
@Test @Test
public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
boolean result = dao.delete(nonExistingCustomer); var result = dao.delete(nonExistingCustomer);
assertFalse(result); assertFalse(result);
assertCustomerCountIs(1); assertCustomerCountIs(1);
@ -81,11 +78,11 @@ public class InMemoryCustomerDaoTest {
@Test @Test
public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
final int nonExistingId = getNonExistingCustomerId(); final var nonExistingId = getNonExistingCustomerId();
final String newFirstname = "Douglas"; final var newFirstname = "Douglas";
final String newLastname = "MacArthur"; final var newLastname = "MacArthur";
final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); final var customer = new Customer(nonExistingId, newFirstname, newLastname);
boolean result = dao.update(customer); var result = dao.update(customer);
assertFalse(result); assertFalse(result);
assertFalse(dao.getById(nonExistingId).isPresent()); assertFalse(dao.getById(nonExistingId).isPresent());
@ -106,7 +103,7 @@ public class InMemoryCustomerDaoTest {
@Test @Test
public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
boolean result = dao.add(CUSTOMER); var result = dao.add(CUSTOMER);
assertFalse(result); assertFalse(result);
assertCustomerCountIs(1); assertCustomerCountIs(1);
@ -115,7 +112,7 @@ public class InMemoryCustomerDaoTest {
@Test @Test
public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
boolean result = dao.delete(CUSTOMER); var result = dao.delete(CUSTOMER);
assertTrue(result); assertTrue(result);
assertCustomerCountIs(0); assertCustomerCountIs(0);
@ -123,23 +120,24 @@ public class InMemoryCustomerDaoTest {
} }
@Test @Test
public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws
final String newFirstname = "Bernard"; Exception {
final String newLastname = "Montgomery"; final var newFirstname = "Bernard";
final Customer customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); final var newLastname = "Montgomery";
boolean result = dao.update(customer); final var customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname);
var result = dao.update(customer);
assertTrue(result); assertTrue(result);
final Customer cust = dao.getById(CUSTOMER.getId()).get(); final var cust = dao.getById(CUSTOMER.getId()).get();
assertEquals(newFirstname, cust.getFirstName()); assertEquals(newFirstname, cust.getFirstName());
assertEquals(newLastname, cust.getLastName()); assertEquals(newLastname, cust.getLastName());
} }
@Test @Test
public void retriveShouldReturnTheCustomer() { public void retriveShouldReturnTheCustomer() {
Optional<Customer> optionalCustomer = dao.getById(CUSTOMER.getId()); var optionalCustomer = dao.getById(CUSTOMER.getId());
assertTrue(optionalCustomer.isPresent()); assertTrue(optionalCustomer.isPresent());
assertEquals(CUSTOMER, optionalCustomer.get()); assertEquals(CUSTOMER, optionalCustomer.get());
} }
@ -147,15 +145,15 @@ public class InMemoryCustomerDaoTest {
/** /**
* An arbitrary number which does not correspond to an active Customer id. * An arbitrary number which does not correspond to an active Customer id.
* *
* @return an int of a customer id which doesn't exist * @return an int of a customer id which doesn't exist
*/ */
private int getNonExistingCustomerId() { private int getNonExistingCustomerId() {
return 999; return 999;
} }
private void assertCustomerCountIs(int count) throws Exception { private void assertCustomerCountIs(int count) throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) { try (var allCustomers = dao.getAll()) {
assertEquals(count, allCustomers.count()); assertEquals(count, allCustomers.count());
} }
} }

View File

@ -59,11 +59,11 @@ import java.time.LocalDateTime;
class App { class App {
public static void main(String[] args) { public static void main(String[] args) {
final DataBus bus = DataBus.getInstance(); final var bus = DataBus.getInstance();
bus.subscribe(new StatusMember(1)); bus.subscribe(new StatusMember(1));
bus.subscribe(new StatusMember(2)); bus.subscribe(new StatusMember(2));
final MessageCollectorMember foo = new MessageCollectorMember("Foo"); final var foo = new MessageCollectorMember("Foo");
final MessageCollectorMember bar = new MessageCollectorMember("Bar"); final var bar = new MessageCollectorMember("Bar");
bus.subscribe(foo); bus.subscribe(foo);
bus.publish(StartingData.of(LocalDateTime.now())); bus.publish(StartingData.of(LocalDateTime.now()));
bus.publish(MessageData.of("Only Foo should see this")); bus.publish(MessageData.of("Only Foo should see this"));

View File

@ -27,7 +27,6 @@ import com.iluwatar.databus.DataType;
import com.iluwatar.databus.Member; import com.iluwatar.databus.Member;
import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.MessageData;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -61,6 +60,6 @@ public class MessageCollectorMember implements Member {
} }
public List<String> getMessages() { public List<String> getMessages() {
return Collections.unmodifiableList(messages); return List.copyOf(messages);
} }
} }

View File

@ -23,14 +23,14 @@
package com.iluwatar.databus; package com.iluwatar.databus;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
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.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
/** /**
* Tests for {@link DataBus}. * Tests for {@link DataBus}.
* *
@ -52,7 +52,7 @@ public class DataBusTest {
@Test @Test
public void publishedEventIsReceivedBySubscribedMember() { public void publishedEventIsReceivedBySubscribedMember() {
//given //given
final DataBus dataBus = DataBus.getInstance(); final var dataBus = DataBus.getInstance();
dataBus.subscribe(member); dataBus.subscribe(member);
//when //when
dataBus.publish(event); dataBus.publish(event);
@ -63,7 +63,7 @@ public class DataBusTest {
@Test @Test
public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() {
//given //given
final DataBus dataBus = DataBus.getInstance(); final var dataBus = DataBus.getInstance();
dataBus.subscribe(member); dataBus.subscribe(member);
dataBus.unsubscribe(member); dataBus.unsubscribe(member);
//when //when

View File

@ -23,15 +23,14 @@
package com.iluwatar.databus.members; package com.iluwatar.databus.members;
import com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
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 com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
/** /**
* Tests for {@link MessageCollectorMember}. * Tests for {@link MessageCollectorMember}.
* *
@ -42,9 +41,9 @@ public class MessageCollectorMemberTest {
@Test @Test
public void collectMessageFromMessageData() { public void collectMessageFromMessageData() {
//given //given
final String message = "message"; final var message = "message";
final MessageData messageData = new MessageData(message); final var messageData = new MessageData(message);
final MessageCollectorMember collector = new MessageCollectorMember("collector"); final var collector = new MessageCollectorMember("collector");
//when //when
collector.accept(messageData); collector.accept(messageData);
//then //then
@ -54,8 +53,8 @@ public class MessageCollectorMemberTest {
@Test @Test
public void collectIgnoresMessageFromOtherDataTypes() { public void collectIgnoresMessageFromOtherDataTypes() {
//given //given
final StartingData startingData = new StartingData(LocalDateTime.now()); final var startingData = new StartingData(LocalDateTime.now());
final MessageCollectorMember collector = new MessageCollectorMember("collector"); final var collector = new MessageCollectorMember("collector");
//when //when
collector.accept(startingData); collector.accept(startingData);
//then //then

View File

@ -23,17 +23,16 @@
package com.iluwatar.databus.members; package com.iluwatar.databus.members;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.iluwatar.databus.DataBus; import com.iluwatar.databus.DataBus;
import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.MessageData;
import com.iluwatar.databus.data.StartingData; import com.iluwatar.databus.data.StartingData;
import com.iluwatar.databus.data.StoppingData; import com.iluwatar.databus.data.StoppingData;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.Month; import java.time.Month;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/** /**
* Tests for {@link StatusMember}. * Tests for {@link StatusMember}.
@ -45,9 +44,9 @@ public class StatusMemberTest {
@Test @Test
public void statusRecordsTheStartTime() { public void statusRecordsTheStartTime() {
//given //given
final LocalDateTime startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); final var startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9);
final StartingData startingData = new StartingData(startTime); final var startingData = new StartingData(startTime);
final StatusMember statusMember = new StatusMember(1); final var statusMember = new StatusMember(1);
//when //when
statusMember.accept(startingData); statusMember.accept(startingData);
//then //then
@ -57,10 +56,10 @@ public class StatusMemberTest {
@Test @Test
public void statusRecordsTheStopTime() { public void statusRecordsTheStopTime() {
//given //given
final LocalDateTime stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); final var stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12);
final StoppingData stoppingData = new StoppingData(stop); final var stoppingData = new StoppingData(stop);
stoppingData.setDataBus(DataBus.getInstance()); stoppingData.setDataBus(DataBus.getInstance());
final StatusMember statusMember = new StatusMember(1); final var statusMember = new StatusMember(1);
//when //when
statusMember.accept(stoppingData); statusMember.accept(stoppingData);
//then //then
@ -70,8 +69,8 @@ public class StatusMemberTest {
@Test @Test
public void statusIgnoresMessageData() { public void statusIgnoresMessageData() {
//given //given
final MessageData messageData = new MessageData("message"); final var messageData = new MessageData("message");
final StatusMember statusMember = new StatusMember(1); final var statusMember = new StatusMember(1);
//when //when
statusMember.accept(messageData); statusMember.accept(messageData);
//then //then

View File

@ -46,7 +46,7 @@ public class Application {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
LOGGER.info("Start Game Application using Data-Locality pattern"); LOGGER.info("Start Game Application using Data-Locality pattern");
GameEntity gameEntity = new GameEntity(NUM_ENTITIES); var gameEntity = new GameEntity(NUM_ENTITIES);
gameEntity.start(); gameEntity.start();
gameEntity.update(); gameEntity.update();
} }

View File

@ -25,6 +25,7 @@ package com.iluwatar.data.locality.game.component.manager;
import com.iluwatar.data.locality.game.component.AiComponent; import com.iluwatar.data.locality.game.component.AiComponent;
import com.iluwatar.data.locality.game.component.Component; import com.iluwatar.data.locality.game.component.Component;
import java.util.stream.IntStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -50,9 +51,7 @@ public class AiComponentManager {
*/ */
public void start() { public void start() {
LOGGER.info("Start AI Game Component"); LOGGER.info("Start AI Game Component");
for (int i = 0; i < numEntities; i++) { IntStream.range(0, numEntities).forEach(i -> AI_COMPONENTS[i] = new AiComponent());
AI_COMPONENTS[i] = new AiComponent();
}
} }
/** /**
@ -60,10 +59,8 @@ public class AiComponentManager {
*/ */
public void update() { public void update() {
LOGGER.info("Update AI Game Component"); LOGGER.info("Update AI Game Component");
for (int i = 0; i < numEntities; i++) { IntStream.range(0, numEntities)
if (AI_COMPONENTS.length > i && AI_COMPONENTS[i] != null) { .filter(i -> AI_COMPONENTS.length > i && AI_COMPONENTS[i] != null)
AI_COMPONENTS[i].update(); .forEach(i -> AI_COMPONENTS[i].update());
}
}
} }
} }

View File

@ -25,6 +25,7 @@ package com.iluwatar.data.locality.game.component.manager;
import com.iluwatar.data.locality.game.component.Component; import com.iluwatar.data.locality.game.component.Component;
import com.iluwatar.data.locality.game.component.PhysicsComponent; import com.iluwatar.data.locality.game.component.PhysicsComponent;
import java.util.stream.IntStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -50,9 +51,7 @@ public class PhysicsComponentManager {
*/ */
public void start() { public void start() {
LOGGER.info("Start Physics Game Component "); LOGGER.info("Start Physics Game Component ");
for (int i = 0; i < numEntities; i++) { IntStream.range(0, numEntities).forEach(i -> PHYSICS_COMPONENTS[i] = new PhysicsComponent());
PHYSICS_COMPONENTS[i] = new PhysicsComponent();
}
} }
@ -62,10 +61,8 @@ public class PhysicsComponentManager {
public void update() { public void update() {
LOGGER.info("Update Physics Game Component "); LOGGER.info("Update Physics Game Component ");
// Process physics. // Process physics.
for (int i = 0; i < numEntities; i++) { IntStream.range(0, numEntities)
if (PHYSICS_COMPONENTS.length > i && PHYSICS_COMPONENTS[i] != null) { .filter(i -> PHYSICS_COMPONENTS.length > i && PHYSICS_COMPONENTS[i] != null)
PHYSICS_COMPONENTS[i].update(); .forEach(i -> PHYSICS_COMPONENTS[i].update());
}
}
} }
} }

View File

@ -25,6 +25,7 @@ package com.iluwatar.data.locality.game.component.manager;
import com.iluwatar.data.locality.game.component.Component; import com.iluwatar.data.locality.game.component.Component;
import com.iluwatar.data.locality.game.component.RenderComponent; import com.iluwatar.data.locality.game.component.RenderComponent;
import java.util.stream.IntStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -50,9 +51,7 @@ public class RenderComponentManager {
*/ */
public void start() { public void start() {
LOGGER.info("Start Render Game Component "); LOGGER.info("Start Render Game Component ");
for (int i = 0; i < numEntities; i++) { IntStream.range(0, numEntities).forEach(i -> RENDER_COMPONENTS[i] = new RenderComponent());
RENDER_COMPONENTS[i] = new RenderComponent();
}
} }
@ -62,10 +61,8 @@ public class RenderComponentManager {
public void render() { public void render() {
LOGGER.info("Update Render Game Component "); LOGGER.info("Update Render Game Component ");
// Process Render. // Process Render.
for (int i = 0; i < numEntities; i++) { IntStream.range(0, numEntities)
if (RENDER_COMPONENTS.length > i && RENDER_COMPONENTS[i] != null) { .filter(i -> RENDER_COMPONENTS.length > i && RENDER_COMPONENTS[i] != null)
RENDER_COMPONENTS[i].render(); .forEach(i -> RENDER_COMPONENTS[i].render());
}
}
} }
} }

View File

@ -23,7 +23,6 @@
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.util.Optional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -51,10 +50,10 @@ public final class App {
public static void main(final String... args) { public static void main(final String... args) {
/* Create new data mapper for type 'first' */ /* Create new data mapper for type 'first' */
final StudentDataMapper mapper = new StudentDataMapperImpl(); final var mapper = new StudentDataMapperImpl();
/* Create new student */ /* Create new student */
Student student = new Student(1, "Adam", 'A'); var student = new Student(1, "Adam", 'A');
/* Add student in respectibe store */ /* Add student in respectibe store */
mapper.insert(student); mapper.insert(student);
@ -62,7 +61,7 @@ public final class App {
log.debug(STUDENT_STRING + student + ", is inserted"); log.debug(STUDENT_STRING + student + ", is inserted");
/* Find this student */ /* Find this student */
final Optional<Student> studentToBeFound = mapper.find(student.getStudentId()); final var studentToBeFound = mapper.find(student.getStudentId());
log.debug(STUDENT_STRING + studentToBeFound + ", is searched"); log.debug(STUDENT_STRING + studentToBeFound + ", is searched");

View File

@ -85,7 +85,7 @@ public final class Student implements Serializable {
isEqual = true; isEqual = true;
} else if (inputObject != null && getClass() == inputObject.getClass()) { } else if (inputObject != null && getClass() == inputObject.getClass()) {
final Student inputStudent = (Student) inputObject; final var inputStudent = (Student) inputObject;
/* If student id matched */ /* If student id matched */
if (this.getStudentId() == inputStudent.getStudentId()) { if (this.getStudentId() == inputStudent.getStudentId()) {

View File

@ -37,71 +37,36 @@ public final class StudentDataMapperImpl implements StudentDataMapper {
@Override @Override
public Optional<Student> find(int studentId) { public Optional<Student> find(int studentId) {
return this.getStudents().stream().filter(x -> x.getStudentId() == studentId).findFirst();
/* Compare with existing students */
for (final Student student : this.getStudents()) {
/* Check if student is found */
if (student.getStudentId() == studentId) {
return Optional.of(student);
}
}
/* Return empty value */
return Optional.empty();
} }
@Override @Override
public void update(Student studentToBeUpdated) throws DataMapperException { public void update(Student studentToBeUpdated) throws DataMapperException {
String name = studentToBeUpdated.getName();
Integer index = Optional.of(studentToBeUpdated)
/* Check with existing students */ .map(Student::getStudentId)
if (this.getStudents().contains(studentToBeUpdated)) { .flatMap(this::find)
.map(students::indexOf)
/* Get the index of student in list */ .orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found"));
final int index = this.getStudents().indexOf(studentToBeUpdated); students.set(index, studentToBeUpdated);
/* Update the student in list */
this.getStudents().set(index, studentToBeUpdated);
} else {
/* Throw user error after wrapping in a runtime exception */
throw new DataMapperException("Student [" + studentToBeUpdated.getName() + "] is not found");
}
} }
@Override @Override
public void insert(Student studentToBeInserted) throws DataMapperException { public void insert(Student studentToBeInserted) throws DataMapperException {
Optional<Student> student = find(studentToBeInserted.getStudentId());
/* Check with existing students */ if (student.isPresent()) {
if (!this.getStudents().contains(studentToBeInserted)) { String name = studentToBeInserted.getName();
throw new DataMapperException("Student already [" + name + "] exists");
/* Add student in list */
this.getStudents().add(studentToBeInserted);
} else {
/* Throw user error after wrapping in a runtime exception */
throw new DataMapperException("Student already [" + studentToBeInserted
.getName() + "] exists");
} }
students.add(studentToBeInserted);
} }
@Override @Override
public void delete(Student studentToBeDeleted) throws DataMapperException { public void delete(Student studentToBeDeleted) throws DataMapperException {
if (!students.remove(studentToBeDeleted)) {
/* Check with existing students */ String name = studentToBeDeleted.getName();
if (this.getStudents().contains(studentToBeDeleted)) { throw new DataMapperException("Student [" + name + "] is not found");
/* Delete the student from list */
this.getStudents().remove(studentToBeDeleted);
} else {
/* Throw user error after wrapping in a runtime exception */
throw new DataMapperException("Student [" + studentToBeDeleted.getName() + "] is not found");
} }
} }

View File

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

View File

@ -23,11 +23,11 @@
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
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.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
/** /**
* The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the
* database. Its responsibility is to transfer data between the two and also to isolate them from * database. Its responsibility is to transfer data between the two and also to isolate them from
@ -46,11 +46,11 @@ public class DataMapperTest {
public void testFirstDataMapper() { public void testFirstDataMapper() {
/* Create new data mapper of first type */ /* Create new data mapper of first type */
final StudentDataMapper mapper = new StudentDataMapperImpl(); final var mapper = new StudentDataMapperImpl();
/* Create new student */ /* Create new student */
int studentId = 1; var studentId = 1;
Student student = new Student(studentId, "Adam", 'A'); var student = new Student(studentId, "Adam", 'A');
/* Add student in respectibe db */ /* Add student in respectibe db */
mapper.insert(student); mapper.insert(student);
@ -59,7 +59,7 @@ public class DataMapperTest {
assertEquals(studentId, mapper.find(student.getStudentId()).get().getStudentId()); assertEquals(studentId, mapper.find(student.getStudentId()).get().getStudentId());
/* Update existing student object */ /* Update existing student object */
String updatedName = "AdamUpdated"; var updatedName = "AdamUpdated";
student = new Student(student.getStudentId(), updatedName, 'A'); student = new Student(student.getStudentId(), updatedName, 'A');
/* Update student in respectibe db */ /* Update student in respectibe db */

View File

@ -23,12 +23,10 @@
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/** /**
* Tests {@link Student}. * Tests {@link Student}.
@ -36,8 +34,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public final class StudentTest { public final class StudentTest {
/** /**
* This API tests the equality behaviour of Student object * This API tests the equality behaviour of Student object Object Equality should work as per
* Object Equality should work as per logic defined in equals method * logic defined in equals method
* *
* @throws Exception if any execution error during test * @throws Exception if any execution error during test
*/ */
@ -45,9 +43,9 @@ public final class StudentTest {
public void testEquality() throws Exception { public void testEquality() throws Exception {
/* Create some students */ /* Create some students */
final Student firstStudent = new Student(1, "Adam", 'A'); final var firstStudent = new Student(1, "Adam", 'A');
final Student secondStudent = new Student(2, "Donald", 'B'); final var secondStudent = new Student(2, "Donald", 'B');
final Student secondSameStudent = new Student(2, "Donald", 'B'); final var secondSameStudent = new Student(2, "Donald", 'B');
/* Check equals functionality: should return 'true' */ /* Check equals functionality: should return 'true' */
assertEquals(firstStudent, firstStudent); assertEquals(firstStudent, firstStudent);

View File

@ -48,16 +48,14 @@ public class CustomerClientApp {
* @param args program argument. * @param args program argument.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
List<CustomerDto> customers = new ArrayList<>(); var customerOne = new CustomerDto("1", "Kelly", "Brown");
CustomerDto customerOne = new CustomerDto("1", "Kelly", "Brown"); var customerTwo = new CustomerDto("2", "Alfonso", "Bass");
CustomerDto customerTwo = new CustomerDto("2", "Alfonso", "Bass"); var customers = new ArrayList<>(List.of(customerOne, customerTwo));
customers.add(customerOne);
customers.add(customerTwo);
CustomerResource customerResource = new CustomerResource(customers); var customerResource = new CustomerResource(customers);
LOGGER.info("All customers:-"); LOGGER.info("All customers:-");
List<CustomerDto> allCustomers = customerResource.getAllCustomers(); var allCustomers = customerResource.getAllCustomers();
printCustomerDetails(allCustomers); printCustomerDetails(allCustomers);
LOGGER.info("----------------------------------------------------------"); LOGGER.info("----------------------------------------------------------");
@ -70,7 +68,7 @@ public class CustomerClientApp {
LOGGER.info("----------------------------------------------------------"); LOGGER.info("----------------------------------------------------------");
LOGGER.info("Adding customer three}"); LOGGER.info("Adding customer three}");
CustomerDto customerThree = new CustomerDto("3", "Lynda", "Blair"); var customerThree = new CustomerDto("3", "Lynda", "Blair");
customerResource.save(customerThree); customerResource.save(customerThree);
allCustomers = customerResource.getAllCustomers(); allCustomers = customerResource.getAllCustomers();
printCustomerDetails(allCustomers); printCustomerDetails(allCustomers);

View File

@ -23,13 +23,12 @@
package com.iluwatar.datatransfer; package com.iluwatar.datatransfer;
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* tests {@link CustomerResource}. * tests {@link CustomerResource}.
@ -37,13 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class CustomerResourceTest { public class CustomerResourceTest {
@Test @Test
public void shouldGetAllCustomers() { public void shouldGetAllCustomers() {
CustomerDto customer = new CustomerDto("1", "Melody", "Yates"); var customers = List.of(new CustomerDto("1", "Melody", "Yates"));
List<CustomerDto> customers = new ArrayList<>(); var customerResource = new CustomerResource(customers);
customers.add(customer); var allCustomers = customerResource.getAllCustomers();
CustomerResource customerResource = new CustomerResource(customers);
List<CustomerDto> allCustomers = customerResource.getAllCustomers();
assertEquals(1, allCustomers.size()); assertEquals(1, allCustomers.size());
assertEquals("1", allCustomers.get(0).getId()); assertEquals("1", allCustomers.get(0).getId());
@ -53,12 +48,12 @@ public class CustomerResourceTest {
@Test @Test
public void shouldSaveCustomer() { public void shouldSaveCustomer() {
CustomerDto customer = new CustomerDto("1", "Rita", "Reynolds"); var customer = new CustomerDto("1", "Rita", "Reynolds");
CustomerResource customerResource = new CustomerResource(new ArrayList<>()); var customerResource = new CustomerResource(new ArrayList<>());
customerResource.save(customer); customerResource.save(customer);
List<CustomerDto> allCustomers = customerResource.getAllCustomers(); var allCustomers = customerResource.getAllCustomers();
assertEquals("1", allCustomers.get(0).getId()); assertEquals("1", allCustomers.get(0).getId());
assertEquals("Rita", allCustomers.get(0).getFirstName()); assertEquals("Rita", allCustomers.get(0).getFirstName());
assertEquals("Reynolds", allCustomers.get(0).getLastName()); assertEquals("Reynolds", allCustomers.get(0).getLastName());
@ -66,15 +61,13 @@ public class CustomerResourceTest {
@Test @Test
public void shouldDeleteCustomer() { public void shouldDeleteCustomer() {
CustomerDto customer = new CustomerDto("1", "Terry", "Nguyen"); var customer = new CustomerDto("1", "Terry", "Nguyen");
List<CustomerDto> customers = new ArrayList<>(); var customers = new ArrayList<>(List.of(customer));
customers.add(customer); var customerResource = new CustomerResource(customers);
CustomerResource customerResource = new CustomerResource(customers);
customerResource.delete(customer.getId()); customerResource.delete(customer.getId());
List<CustomerDto> allCustomers = customerResource.getAllCustomers(); var allCustomers = customerResource.getAllCustomers();
assertTrue(allCustomers.isEmpty()); assertTrue(allCustomers.isEmpty());
} }

View File

@ -98,12 +98,12 @@ Here's the troll in action
```java ```java
// simple troll // simple troll
Troll troll = new SimpleTroll(); var troll = new SimpleTroll();
troll.attack(); // The troll tries to grab you! troll.attack(); // The troll tries to grab you!
troll.fleeBattle(); // The troll shrieks in horror and runs away! troll.fleeBattle(); // The troll shrieks in horror and runs away!
// change the behavior of the simple troll by adding a decorator // change the behavior of the simple troll by adding a decorator
Troll clubbedTroll = new ClubbedTroll(troll); var clubbedTroll = new ClubbedTroll(troll);
clubbedTroll.attack(); // The troll tries to grab you! The troll swings at you with a club! clubbedTroll.attack(); // The troll tries to grab you! The troll swings at you with a club!
clubbedTroll.fleeBattle(); // The troll shrieks in horror and runs away! clubbedTroll.fleeBattle(); // The troll shrieks in horror and runs away!
``` ```

View File

@ -49,14 +49,14 @@ public class App {
// simple troll // simple troll
LOGGER.info("A simple looking troll approaches."); LOGGER.info("A simple looking troll approaches.");
Troll troll = new SimpleTroll(); var troll = new SimpleTroll();
troll.attack(); troll.attack();
troll.fleeBattle(); troll.fleeBattle();
LOGGER.info("Simple troll power {}.\n", troll.getAttackPower()); LOGGER.info("Simple troll power {}.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator // change the behavior of the simple troll by adding a decorator
LOGGER.info("A troll with huge club surprises you."); LOGGER.info("A troll with huge club surprises you.");
Troll clubbedTroll = new ClubbedTroll(troll); var clubbedTroll = new ClubbedTroll(troll);
clubbedTroll.attack(); clubbedTroll.attack();
clubbedTroll.fleeBattle(); clubbedTroll.fleeBattle();
LOGGER.info("Clubbed troll power {}.\n", clubbedTroll.getAttackPower()); LOGGER.info("Clubbed troll power {}.\n", clubbedTroll.getAttackPower());

View File

@ -26,15 +26,12 @@ package com.iluwatar.decorator;
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,14 +23,14 @@
package com.iluwatar.decorator; package com.iluwatar.decorator;
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.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
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 static org.mockito.internal.verification.VerificationModeFactory.times; import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.junit.jupiter.api.Test;
/** /**
* Tests for {@link ClubbedTroll} * Tests for {@link ClubbedTroll}
*/ */
@ -39,10 +39,10 @@ public class ClubbedTrollTest {
@Test @Test
public void testClubbedTroll() { public void testClubbedTroll() {
// Create a normal troll first, but make sure we can spy on it later on. // Create a normal troll first, but make sure we can spy on it later on.
final Troll simpleTroll = spy(new SimpleTroll()); final var simpleTroll = spy(new SimpleTroll());
// Now we want to decorate the troll to make it stronger ... // Now we want to decorate the troll to make it stronger ...
final Troll clubbed = new ClubbedTroll(simpleTroll); final var clubbed = new ClubbedTroll(simpleTroll);
assertEquals(20, clubbed.getAttackPower()); assertEquals(20, clubbed.getAttackPower());
verify(simpleTroll, times(1)).getAttackPower(); verify(simpleTroll, times(1)).getAttackPower();

View File

@ -23,19 +23,18 @@
package com.iluwatar.decorator; package com.iluwatar.decorator;
import static org.junit.jupiter.api.Assertions.assertEquals;
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;
/** /**
* Tests for {@link SimpleTroll} * Tests for {@link SimpleTroll}
*/ */
@ -55,7 +54,7 @@ public class SimpleTrollTest {
@Test @Test
public void testTrollActions() { public void testTrollActions() {
final SimpleTroll troll = new SimpleTroll(); final var troll = new SimpleTroll();
assertEquals(10, troll.getAttackPower()); assertEquals(10, troll.getAttackPower());
troll.attack(); troll.attack();

View File

@ -51,9 +51,9 @@ 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) {
PrinterController hpPrinterController = new PrinterController(new HpPrinter()); var hpPrinterController = new PrinterController(new HpPrinter());
PrinterController canonPrinterController = new PrinterController(new CanonPrinter()); var canonPrinterController = new PrinterController(new CanonPrinter());
PrinterController epsonPrinterController = new PrinterController(new EpsonPrinter()); var epsonPrinterController = new PrinterController(new EpsonPrinter());
hpPrinterController.print(MESSAGE_TO_PRINT); hpPrinterController.print(MESSAGE_TO_PRINT);
canonPrinterController.print(MESSAGE_TO_PRINT); canonPrinterController.print(MESSAGE_TO_PRINT);

View File

@ -32,8 +32,7 @@ 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,21 @@
package com.iluwatar.delegation.simple; package com.iluwatar.delegation.simple;
import static org.junit.jupiter.api.Assertions.assertEquals;
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 com.iluwatar.delegation.simple.printers.CanonPrinter; import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter; import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter; import com.iluwatar.delegation.simple.printers.HpPrinter;
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;
/** /**
* Test for Delegation Pattern * Test for Delegation Pattern
*/ */
@ -60,7 +59,7 @@ public class DelegateTest {
@Test @Test
public void testCanonPrinter() throws Exception { public void testCanonPrinter() throws Exception {
PrinterController printerController = new PrinterController(new CanonPrinter()); var printerController = new PrinterController(new CanonPrinter());
printerController.print(MESSAGE); printerController.print(MESSAGE);
assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage()); assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage());
@ -68,7 +67,7 @@ public class DelegateTest {
@Test @Test
public void testHpPrinter() throws Exception { public void testHpPrinter() throws Exception {
PrinterController printerController = new PrinterController(new HpPrinter()); var printerController = new PrinterController(new HpPrinter());
printerController.print(MESSAGE); printerController.print(MESSAGE);
assertEquals("HP Printer : Test Message Printed", appender.getLastMessage()); assertEquals("HP Printer : Test Message Printed", appender.getLastMessage());
@ -76,7 +75,7 @@ public class DelegateTest {
@Test @Test
public void testEpsonPrinter() throws Exception { public void testEpsonPrinter() throws Exception {
PrinterController printerController = new PrinterController(new EpsonPrinter()); var printerController = new PrinterController(new EpsonPrinter());
printerController.print(MESSAGE); printerController.print(MESSAGE);
assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage());

View File

@ -24,7 +24,6 @@
package com.iluwatar.dependency.injection; package com.iluwatar.dependency.injection;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector;
/** /**
* Dependency Injection pattern deals with how objects handle their dependencies. The pattern * Dependency Injection pattern deals with how objects handle their dependencies. The pattern
@ -55,18 +54,18 @@ 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) {
SimpleWizard simpleWizard = new SimpleWizard(); var simpleWizard = new SimpleWizard();
simpleWizard.smoke(); simpleWizard.smoke();
AdvancedWizard advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco()); var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
advancedWizard.smoke(); advancedWizard.smoke();
AdvancedSorceress advancedSorceress = new AdvancedSorceress(); var advancedSorceress = new AdvancedSorceress();
advancedSorceress.setTobacco(new SecondBreakfastTobacco()); advancedSorceress.setTobacco(new SecondBreakfastTobacco());
advancedSorceress.smoke(); advancedSorceress.smoke();
Injector injector = Guice.createInjector(new TobaccoModule()); var injector = Guice.createInjector(new TobaccoModule());
GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class); var guiceWizard = injector.getInstance(GuiceWizard.class);
guiceWizard.smoke(); guiceWizard.smoke();
} }
} }

View File

@ -23,13 +23,14 @@
package com.iluwatar.dependency.injection; package com.iluwatar.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.dependency.injection.utils.InMemoryAppender; import com.iluwatar.dependency.injection.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.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 28/04/17 - 7:40 AM * Date: 28/04/17 - 7:40 AM
@ -52,27 +53,29 @@ public class AdvancedSorceressTest {
} }
/** /**
* Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to her * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to
* through the setter's parameter * her through the setter's parameter
*/ */
@Test @Test
public void testSmokeEveryThing() throws Exception { public void testSmokeEveryThing() throws Exception {
final Tobacco[] tobaccos = { List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() new OldTobyTobacco(),
}; new RivendellTobacco(),
new SecondBreakfastTobacco()
);
for (final Tobacco tobacco : tobaccos) { // Verify if the sorceress is smoking the correct tobacco ...
final AdvancedSorceress advancedSorceress = new AdvancedSorceress(); tobaccos.forEach(tobacco -> {
final var advancedSorceress = new AdvancedSorceress();
advancedSorceress.setTobacco(tobacco); advancedSorceress.setTobacco(tobacco);
advancedSorceress.smoke(); advancedSorceress.smoke();
// Verify if the sorceress is smoking the correct tobacco ... String lastMessage = appender.getLastMessage();
assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), lastMessage);
});
}
// ... and nothing else is happening. // ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize()); assertEquals(tobaccos.size(), appender.getLogSize());
} }
} }

View File

@ -23,13 +23,14 @@
package com.iluwatar.dependency.injection; package com.iluwatar.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.dependency.injection.utils.InMemoryAppender; import com.iluwatar.dependency.injection.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.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 12/10/15 - 8:40 PM * Date: 12/10/15 - 8:40 PM
@ -57,21 +58,22 @@ public class AdvancedWizardTest {
@Test @Test
public void testSmokeEveryThing() throws Exception { public void testSmokeEveryThing() throws Exception {
final Tobacco[] tobaccos = { List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() new OldTobyTobacco(),
}; new RivendellTobacco(),
new SecondBreakfastTobacco()
);
for (final Tobacco tobacco : tobaccos) { // Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco);
advancedWizard.smoke(); advancedWizard.smoke();
String lastMessage = appender.getLastMessage();
// Verify if the wizard is smoking the correct tobacco ... assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); });
}
// ... and nothing else is happening. // ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize()); assertEquals(tobaccos.size(), appender.getLogSize());
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.dependency.injection;
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,16 +23,16 @@
package com.iluwatar.dependency.injection; package com.iluwatar.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector;
import com.iluwatar.dependency.injection.utils.InMemoryAppender; import com.iluwatar.dependency.injection.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.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 12/10/15 - 8:57 PM * Date: 12/10/15 - 8:57 PM
* *
@ -59,20 +59,22 @@ public class GuiceWizardTest {
@Test @Test
public void testSmokeEveryThingThroughConstructor() throws Exception { public void testSmokeEveryThingThroughConstructor() throws Exception {
final Tobacco[] tobaccos = { List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() new OldTobyTobacco(),
}; new RivendellTobacco(),
new SecondBreakfastTobacco()
);
for (final Tobacco tobacco : tobaccos) { // Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final GuiceWizard guiceWizard = new GuiceWizard(tobacco); final GuiceWizard guiceWizard = new GuiceWizard(tobacco);
guiceWizard.smoke(); guiceWizard.smoke();
String lastMessage = appender.getLastMessage();
// Verify if the wizard is smoking the correct tobacco ... assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); });
}
// ... and nothing else is happening. // ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize()); assertEquals(tobaccos.size(), appender.getLogSize());
} }
/** /**
@ -82,30 +84,30 @@ public class GuiceWizardTest {
@Test @Test
public void testSmokeEveryThingThroughInjectionFramework() throws Exception { public void testSmokeEveryThingThroughInjectionFramework() throws Exception {
@SuppressWarnings("unchecked") List<Class<? extends Tobacco>> tobaccos = List.of(
final Class<? extends Tobacco>[] tobaccos = new Class[]{ OldTobyTobacco.class,
OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class RivendellTobacco.class,
}; SecondBreakfastTobacco.class
);
for (final Class<? extends Tobacco> tobaccoClass : tobaccos) { // Configure the tobacco in the injection framework ...
// Configure the tobacco in the injection framework ... // ... and create a new wizard with it
final Injector injector = Guice.createInjector(new AbstractModule() { // Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobaccoClass -> {
final var injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() { protected void configure() {
bind(Tobacco.class).to(tobaccoClass); bind(Tobacco.class).to(tobaccoClass);
} }
}); });
final var guiceWizard = injector.getInstance(GuiceWizard.class);
// ... and create a new wizard with it
final GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class);
guiceWizard.smoke(); guiceWizard.smoke();
String lastMessage = appender.getLastMessage();
// Verify if the wizard is smoking the correct tobacco ... assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), lastMessage);
assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage()); });
}
// ... and nothing else is happening. // ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize()); assertEquals(tobaccos.size(), appender.getLogSize());
} }
} }

View File

@ -23,13 +23,13 @@
package com.iluwatar.dependency.injection; package com.iluwatar.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.dependency.injection.utils.InMemoryAppender; import com.iluwatar.dependency.injection.utils.InMemoryAppender;
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 static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Date: 12/10/15 - 8:26 PM * Date: 12/10/15 - 8:26 PM
* *
@ -55,7 +55,7 @@ public class SimpleWizardTest {
*/ */
@Test @Test
public void testSmoke() { public void testSmoke() {
final SimpleWizard simpleWizard = new SimpleWizard(); final var simpleWizard = new SimpleWizard();
simpleWizard.smoke(); simpleWizard.smoke();
assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage()); assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage());
assertEquals(1, appender.getLogSize()); assertEquals(1, appender.getLogSize());

View File

@ -23,9 +23,7 @@
package com.iluwatar.dirtyflag; package com.iluwatar.dirtyflag;
import java.util.List;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -61,18 +59,15 @@ public class App {
* Program execution point. * Program execution point.
*/ */
public void run() { public void run() {
final var executorService = Executors.newSingleThreadScheduledExecutor();
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() { executorService.scheduleAtFixedRate(new Runnable() {
final World world = new World(); final World world = new World();
@Override @Override
public void run() { public void run() {
List<String> countries = world.fetch(); var countries = world.fetch();
LOGGER.info("Our world currently has the following countries:-"); LOGGER.info("Our world currently has the following countries:-");
for (String country : countries) { countries.stream().map(country -> "\t" + country).forEach(LOGGER::info);
LOGGER.info("\t" + country);
}
} }
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds. }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
} }
@ -83,8 +78,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) {
App app = new App(); var app = new App();
app.run(); app.run();
} }

View File

@ -27,8 +27,8 @@ import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -62,24 +62,18 @@ public class DataFetcher {
* @return List of strings * @return List of strings
*/ */
public List<String> fetch() { public List<String> fetch() {
ClassLoader classLoader = getClass().getClassLoader(); var classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(filename).getFile()); var file = new File(classLoader.getResource(filename).getFile());
if (isDirty(file.lastModified())) { if (isDirty(file.lastModified())) {
LOGGER.info(filename + " is dirty! Re-fetching file content..."); LOGGER.info(filename + " is dirty! Re-fetching file content...");
try (var br = new BufferedReader(new FileReader(file))) {
List<String> data = new ArrayList<String>(); return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf));
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
data.add(line);
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return data;
} }
return new ArrayList<String>(); return List.of();
} }
} }

View File

@ -47,10 +47,8 @@ public class World {
* @return List of strings * @return List of strings
*/ */
public List<String> fetch() { public List<String> fetch() {
List<String> data = df.fetch(); var data = df.fetch();
countries = data.isEmpty() ? countries : data; countries = data.isEmpty() ? countries : data;
return countries; return countries;
} }
} }

View File

@ -23,19 +23,15 @@
package org.dirty.flag; package org.dirty.flag;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import com.iluwatar.dirtyflag.App; import com.iluwatar.dirtyflag.App;
import org.junit.jupiter.api.Test;
/** /**
* Tests that Dirty-Flag example runs without errors. * Tests that Dirty-Flag 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

@ -26,31 +26,26 @@ package org.dirty.flag;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List; import com.iluwatar.dirtyflag.DataFetcher;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import com.iluwatar.dirtyflag.DataFetcher;
/** /**
*
* Application test * Application test
*
*/ */
public class DirtyFlagTest { public class DirtyFlagTest {
@Test @Test
public void testIsDirty() { public void testIsDirty() {
DataFetcher df = new DataFetcher(); var df = new DataFetcher();
List<String> countries = df.fetch(); var countries = df.fetch();
assertFalse(countries.isEmpty()); assertFalse(countries.isEmpty());
} }
@Test @Test
public void testIsNotDirty() { public void testIsNotDirty() {
DataFetcher df = new DataFetcher(); var df = new DataFetcher();
df.fetch(); df.fetch();
List<String> countries = df.fetch(); var countries = df.fetch();
assertTrue(countries.isEmpty()); assertTrue(countries.isEmpty());
} }
} }

View File

@ -23,10 +23,8 @@
package com.iluwatar.doublebuffer; package com.iluwatar.doublebuffer;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -48,37 +46,34 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
final var scene = new Scene(); final var scene = new Scene();
List<Pair<Integer, Integer>> drawPixels = new ArrayList<>(); var drawPixels1 = List.of(
Pair<Integer, Integer> pixel1 = new MutablePair<>(1, 1); new MutablePair<>(1, 1),
Pair<Integer, Integer> pixel2 = new MutablePair<>(5, 6); new MutablePair<>(5, 6),
Pair<Integer, Integer> pixel3 = new MutablePair<>(3, 2); new MutablePair<>(3, 2)
drawPixels.add(pixel1); );
drawPixels.add(pixel2); scene.draw(drawPixels1);
drawPixels.add(pixel3);
scene.draw(drawPixels);
var buffer1 = scene.getBuffer(); var buffer1 = scene.getBuffer();
printBlackPixelCoordinate(buffer1); printBlackPixelCoordinate(buffer1);
drawPixels.clear(); var drawPixels2 = List.of(
Pair<Integer, Integer> pixel4 = new MutablePair<>(3, 7); new MutablePair<>(3, 7),
Pair<Integer, Integer> pixel5 = new MutablePair<>(6, 1); new MutablePair<>(6, 1)
drawPixels.add(pixel4); );
drawPixels.add(pixel5); scene.draw(drawPixels2);
scene.draw(drawPixels); var buffer2 = scene.getBuffer();
Buffer buffer2 = scene.getBuffer();
printBlackPixelCoordinate(buffer2); printBlackPixelCoordinate(buffer2);
} }
private static void printBlackPixelCoordinate(Buffer buffer) { private static void printBlackPixelCoordinate(Buffer buffer) {
var log = "Black Pixels: "; StringBuilder log = new StringBuilder("Black Pixels: ");
Pixel[] pixels = buffer.getPixels(); var pixels = buffer.getPixels();
for (var i = 0; i < pixels.length; ++i) { for (var i = 0; i < pixels.length; ++i) {
if (pixels[i] == Pixel.BLACK) { if (pixels[i] == Pixel.BLACK) {
var y = i / FrameBuffer.WIDTH; var y = i / FrameBuffer.WIDTH;
var x = i % FrameBuffer.WIDTH; var x = i % FrameBuffer.WIDTH;
log += " (" + x + ", " + y + ")"; log.append(" (").append(x).append(", ").append(y).append(")");
} }
} }
LOGGER.info(log); LOGGER.info(log.toString());
} }
} }

View File

@ -23,6 +23,8 @@
package com.iluwatar.doublebuffer; package com.iluwatar.doublebuffer;
import java.util.Arrays;
/** /**
* FrameBuffer implementation class. * FrameBuffer implementation class.
*/ */
@ -49,9 +51,7 @@ public class FrameBuffer implements Buffer {
@Override @Override
public void clearAll() { public void clearAll() {
for (var i = 0; i < pixels.length; ++i) { Arrays.fill(pixels, Pixel.WHITE);
pixels[i] = Pixel.WHITE;
}
} }
@Override @Override

View File

@ -57,15 +57,15 @@ public class Scene {
* *
* @param coordinateList list of pixels of which the color should be black * @param coordinateList list of pixels of which the color should be black
*/ */
public void draw(List<Pair<Integer, Integer>> coordinateList) { public void draw(List<? extends Pair<Integer, Integer>> coordinateList) {
LOGGER.info("Start drawing next frame"); LOGGER.info("Start drawing next frame");
LOGGER.info("Current buffer: " + current + " Next buffer: " + next); LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
frameBuffers[next].clearAll(); frameBuffers[next].clearAll();
for (Pair<Integer, Integer> coordinate : coordinateList) { coordinateList.forEach(coordinate -> {
var x = coordinate.getKey(); var x = coordinate.getKey();
var y = coordinate.getValue(); var y = coordinate.getValue();
frameBuffers[next].draw(x, y); frameBuffers[next].draw(x, y);
} });
LOGGER.info("Swap current and next buffer"); LOGGER.info("Swap current and next buffer");
swap(); swap();
LOGGER.info("Finish swapping"); LOGGER.info("Finish swapping");

View File

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

View File

@ -23,6 +23,7 @@
package com.iluwatar.doublebuffer; package com.iluwatar.doublebuffer;
import java.util.Arrays;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -35,10 +36,8 @@ public class FrameBufferTest {
public void testClearAll() { public void testClearAll() {
try { try {
var field = FrameBuffer.class.getDeclaredField("pixels"); var field = FrameBuffer.class.getDeclaredField("pixels");
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
for (int i = 0; i < pixels.length; ++i) { Arrays.fill(pixels, Pixel.WHITE);
pixels[i] = Pixel.WHITE;
}
pixels[0] = Pixel.BLACK; pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer(); var frameBuffer = new FrameBuffer();
field.setAccessible(true); field.setAccessible(true);
@ -54,10 +53,8 @@ public class FrameBufferTest {
public void testClear() { public void testClear() {
try { try {
var field = FrameBuffer.class.getDeclaredField("pixels"); var field = FrameBuffer.class.getDeclaredField("pixels");
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
for (int i = 0; i < pixels.length; ++i) { Arrays.fill(pixels, Pixel.WHITE);
pixels[i] = Pixel.WHITE;
}
pixels[0] = Pixel.BLACK; pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer(); var frameBuffer = new FrameBuffer();
field.setAccessible(true); field.setAccessible(true);
@ -80,10 +77,8 @@ public class FrameBufferTest {
public void testGetPixels() { public void testGetPixels() {
try { try {
var field = FrameBuffer.class.getDeclaredField("pixels"); var field = FrameBuffer.class.getDeclaredField("pixels");
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH]; var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
for (int i = 0; i < pixels.length; ++i) { Arrays.fill(pixels, Pixel.WHITE);
pixels[i] = Pixel.WHITE;
}
pixels[0] = Pixel.BLACK; pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer(); var frameBuffer = new FrameBuffer();
field.setAccessible(true); field.setAccessible(true);

View File

@ -23,12 +23,10 @@
package com.iluwatar.doublebuffer; package com.iluwatar.doublebuffer;
import java.util.ArrayList;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
/** /**
* Scene unit tests. * Scene unit tests.
*/ */
@ -41,8 +39,8 @@ public class SceneTest {
var field1 = Scene.class.getDeclaredField("current"); var field1 = Scene.class.getDeclaredField("current");
field1.setAccessible(true); field1.setAccessible(true);
field1.set(scene, 0); field1.set(scene, 0);
FrameBuffer[] frameBuffers = new FrameBuffer[2]; var frameBuffers = new FrameBuffer[2];
FrameBuffer frameBuffer = new FrameBuffer(); var frameBuffer = new FrameBuffer();
frameBuffer.draw(0, 0); frameBuffer.draw(0, 0);
frameBuffers[0] = frameBuffer; frameBuffers[0] = frameBuffer;
var field2 = Scene.class.getDeclaredField("frameBuffers"); var field2 = Scene.class.getDeclaredField("frameBuffers");

View File

@ -23,9 +23,9 @@
package com.iluwatar.doublechecked.locking; package com.iluwatar.doublechecked.locking;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -50,15 +50,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) {
final Inventory inventory = new Inventory(1000); final var inventory = new Inventory(1000);
ExecutorService executorService = Executors.newFixedThreadPool(3); var executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) { IntStream.range(0, 3).<Runnable>mapToObj(i -> () -> {
executorService.execute(() -> { while (inventory.addItem(new Item())) {
while (inventory.addItem(new Item())) { LOGGER.info("Adding another item");
LOGGER.info("Adding another item"); }
} }).forEach(executorService::execute);
});
}
executorService.shutdown(); executorService.shutdown();
try { try {

View File

@ -24,7 +24,6 @@
package com.iluwatar.doublechecked.locking; package com.iluwatar.doublechecked.locking;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
@ -60,8 +59,8 @@ public class Inventory {
try { try {
if (items.size() < inventorySize) { if (items.size() < inventorySize) {
items.add(item); items.add(item);
LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items var thread = Thread.currentThread();
.size(), inventorySize); LOGGER.info("{}: items.size()={}, inventorySize={}", thread, items.size(), inventorySize);
return true; return true;
} }
} finally { } finally {
@ -77,7 +76,7 @@ public class Inventory {
* @return All the items of the inventory, as an unmodifiable list * @return All the items of the inventory, as an unmodifiable list
*/ */
public final List<Item> getItems() { public final List<Item> getItems() {
return Collections.unmodifiableList(items); return List.copyOf(items);
} }
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.doublechecked.locking;
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,25 +23,24 @@
package com.iluwatar.doublechecked.locking; package com.iluwatar.doublechecked.locking;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
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 java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static java.time.Duration.ofMillis; import static java.time.Duration.ofMillis;
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.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTimeout;
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 java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
/** /**
* Date: 12/10/15 - 9:34 PM * Date: 12/10/15 - 9:34 PM
@ -83,34 +82,32 @@ public class InventoryTest {
public void testAddItem() throws Exception { public void testAddItem() throws Exception {
assertTimeout(ofMillis(10000), () -> { assertTimeout(ofMillis(10000), () -> {
// Create a new inventory with a limit of 1000 items and put some load on the add method // Create a new inventory with a limit of 1000 items and put some load on the add method
final Inventory inventory = new Inventory(INVENTORY_SIZE); final var inventory = new Inventory(INVENTORY_SIZE);
final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); final var executorService = Executors.newFixedThreadPool(THREAD_COUNT);
for (int i = 0; i < THREAD_COUNT; i++) { IntStream.range(0, THREAD_COUNT).<Runnable>mapToObj(i -> () -> {
executorService.execute(() -> { while (inventory.addItem(new Item())) ;
while (inventory.addItem(new Item())) {}; }).forEach(executorService::execute);
});
}
// Wait until all threads have finished // Wait until all threads have finished
executorService.shutdown(); executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS); executorService.awaitTermination(5, TimeUnit.SECONDS);
// Check the number of items in the inventory. It should not have exceeded the allowed maximum // Check the number of items in the inventory. It should not have exceeded the allowed maximum
final List<Item> items = inventory.getItems(); final var items = inventory.getItems();
assertNotNull(items); assertNotNull(items);
assertEquals(INVENTORY_SIZE, items.size()); assertEquals(INVENTORY_SIZE, items.size());
assertEquals(INVENTORY_SIZE, appender.getLogSize()); assertEquals(INVENTORY_SIZE, appender.getLogSize());
// ... and check if the inventory size is increasing continuously // ... and check if the inventory size is increasing continuously
for (int i = 0; i < items.size(); i++) { IntStream.range(0, items.size())
assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); .mapToObj(i -> appender.log.get(i).getFormattedMessage()
} .contains("items.size()=" + (i + 1)))
.forEach(Assertions::assertTrue);
}); });
} }
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private List<ILoggingEvent> log = new LinkedList<>();

View File

@ -57,16 +57,17 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// initialize game objects and print their status // initialize game objects and print their status
List<GameObject> objects = List.of( var objects = List.of(
new FlamingAsteroid(0, 0, 5, 5), new FlamingAsteroid(0, 0, 5, 5),
new SpaceStationMir(1, 1, 2, 2), new SpaceStationMir(1, 1, 2, 2),
new Meteoroid(10, 10, 15, 15), new Meteoroid(10, 10, 15, 15),
new SpaceStationIss(12, 12, 14, 14)); new SpaceStationIss(12, 12, 14, 14)
objects.stream().forEach(o -> LOGGER.info(o.toString())); );
objects.forEach(o -> LOGGER.info(o.toString()));
LOGGER.info(""); LOGGER.info("");
// collision check // collision check
objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { objects.forEach(o1 -> objects.forEach(o2 -> {
if (o1 != o2 && o1.intersectsWith(o2)) { if (o1 != o2 && o1.intersectsWith(o2)) {
o1.collision(o2); o1.collision(o2);
} }
@ -74,7 +75,7 @@ public class App {
LOGGER.info(""); LOGGER.info("");
// output eventual object statuses // output eventual object statuses
objects.stream().forEach(o -> LOGGER.info(o.toString())); objects.forEach(o -> LOGGER.info(o.toString()));
LOGGER.info(""); LOGGER.info("");
} }
} }

View File

@ -26,15 +26,12 @@ package com.iluwatar.doubledispatch;
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,13 +23,13 @@
package com.iluwatar.doubledispatch; package com.iluwatar.doubledispatch;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Objects;
/** /**
* Date: 12/10/15 - 8:37 PM * Date: 12/10/15 - 8:37 PM Test for Collision
* Test for Collision *
* @param <O> Type of GameObject * @param <O> Type of GameObject
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */
@ -51,15 +51,14 @@ public abstract class CollisionTest<O extends GameObject> {
* @param otherOnFire Indicates if the other object should be burning after the collision * @param otherOnFire Indicates if the other object should be burning after the collision
* @param thisDamaged Indicates if the test object should be damaged after the collision * @param thisDamaged Indicates if the test object should be damaged after the collision
* @param thisOnFire Indicates if the other object should be burning after the collision * @param thisOnFire Indicates if the other object should be burning after the collision
* @param description The expected description of the collision
*/ */
void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire, void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire,
final boolean thisDamaged, final boolean thisOnFire, final String description) { final boolean thisDamaged, final boolean thisOnFire) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
Objects.requireNonNull(getTestedObject()); Objects.requireNonNull(getTestedObject());
final O tested = getTestedObject(); final var tested = getTestedObject();
tested.collision(other); tested.collision(other);
@ -80,10 +79,10 @@ public abstract class CollisionTest<O extends GameObject> {
* @param expectTargetOnFire The expected state of fire on the target object * @param expectTargetOnFire The expected state of fire on the target object
*/ */
private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) { private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) {
final String targetName = target.getClass().getSimpleName(); final var targetName = target.getClass().getSimpleName();
final String otherName = other.getClass().getSimpleName(); final var otherName = other.getClass().getSimpleName();
final String errorMessage = expectTargetOnFire final var errorMessage = expectTargetOnFire
? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!"
: "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!";
@ -99,10 +98,10 @@ public abstract class CollisionTest<O extends GameObject> {
* @param expectedDamage The expected state of damage on the target object * @param expectedDamage The expected state of damage on the target object
*/ */
private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) { private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) {
final String targetName = target.getClass().getSimpleName(); final var targetName = target.getClass().getSimpleName();
final String otherName = other.getClass().getSimpleName(); final var otherName = other.getClass().getSimpleName();
final String errorMessage = expectedDamage final var errorMessage = expectedDamage
? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!"
: "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!";

View File

@ -23,12 +23,12 @@
package com.iluwatar.doubledispatch; package com.iluwatar.doubledispatch;
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.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/10/15 - 11:31 PM * Date: 12/10/15 - 11:31 PM
* *
@ -46,7 +46,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
*/ */
@Test @Test
public void testConstructor() { public void testConstructor() {
final FlamingAsteroid asteroid = new FlamingAsteroid(1, 2, 3, 4); final var asteroid = new FlamingAsteroid(1, 2, 3, 4);
assertEquals(1, asteroid.getLeft()); assertEquals(1, asteroid.getLeft());
assertEquals(2, asteroid.getTop()); assertEquals(2, asteroid.getTop());
assertEquals(3, asteroid.getRight()); assertEquals(3, asteroid.getRight());
@ -64,8 +64,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
testCollision( testCollision(
new FlamingAsteroid(1, 2, 3, 4), new FlamingAsteroid(1, 2, 3, 4),
false, true, false, true,
false, true, false, true
"FlamingAsteroid hits FlamingAsteroid."
); );
} }
@ -77,8 +76,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
testCollision( testCollision(
new Meteoroid(1, 1, 3, 4), new Meteoroid(1, 1, 3, 4),
false, false, false, false,
false, true, false, true
"FlamingAsteroid hits Meteoroid."
); );
} }
@ -90,8 +88,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
testCollision( testCollision(
new SpaceStationIss(1, 1, 3, 4), new SpaceStationIss(1, 1, 3, 4),
true, true, true, true,
false, true, false, true
"FlamingAsteroid hits SpaceStationIss. SpaceStationIss is damaged! SpaceStationIss is set on fire!"
); );
} }
@ -103,8 +100,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
testCollision( testCollision(
new SpaceStationMir(1, 1, 3, 4), new SpaceStationMir(1, 1, 3, 4),
true, true, true, true,
false, true, false, true
"FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire!"
); );
} }

View File

@ -23,11 +23,11 @@
package com.iluwatar.doubledispatch; package com.iluwatar.doubledispatch;
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.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/10/15 - 11:31 PM * Date: 12/10/15 - 11:31 PM
* *
@ -45,7 +45,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
*/ */
@Test @Test
public void testConstructor() { public void testConstructor() {
final Meteoroid meteoroid = new Meteoroid(1, 2, 3, 4); final var meteoroid = new Meteoroid(1, 2, 3, 4);
assertEquals(1, meteoroid.getLeft()); assertEquals(1, meteoroid.getLeft());
assertEquals(2, meteoroid.getTop()); assertEquals(2, meteoroid.getTop());
assertEquals(3, meteoroid.getRight()); assertEquals(3, meteoroid.getRight());
@ -63,8 +63,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
testCollision( testCollision(
new FlamingAsteroid(1, 1, 3, 4), new FlamingAsteroid(1, 1, 3, 4),
false, true, false, true,
false, false, false, false
"Meteoroid hits FlamingAsteroid."
); );
} }
@ -76,8 +75,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
testCollision( testCollision(
new Meteoroid(1, 1, 3, 4), new Meteoroid(1, 1, 3, 4),
false, false, false, false,
false, false, false, false
"Meteoroid hits Meteoroid."
); );
} }
@ -89,8 +87,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
testCollision( testCollision(
new SpaceStationIss(1, 1, 3, 4), new SpaceStationIss(1, 1, 3, 4),
true, false, true, false,
false, false, false, false
"Meteoroid hits SpaceStationIss. SpaceStationIss is damaged!"
); );
} }
@ -102,8 +99,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
testCollision( testCollision(
new SpaceStationMir(1, 1, 3, 4), new SpaceStationMir(1, 1, 3, 4),
true, false, true, false,
false, false, false, false
"Meteoroid hits SpaceStationMir. SpaceStationMir is damaged!"
); );
} }

View File

@ -23,12 +23,12 @@
package com.iluwatar.doubledispatch; package com.iluwatar.doubledispatch;
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.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/** /**
* Unit test for Rectangle * Unit test for Rectangle
*/ */
@ -39,7 +39,7 @@ public class RectangleTest {
*/ */
@Test @Test
public void testConstructor() { public void testConstructor() {
final Rectangle rectangle = new Rectangle(1, 2, 3, 4); final var rectangle = new Rectangle(1, 2, 3, 4);
assertEquals(1, rectangle.getLeft()); assertEquals(1, rectangle.getLeft());
assertEquals(2, rectangle.getTop()); assertEquals(2, rectangle.getTop());
assertEquals(3, rectangle.getRight()); assertEquals(3, rectangle.getRight());
@ -52,7 +52,7 @@ public class RectangleTest {
*/ */
@Test @Test
public void testToString() throws Exception { public void testToString() throws Exception {
final Rectangle rectangle = new Rectangle(1, 2, 3, 4); final var rectangle = new Rectangle(1, 2, 3, 4);
assertEquals("[1,2,3,4]", rectangle.toString()); assertEquals("[1,2,3,4]", rectangle.toString());
} }

View File

@ -23,11 +23,11 @@
package com.iluwatar.doubledispatch; package com.iluwatar.doubledispatch;
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.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/10/15 - 11:31 PM * Date: 12/10/15 - 11:31 PM
* *
@ -45,7 +45,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
*/ */
@Test @Test
public void testConstructor() { public void testConstructor() {
final SpaceStationIss iss = new SpaceStationIss(1, 2, 3, 4); final var iss = new SpaceStationIss(1, 2, 3, 4);
assertEquals(1, iss.getLeft()); assertEquals(1, iss.getLeft());
assertEquals(2, iss.getTop()); assertEquals(2, iss.getTop());
assertEquals(3, iss.getRight()); assertEquals(3, iss.getRight());
@ -63,8 +63,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
testCollision( testCollision(
new FlamingAsteroid(1, 1, 3, 4), new FlamingAsteroid(1, 1, 3, 4),
false, true, false, true,
false, false, false, false
"SpaceStationIss hits FlamingAsteroid."
); );
} }
@ -76,8 +75,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
testCollision( testCollision(
new Meteoroid(1, 1, 3, 4), new Meteoroid(1, 1, 3, 4),
false, false, false, false,
false, false, false, false
"SpaceStationIss hits Meteoroid."
); );
} }
@ -89,8 +87,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
testCollision( testCollision(
new SpaceStationIss(1, 1, 3, 4), new SpaceStationIss(1, 1, 3, 4),
true, false, true, false,
false, false, false, false
"SpaceStationIss hits SpaceStationIss. SpaceStationIss is damaged!"
); );
} }
@ -102,8 +99,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
testCollision( testCollision(
new SpaceStationMir(1, 1, 3, 4), new SpaceStationMir(1, 1, 3, 4),
true, false, true, false,
false, false, false, false
"SpaceStationIss hits SpaceStationMir. SpaceStationMir is damaged!"
); );
} }

View File

@ -23,11 +23,11 @@
package com.iluwatar.doubledispatch; package com.iluwatar.doubledispatch;
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.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/10/15 - 11:31 PM * Date: 12/10/15 - 11:31 PM
* *
@ -45,7 +45,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
*/ */
@Test @Test
public void testConstructor() { public void testConstructor() {
final SpaceStationMir mir = new SpaceStationMir(1, 2, 3, 4); final var mir = new SpaceStationMir(1, 2, 3, 4);
assertEquals(1, mir.getLeft()); assertEquals(1, mir.getLeft());
assertEquals(2, mir.getTop()); assertEquals(2, mir.getTop());
assertEquals(3, mir.getRight()); assertEquals(3, mir.getRight());
@ -63,8 +63,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
testCollision( testCollision(
new FlamingAsteroid(1, 1, 3, 4), new FlamingAsteroid(1, 1, 3, 4),
false, true, false, true,
false, false, false, false
"SpaceStationMir hits FlamingAsteroid."
); );
} }
@ -76,8 +75,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
testCollision( testCollision(
new Meteoroid(1, 1, 3, 4), new Meteoroid(1, 1, 3, 4),
false, false, false, false,
false, false, false, false
"SpaceStationMir hits Meteoroid."
); );
} }
@ -89,8 +87,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
testCollision( testCollision(
new SpaceStationIss(1, 1, 3, 4), new SpaceStationIss(1, 1, 3, 4),
true, false, true, false,
false, false, false, false
"SpaceStationMir hits SpaceStationIss. SpaceStationIss is damaged!"
); );
} }
@ -102,8 +99,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
testCollision( testCollision(
new SpaceStationMir(1, 1, 3, 4), new SpaceStationMir(1, 1, 3, 4),
true, false, true, false,
false, false, false, false
"SpaceStationMir hits SpaceStationMir. SpaceStationMir is damaged!"
); );
} }