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:
parent
5681684157
commit
ea57934db6
@ -63,20 +63,26 @@ The specialized converters inherit from this base class as follows.
|
||||
public class UserConverter extends Converter<UserDto, User> {
|
||||
|
||||
public UserConverter() {
|
||||
super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(),
|
||||
userDto.getEmail()),
|
||||
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(),
|
||||
user.getUserId()));
|
||||
super(UserConverter::convertToEntity, UserConverter::convertToDto);
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
```java
|
||||
Converter<UserDto, User> userConverter = new UserConverter();
|
||||
UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
|
||||
User user = userConverter.convertFromDto(dtoUser);
|
||||
var userConverter = new UserConverter();
|
||||
var dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
|
||||
var user = userConverter.convertFromDto(dtoUser);
|
||||
```
|
||||
|
||||
## Class diagram
|
||||
|
@ -49,8 +49,11 @@ public class App {
|
||||
User user = userConverter.convertFromDto(dtoUser);
|
||||
LOGGER.info("Entity converted from DTO:" + user);
|
||||
|
||||
var users = List.of(new User("Camile", "Tough", false, "124sad"),
|
||||
new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243"));
|
||||
var users = List.of(
|
||||
new User("Camile", "Tough", false, "124sad"),
|
||||
new User("Marti", "Luther", true, "42309fd"),
|
||||
new User("Kate", "Smith", true, "if0243")
|
||||
);
|
||||
LOGGER.info("Domain entities:");
|
||||
users.stream().map(User::toString).forEach(LOGGER::info);
|
||||
|
||||
|
@ -73,7 +73,7 @@ public class User {
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
User user = (User) o;
|
||||
var user = (User) o;
|
||||
return isActive == user.isActive && Objects.equals(firstName, user.firstName) && Objects
|
||||
.equals(lastName, user.lastName) && Objects.equals(userId, user.userId);
|
||||
}
|
||||
|
@ -28,13 +28,16 @@ package com.iluwatar.converter;
|
||||
*/
|
||||
public class UserConverter extends Converter<UserDto, User> {
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public UserConverter() {
|
||||
super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(),
|
||||
userDto.getEmail()),
|
||||
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(),
|
||||
user.getUserId()));
|
||||
super(UserConverter::convertToEntity, UserConverter::convertToDto);
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -74,7 +74,7 @@ public class UserDto {
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
UserDto userDto = (UserDto) o;
|
||||
var userDto = (UserDto) o;
|
||||
return isActive == userDto.isActive && Objects.equals(firstName, userDto.firstName) && Objects
|
||||
.equals(lastName, userDto.lastName) && Objects.equals(email, userDto.email);
|
||||
}
|
||||
|
@ -32,8 +32,7 @@ public class AppTest {
|
||||
|
||||
@Test
|
||||
public void testMain() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -23,12 +23,11 @@
|
||||
|
||||
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.Random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for {@link Converter}
|
||||
@ -42,8 +41,8 @@ public class ConverterTest {
|
||||
*/
|
||||
@Test
|
||||
public void testConversionsStartingFromDomain() {
|
||||
User u1 = new User("Tom", "Hanks", true, "tom@hanks.com");
|
||||
User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1));
|
||||
var u1 = new User("Tom", "Hanks", true, "tom@hanks.com");
|
||||
var u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1));
|
||||
assertEquals(u1, u2);
|
||||
}
|
||||
|
||||
@ -52,37 +51,47 @@ public class ConverterTest {
|
||||
*/
|
||||
@Test
|
||||
public void testConversionsStartingFromDto() {
|
||||
UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com");
|
||||
UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1));
|
||||
var u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com");
|
||||
var u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1));
|
||||
assertEquals(u1, u2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and
|
||||
* cleanly instantiated allowing various different conversion strategies to be implemented.
|
||||
* Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and cleanly
|
||||
* instantiated allowing various different conversion strategies to be implemented.
|
||||
*/
|
||||
@Test
|
||||
public void testCustomConverter() {
|
||||
Converter<UserDto, User> converter = new Converter<>(
|
||||
userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(),
|
||||
String.valueOf(new Random().nextInt())),
|
||||
user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(),
|
||||
user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com"));
|
||||
User u1 = new User("John", "Doe", false, "12324");
|
||||
UserDto userDto = converter.convertFromEntity(u1);
|
||||
var converter = new Converter<UserDto, User>(
|
||||
userDto -> new User(
|
||||
userDto.getFirstName(),
|
||||
userDto.getLastName(),
|
||||
userDto.isActive(),
|
||||
String.valueOf(new Random().nextInt())
|
||||
),
|
||||
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());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test whether converting a collection of Users to DTO Users and then converting them back to domain
|
||||
* users returns an equal collection.
|
||||
* Test whether converting a collection of Users to DTO Users and then converting them back to
|
||||
* domain users returns an equal collection.
|
||||
*/
|
||||
@Test
|
||||
public void testCollectionConversion() {
|
||||
List<User> users = List.of(new User("Camile", "Tough", false, "124sad"),
|
||||
new User("Marti", "Luther", true, "42309fd"),
|
||||
new User("Kate", "Smith", true, "if0243"));
|
||||
List<User> fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users));
|
||||
var users = List.of(
|
||||
new User("Camile", "Tough", false, "124sad"),
|
||||
new User("Marti", "Luther", true, "42309fd"),
|
||||
new User("Kate", "Smith", true, "if0243")
|
||||
);
|
||||
var fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users));
|
||||
assertEquals(users, fromDtos);
|
||||
}
|
||||
}
|
||||
|
@ -24,15 +24,9 @@
|
||||
package com.iluwatar.cqrs.app;
|
||||
|
||||
import com.iluwatar.cqrs.commandes.CommandServiceImpl;
|
||||
import com.iluwatar.cqrs.commandes.ICommandService;
|
||||
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.util.HibernateUtil;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -56,7 +50,7 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
ICommandService commands = new CommandServiceImpl();
|
||||
var commands = new CommandServiceImpl();
|
||||
|
||||
// Create Authors and Books using CommandService
|
||||
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.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans");
|
||||
|
||||
IQueryService queries = new QueryServiceImpl();
|
||||
var queries = new QueryServiceImpl();
|
||||
|
||||
// Query the database using QueryService
|
||||
Author nullAuthor = queries.getAuthorByUsername("username");
|
||||
Author evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
|
||||
BigInteger blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
|
||||
BigInteger authorsCount = queries.getAuthorsCount();
|
||||
Book dddBook = queries.getBook("Domain-Driven Design");
|
||||
List<Book> blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);
|
||||
var nullAuthor = queries.getAuthorByUsername("username");
|
||||
var evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
|
||||
var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
|
||||
var authorsCount = queries.getAuthorsCount();
|
||||
var dddBook = queries.getBook("Domain-Driven Design");
|
||||
var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);
|
||||
|
||||
LOGGER.info("Author username : {}", nullAuthor);
|
||||
LOGGER.info("Author evans : {}", evans);
|
||||
|
@ -26,8 +26,6 @@ package com.iluwatar.cqrs.commandes;
|
||||
import com.iluwatar.cqrs.domain.model.Author;
|
||||
import com.iluwatar.cqrs.domain.model.Book;
|
||||
import com.iluwatar.cqrs.util.HibernateUtil;
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
|
||||
/**
|
||||
@ -39,9 +37,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
|
||||
|
||||
private Author getAuthorByUsername(String username) {
|
||||
Author author = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
Query query = session.createQuery("from Author where username=:username");
|
||||
Author author;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
var query = session.createQuery("from Author where username=:username");
|
||||
query.setParameter("username", username);
|
||||
author = (Author) query.uniqueResult();
|
||||
}
|
||||
@ -53,9 +51,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
}
|
||||
|
||||
private Book getBookByTitle(String title) {
|
||||
Book book = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
Query query = session.createQuery("from Book where title=:title");
|
||||
Book book;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
var query = session.createQuery("from Book where title=:title");
|
||||
query.setParameter("title", title);
|
||||
book = (Book) query.uniqueResult();
|
||||
}
|
||||
@ -68,8 +66,8 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void authorCreated(String username, String name, String email) {
|
||||
Author author = new Author(username, name, email);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
var author = new Author(username, name, email);
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.save(author);
|
||||
session.getTransaction().commit();
|
||||
@ -78,9 +76,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void bookAddedToAuthor(String title, double price, String username) {
|
||||
Author author = getAuthorByUsername(username);
|
||||
Book book = new Book(title, price, author);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
var author = getAuthorByUsername(username);
|
||||
var book = new Book(title, price, author);
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.save(book);
|
||||
session.getTransaction().commit();
|
||||
@ -89,9 +87,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void authorNameUpdated(String username, String name) {
|
||||
Author author = getAuthorByUsername(username);
|
||||
var author = getAuthorByUsername(username);
|
||||
author.setName(name);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(author);
|
||||
session.getTransaction().commit();
|
||||
@ -100,9 +98,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void authorUsernameUpdated(String oldUsername, String newUsername) {
|
||||
Author author = getAuthorByUsername(oldUsername);
|
||||
var author = getAuthorByUsername(oldUsername);
|
||||
author.setUsername(newUsername);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(author);
|
||||
session.getTransaction().commit();
|
||||
@ -111,9 +109,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void authorEmailUpdated(String username, String email) {
|
||||
Author author = getAuthorByUsername(username);
|
||||
var author = getAuthorByUsername(username);
|
||||
author.setEmail(email);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(author);
|
||||
session.getTransaction().commit();
|
||||
@ -122,9 +120,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void bookTitleUpdated(String oldTitle, String newTitle) {
|
||||
Book book = getBookByTitle(oldTitle);
|
||||
var book = getBookByTitle(oldTitle);
|
||||
book.setTitle(newTitle);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(book);
|
||||
session.getTransaction().commit();
|
||||
@ -133,9 +131,9 @@ public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
@Override
|
||||
public void bookPriceUpdated(String title, double price) {
|
||||
Book book = getBookByTitle(title);
|
||||
var book = getBookByTitle(title);
|
||||
book.setPrice(price);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(book);
|
||||
session.getTransaction().commit();
|
||||
|
@ -80,7 +80,7 @@ public class Author {
|
||||
if (!(obj instanceof Author)) {
|
||||
return false;
|
||||
}
|
||||
Author other = (Author) obj;
|
||||
var other = (Author) obj;
|
||||
return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name
|
||||
.equals(other.getName());
|
||||
|
||||
|
@ -73,7 +73,7 @@ public class Book {
|
||||
if (!(obj instanceof Book)) {
|
||||
return false;
|
||||
}
|
||||
Book book = (Book) obj;
|
||||
var book = (Book) obj;
|
||||
return title.equals(book.getTitle()) && price == book.getPrice();
|
||||
}
|
||||
|
||||
|
@ -29,8 +29,6 @@ import com.iluwatar.cqrs.dto.Book;
|
||||
import com.iluwatar.cqrs.util.HibernateUtil;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import org.hibernate.SQLQuery;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.transform.Transformers;
|
||||
|
||||
@ -44,9 +42,9 @@ public class QueryServiceImpl implements IQueryService {
|
||||
|
||||
@Override
|
||||
public Author getAuthorByUsername(String username) {
|
||||
Author authorDTo = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery("SELECT a.username as \"username\","
|
||||
Author authorDTo;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
var sqlQuery = session.createSQLQuery("SELECT a.username as \"username\","
|
||||
+ " a.name as \"name\", a.email as \"email\""
|
||||
+ "FROM Author a where a.username=:username");
|
||||
sqlQuery.setParameter(AppConstants.USER_NAME, username);
|
||||
@ -58,9 +56,9 @@ public class QueryServiceImpl implements IQueryService {
|
||||
|
||||
@Override
|
||||
public Book getBook(String title) {
|
||||
Book bookDTo = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\","
|
||||
Book bookDTo;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
var sqlQuery = session.createSQLQuery("SELECT b.title as \"title\","
|
||||
+ " b.price as \"price\"" + " FROM Book b where b.title=:title");
|
||||
sqlQuery.setParameter("title", title);
|
||||
bookDTo =
|
||||
@ -71,9 +69,9 @@ public class QueryServiceImpl implements IQueryService {
|
||||
|
||||
@Override
|
||||
public List<Book> getAuthorBooks(String username) {
|
||||
List<Book> bookDTos = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\", b.price as \"price\""
|
||||
List<Book> bookDTos;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
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");
|
||||
sqlQuery.setParameter(AppConstants.USER_NAME, username);
|
||||
bookDTos = sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).list();
|
||||
@ -83,9 +81,9 @@ public class QueryServiceImpl implements IQueryService {
|
||||
|
||||
@Override
|
||||
public BigInteger getAuthorBooksCount(String username) {
|
||||
BigInteger bookcount = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery(
|
||||
BigInteger bookcount;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
var sqlQuery = session.createSQLQuery(
|
||||
"SELECT count(b.title)" + " FROM Book b, Author a"
|
||||
+ " where b.author_id = a.id and a.username=:username");
|
||||
sqlQuery.setParameter(AppConstants.USER_NAME, username);
|
||||
@ -96,9 +94,9 @@ public class QueryServiceImpl implements IQueryService {
|
||||
|
||||
@Override
|
||||
public BigInteger getAuthorsCount() {
|
||||
BigInteger authorcount = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery("SELECT count(id) from Author");
|
||||
BigInteger authorcount;
|
||||
try (var session = sessionFactory.openSession()) {
|
||||
var sqlQuery = session.createSQLQuery("SELECT count(id) from Author");
|
||||
authorcount = (BigInteger) sqlQuery.uniqueResult();
|
||||
}
|
||||
return authorcount;
|
||||
|
@ -25,7 +25,6 @@ package com.iluwatar.cqrs.util;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -42,8 +41,7 @@ public class HibernateUtil {
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
|
||||
// configures settings from hibernate.cfg.xml
|
||||
final StandardServiceRegistry registry =
|
||||
new StandardServiceRegistryBuilder().configure().build();
|
||||
final var registry = new StandardServiceRegistryBuilder().configure().build();
|
||||
try {
|
||||
return new MetadataSources(registry).buildMetadata().buildSessionFactory();
|
||||
} catch (Exception ex) {
|
||||
|
@ -23,33 +23,28 @@
|
||||
|
||||
package com.iluwatar.cqrs;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.iluwatar.cqrs.commandes.CommandServiceImpl;
|
||||
import com.iluwatar.cqrs.commandes.ICommandService;
|
||||
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 java.math.BigInteger;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
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
|
||||
*
|
||||
*/
|
||||
public class IntegrationTest {
|
||||
|
||||
private static IQueryService queryService;
|
||||
private static ICommandService commandService;
|
||||
|
||||
@BeforeAll
|
||||
public static void initializeAndPopulateDatabase() {
|
||||
commandService = new CommandServiceImpl();
|
||||
var commandService = new CommandServiceImpl();
|
||||
queryService = new QueryServiceImpl();
|
||||
|
||||
// create first author1
|
||||
@ -73,7 +68,7 @@ public class IntegrationTest {
|
||||
|
||||
@Test
|
||||
public void testGetAuthorByUsername() {
|
||||
Author author = queryService.getAuthorByUsername("username1");
|
||||
var author = queryService.getAuthorByUsername("username1");
|
||||
assertEquals("username1", author.getUsername());
|
||||
assertEquals("name1", author.getName());
|
||||
assertEquals("email1", author.getEmail());
|
||||
@ -81,22 +76,22 @@ public class IntegrationTest {
|
||||
|
||||
@Test
|
||||
public void testGetUpdatedAuthorByUsername() {
|
||||
Author author = queryService.getAuthorByUsername("new_username2");
|
||||
Author expectedAuthor = new Author("new_name2", "new_email2", "new_username2");
|
||||
var author = queryService.getAuthorByUsername("new_username2");
|
||||
var expectedAuthor = new Author("new_name2", "new_email2", "new_username2");
|
||||
assertEquals(expectedAuthor, author);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBook() {
|
||||
Book book = queryService.getBook("title1");
|
||||
var book = queryService.getBook("title1");
|
||||
assertEquals("title1", book.getTitle());
|
||||
assertEquals(10, book.getPrice(), 0.01);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthorBooks() {
|
||||
List<Book> books = queryService.getAuthorBooks("username1");
|
||||
var books = queryService.getAuthorBooks("username1");
|
||||
assertEquals(2, books.size());
|
||||
assertTrue(books.contains(new Book("title1", 10)));
|
||||
assertTrue(books.contains(new Book("new_title2", 30)));
|
||||
@ -104,13 +99,13 @@ public class IntegrationTest {
|
||||
|
||||
@Test
|
||||
public void testGetAuthorBooksCount() {
|
||||
BigInteger bookCount = queryService.getAuthorBooksCount("username1");
|
||||
var bookCount = queryService.getAuthorBooksCount("username1");
|
||||
assertEquals(new BigInteger("2"), bookCount);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthorsCount() {
|
||||
BigInteger authorCount = queryService.getAuthorsCount();
|
||||
var authorCount = queryService.getAuthorsCount();
|
||||
assertEquals(new BigInteger("2"), authorCount);
|
||||
}
|
||||
|
||||
|
@ -23,11 +23,8 @@
|
||||
|
||||
package com.iluwatar.dao;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import javax.sql.DataSource;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.slf4j.Logger;
|
||||
@ -57,32 +54,32 @@ public class App {
|
||||
* @throws Exception if any error occurs.
|
||||
*/
|
||||
public static void main(final String[] args) throws Exception {
|
||||
final CustomerDao inMemoryDao = new InMemoryCustomerDao();
|
||||
final var inMemoryDao = new InMemoryCustomerDao();
|
||||
performOperationsUsing(inMemoryDao);
|
||||
|
||||
final DataSource dataSource = createDataSource();
|
||||
final var dataSource = createDataSource();
|
||||
createSchema(dataSource);
|
||||
final CustomerDao dbDao = new DbCustomerDao(dataSource);
|
||||
final var dbDao = new DbCustomerDao(dataSource);
|
||||
performOperationsUsing(dbDao);
|
||||
deleteSchema(dataSource);
|
||||
}
|
||||
|
||||
private static void deleteSchema(DataSource dataSource) throws SQLException {
|
||||
try (Connection connection = dataSource.getConnection();
|
||||
Statement statement = connection.createStatement()) {
|
||||
try (var connection = dataSource.getConnection();
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL);
|
||||
}
|
||||
}
|
||||
|
||||
private static void createSchema(DataSource dataSource) throws SQLException {
|
||||
try (Connection connection = dataSource.getConnection();
|
||||
Statement statement = connection.createStatement()) {
|
||||
try (var connection = dataSource.getConnection();
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL);
|
||||
}
|
||||
}
|
||||
|
||||
private static DataSource createDataSource() {
|
||||
JdbcDataSource dataSource = new JdbcDataSource();
|
||||
var dataSource = new JdbcDataSource();
|
||||
dataSource.setURL(DB_URL);
|
||||
return dataSource;
|
||||
}
|
||||
@ -90,18 +87,18 @@ public class App {
|
||||
private static void performOperationsUsing(final CustomerDao customerDao) throws Exception {
|
||||
addCustomers(customerDao);
|
||||
log.info(ALL_CUSTOMERS);
|
||||
try (Stream<Customer> customerStream = customerDao.getAll()) {
|
||||
try (var customerStream = customerDao.getAll()) {
|
||||
customerStream.forEach((customer) -> log.info(customer.toString()));
|
||||
}
|
||||
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);
|
||||
log.info(ALL_CUSTOMERS + customerDao.getAll());
|
||||
customer.setFirstName("Daniel");
|
||||
customer.setLastName("Danielson");
|
||||
customerDao.update(customer);
|
||||
log.info(ALL_CUSTOMERS);
|
||||
try (Stream<Customer> customerStream = customerDao.getAll()) {
|
||||
try (var customerStream = customerDao.getAll()) {
|
||||
customerStream.forEach((cust) -> log.info(cust.toString()));
|
||||
}
|
||||
customerDao.delete(customer);
|
||||
@ -109,7 +106,7 @@ public class App {
|
||||
}
|
||||
|
||||
private static void addCustomers(CustomerDao customerDao) throws Exception {
|
||||
for (Customer customer : generateSampleCustomers()) {
|
||||
for (var customer : generateSampleCustomers()) {
|
||||
customerDao.add(customer);
|
||||
}
|
||||
}
|
||||
@ -120,9 +117,9 @@ public class App {
|
||||
* @return list of customers.
|
||||
*/
|
||||
public static List<Customer> generateSampleCustomers() {
|
||||
final Customer customer1 = new Customer(1, "Adam", "Adamson");
|
||||
final Customer customer2 = new Customer(2, "Bob", "Bobson");
|
||||
final Customer customer3 = new Customer(3, "Carl", "Carlson");
|
||||
final var customer1 = new Customer(1, "Adam", "Adamson");
|
||||
final var customer2 = new Customer(2, "Bob", "Bobson");
|
||||
final var customer3 = new Customer(3, "Carl", "Carlson");
|
||||
return List.of(customer1, customer2, customer3);
|
||||
}
|
||||
}
|
||||
|
@ -73,11 +73,11 @@ public class Customer {
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object that) {
|
||||
boolean isEqual = false;
|
||||
var isEqual = false;
|
||||
if (this == that) {
|
||||
isEqual = true;
|
||||
} else if (that != null && getClass() == that.getClass()) {
|
||||
final Customer customer = (Customer) that;
|
||||
final var customer = (Customer) that;
|
||||
if (getId() == customer.getId()) {
|
||||
isEqual = true;
|
||||
}
|
||||
|
@ -65,13 +65,10 @@ public class DbCustomerDao implements CustomerDao {
|
||||
*/
|
||||
@Override
|
||||
public Stream<Customer> getAll() throws Exception {
|
||||
|
||||
Connection connection;
|
||||
try {
|
||||
connection = getConnection();
|
||||
PreparedStatement statement =
|
||||
connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR
|
||||
ResultSet resultSet = statement.executeQuery(); // NOSONAR
|
||||
var connection = getConnection();
|
||||
var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS");
|
||||
var resultSet = statement.executeQuery(); // NOSONAR
|
||||
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE,
|
||||
Spliterator.ORDERED) {
|
||||
|
||||
@ -121,9 +118,8 @@ public class DbCustomerDao implements CustomerDao {
|
||||
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try (Connection connection = getConnection();
|
||||
PreparedStatement statement =
|
||||
connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) {
|
||||
try (var connection = getConnection();
|
||||
var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) {
|
||||
|
||||
statement.setInt(1, id);
|
||||
resultSet = statement.executeQuery();
|
||||
@ -150,9 +146,8 @@ public class DbCustomerDao implements CustomerDao {
|
||||
return false;
|
||||
}
|
||||
|
||||
try (Connection connection = getConnection();
|
||||
PreparedStatement statement =
|
||||
connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) {
|
||||
try (var connection = getConnection();
|
||||
var statement = connection.prepareStatement("INSERT INTO CUSTOMERS VALUES (?,?,?)")) {
|
||||
statement.setInt(1, customer.getId());
|
||||
statement.setString(2, customer.getFirstName());
|
||||
statement.setString(3, customer.getLastName());
|
||||
@ -168,8 +163,8 @@ public class DbCustomerDao implements CustomerDao {
|
||||
*/
|
||||
@Override
|
||||
public boolean update(Customer customer) throws Exception {
|
||||
try (Connection connection = getConnection();
|
||||
PreparedStatement statement =
|
||||
try (var connection = getConnection();
|
||||
var statement =
|
||||
connection
|
||||
.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) {
|
||||
statement.setString(1, customer.getFirstName());
|
||||
@ -186,9 +181,8 @@ public class DbCustomerDao implements CustomerDao {
|
||||
*/
|
||||
@Override
|
||||
public boolean delete(Customer customer) throws Exception {
|
||||
try (Connection connection = getConnection();
|
||||
PreparedStatement statement =
|
||||
connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
|
||||
try (var connection = getConnection();
|
||||
var statement = connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
|
||||
statement.setInt(1, customer.getId());
|
||||
return statement.executeUpdate() > 0;
|
||||
} catch (SQLException ex) {
|
||||
|
@ -31,7 +31,6 @@ import org.junit.jupiter.api.Test;
|
||||
public class AppTest {
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -46,36 +46,36 @@ public class CustomerTest {
|
||||
|
||||
@Test
|
||||
public void getAndSetId() {
|
||||
final int newId = 2;
|
||||
final var newId = 2;
|
||||
customer.setId(newId);
|
||||
assertEquals(newId, customer.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAndSetFirstname() {
|
||||
final String newFirstname = "Bill";
|
||||
final var newFirstname = "Bill";
|
||||
customer.setFirstName(newFirstname);
|
||||
assertEquals(newFirstname, customer.getFirstName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAndSetLastname() {
|
||||
final String newLastname = "Clinton";
|
||||
final var newLastname = "Clinton";
|
||||
customer.setLastName(newLastname);
|
||||
assertEquals(newLastname, customer.getLastName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notEqualWithDifferentId() {
|
||||
final int newId = 2;
|
||||
final Customer otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME);
|
||||
final var newId = 2;
|
||||
final var otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME);
|
||||
assertNotEquals(customer, otherCustomer);
|
||||
assertNotEquals(customer.hashCode(), otherCustomer.hashCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equalsWithSameObjectValues() {
|
||||
final Customer otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME);
|
||||
final var otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME);
|
||||
assertEquals(customer, otherCustomer);
|
||||
assertEquals(customer.hashCode(), otherCustomer.hashCode());
|
||||
}
|
||||
|
@ -23,20 +23,6 @@
|
||||
|
||||
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.assertFalse;
|
||||
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.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}.
|
||||
*/
|
||||
@ -57,12 +54,13 @@ public class DbCustomerDaoTest {
|
||||
|
||||
/**
|
||||
* Creates customers schema.
|
||||
*
|
||||
* @throws SQLException if there is any error while creating schema.
|
||||
*/
|
||||
@BeforeEach
|
||||
public void createSchema() throws SQLException {
|
||||
try (Connection connection = DriverManager.getConnection(DB_URL);
|
||||
Statement statement = connection.createStatement()) {
|
||||
try (var connection = DriverManager.getConnection(DB_URL);
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL);
|
||||
}
|
||||
}
|
||||
@ -75,14 +73,15 @@ public class DbCustomerDaoTest {
|
||||
|
||||
/**
|
||||
* Setup for connection success scenario.
|
||||
*
|
||||
* @throws Exception if any error occurs.
|
||||
*/
|
||||
@BeforeEach
|
||||
public void setUp() throws Exception {
|
||||
JdbcDataSource dataSource = new JdbcDataSource();
|
||||
var dataSource = new JdbcDataSource();
|
||||
dataSource.setURL(DB_URL);
|
||||
dao = new DbCustomerDao(dataSource);
|
||||
boolean result = dao.add(existingCustomer);
|
||||
var result = dao.add(existingCustomer);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@ -94,12 +93,12 @@ public class DbCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void addingShouldResultInSuccess() throws Exception {
|
||||
try (Stream<Customer> allCustomers = dao.getAll()) {
|
||||
try (var allCustomers = dao.getAll()) {
|
||||
assumeTrue(allCustomers.count() == 1);
|
||||
}
|
||||
|
||||
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
boolean result = dao.add(nonExistingCustomer);
|
||||
final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
var result = dao.add(nonExistingCustomer);
|
||||
assertTrue(result);
|
||||
|
||||
assertCustomerCountIs(2);
|
||||
@ -108,8 +107,8 @@ public class DbCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
|
||||
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
boolean result = dao.delete(nonExistingCustomer);
|
||||
final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
var result = dao.delete(nonExistingCustomer);
|
||||
|
||||
assertFalse(result);
|
||||
assertCustomerCountIs(1);
|
||||
@ -117,11 +116,11 @@ public class DbCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
|
||||
final int nonExistingId = getNonExistingCustomerId();
|
||||
final String newFirstname = "Douglas";
|
||||
final String newLastname = "MacArthur";
|
||||
final Customer customer = new Customer(nonExistingId, newFirstname, newLastname);
|
||||
boolean result = dao.update(customer);
|
||||
final var nonExistingId = getNonExistingCustomerId();
|
||||
final var newFirstname = "Douglas";
|
||||
final var newLastname = "MacArthur";
|
||||
final var customer = new Customer(nonExistingId, newFirstname, newLastname);
|
||||
var result = dao.update(customer);
|
||||
|
||||
assertFalse(result);
|
||||
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
|
||||
* customer.
|
||||
*
|
||||
*/
|
||||
@Nested
|
||||
public class ExistingCustomer {
|
||||
|
||||
@Test
|
||||
public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
|
||||
Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
|
||||
|
||||
boolean result = dao.add(existingCustomer);
|
||||
var existingCustomer = new Customer(1, "Freddy", "Krueger");
|
||||
var result = dao.add(existingCustomer);
|
||||
|
||||
assertFalse(result);
|
||||
assertCustomerCountIs(1);
|
||||
@ -154,7 +151,7 @@ public class DbCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
|
||||
boolean result = dao.delete(existingCustomer);
|
||||
var result = dao.delete(existingCustomer);
|
||||
|
||||
assertTrue(result);
|
||||
assertCustomerCountIs(0);
|
||||
@ -162,15 +159,16 @@ public class DbCustomerDaoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception {
|
||||
final String newFirstname = "Bernard";
|
||||
final String newLastname = "Montgomery";
|
||||
final Customer customer = new Customer(existingCustomer.getId(), newFirstname, newLastname);
|
||||
boolean result = dao.update(customer);
|
||||
public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws
|
||||
Exception {
|
||||
final var newFirstname = "Bernard";
|
||||
final var newLastname = "Montgomery";
|
||||
final var customer = new Customer(existingCustomer.getId(), newFirstname, newLastname);
|
||||
var result = dao.update(customer);
|
||||
|
||||
assertTrue(result);
|
||||
|
||||
final Customer cust = dao.getById(existingCustomer.getId()).get();
|
||||
final var cust = dao.getById(existingCustomer.getId()).get();
|
||||
assertEquals(newFirstname, cust.getFirstName());
|
||||
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
|
||||
* DB service unavailable.
|
||||
*
|
||||
* Represents a scenario where DB connectivity is not present due to network issue, or DB service
|
||||
* unavailable.
|
||||
*/
|
||||
@Nested
|
||||
public class ConnectivityIssue {
|
||||
|
||||
|
||||
private static final String EXCEPTION_CAUSE = "Connection not available";
|
||||
|
||||
/**
|
||||
* setup a connection failure scenario.
|
||||
*
|
||||
* @throws SQLException if any error occurs.
|
||||
*/
|
||||
@BeforeEach
|
||||
public void setUp() throws SQLException {
|
||||
dao = new DbCustomerDao(mockedDatasource());
|
||||
}
|
||||
|
||||
|
||||
private DataSource mockedDatasource() throws SQLException {
|
||||
DataSource mockedDataSource = mock(DataSource.class);
|
||||
Connection mockedConnection = mock(Connection.class);
|
||||
SQLException exception = new SQLException(EXCEPTION_CAUSE);
|
||||
var mockedDataSource = mock(DataSource.class);
|
||||
var mockedConnection = mock(Connection.class);
|
||||
var exception = new SQLException(EXCEPTION_CAUSE);
|
||||
doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString());
|
||||
doReturn(mockedConnection).when(mockedDataSource).getConnection();
|
||||
return mockedDataSource;
|
||||
@ -211,30 +209,30 @@ public class DbCustomerDaoTest {
|
||||
dao.add(new Customer(2, "Bernard", "Montgomery"));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
dao.delete(existingCustomer);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void updatingACustomerFailsWithFeedbackToTheClient() {
|
||||
final String newFirstname = "Bernard";
|
||||
final String newLastname = "Montgomery";
|
||||
final var newFirstname = "Bernard";
|
||||
final var newLastname = "Montgomery";
|
||||
assertThrows(Exception.class, () -> {
|
||||
dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
dao.getById(existingCustomer.getId());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
@ -246,18 +244,19 @@ public class DbCustomerDaoTest {
|
||||
|
||||
/**
|
||||
* Delete customer schema for fresh setup per test.
|
||||
*
|
||||
* @throws SQLException if any error occurs.
|
||||
*/
|
||||
@AfterEach
|
||||
public void deleteSchema() throws SQLException {
|
||||
try (Connection connection = DriverManager.getConnection(DB_URL);
|
||||
Statement statement = connection.createStatement()) {
|
||||
try (var connection = DriverManager.getConnection(DB_URL);
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertCustomerCountIs(int count) throws Exception {
|
||||
try (Stream<Customer> allCustomers = dao.getAll()) {
|
||||
try (var allCustomers = dao.getAll()) {
|
||||
assertEquals(count, allCustomers.count());
|
||||
}
|
||||
}
|
||||
@ -265,7 +264,7 @@ public class DbCustomerDaoTest {
|
||||
|
||||
/**
|
||||
* An arbitrary number which does not correspond to an active Customer id.
|
||||
*
|
||||
*
|
||||
* @return an int of a customer id which doesn't exist
|
||||
*/
|
||||
private int getNonExistingCustomerId() {
|
||||
|
@ -23,18 +23,15 @@
|
||||
|
||||
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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
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}.
|
||||
*/
|
||||
@ -50,20 +47,20 @@ public class InMemoryCustomerDaoTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the scenario when the DAO operations are being performed on a non existent
|
||||
* customer.
|
||||
* Represents the scenario when the DAO operations are being performed on a non existent
|
||||
* customer.
|
||||
*/
|
||||
@Nested
|
||||
public class NonExistingCustomer {
|
||||
|
||||
@Test
|
||||
public void addingShouldResultInSuccess() throws Exception {
|
||||
try (Stream<Customer> allCustomers = dao.getAll()) {
|
||||
try (var allCustomers = dao.getAll()) {
|
||||
assumeTrue(allCustomers.count() == 1);
|
||||
}
|
||||
|
||||
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
boolean result = dao.add(nonExistingCustomer);
|
||||
final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
var result = dao.add(nonExistingCustomer);
|
||||
assertTrue(result);
|
||||
|
||||
assertCustomerCountIs(2);
|
||||
@ -72,8 +69,8 @@ public class InMemoryCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
|
||||
final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
boolean result = dao.delete(nonExistingCustomer);
|
||||
final var nonExistingCustomer = new Customer(2, "Robert", "Englund");
|
||||
var result = dao.delete(nonExistingCustomer);
|
||||
|
||||
assertFalse(result);
|
||||
assertCustomerCountIs(1);
|
||||
@ -81,11 +78,11 @@ public class InMemoryCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
|
||||
final int nonExistingId = getNonExistingCustomerId();
|
||||
final String newFirstname = "Douglas";
|
||||
final String newLastname = "MacArthur";
|
||||
final Customer customer = new Customer(nonExistingId, newFirstname, newLastname);
|
||||
boolean result = dao.update(customer);
|
||||
final var nonExistingId = getNonExistingCustomerId();
|
||||
final var newFirstname = "Douglas";
|
||||
final var newLastname = "MacArthur";
|
||||
final var customer = new Customer(nonExistingId, newFirstname, newLastname);
|
||||
var result = dao.update(customer);
|
||||
|
||||
assertFalse(result);
|
||||
assertFalse(dao.getById(nonExistingId).isPresent());
|
||||
@ -106,7 +103,7 @@ public class InMemoryCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
|
||||
boolean result = dao.add(CUSTOMER);
|
||||
var result = dao.add(CUSTOMER);
|
||||
|
||||
assertFalse(result);
|
||||
assertCustomerCountIs(1);
|
||||
@ -115,7 +112,7 @@ public class InMemoryCustomerDaoTest {
|
||||
|
||||
@Test
|
||||
public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
|
||||
boolean result = dao.delete(CUSTOMER);
|
||||
var result = dao.delete(CUSTOMER);
|
||||
|
||||
assertTrue(result);
|
||||
assertCustomerCountIs(0);
|
||||
@ -123,23 +120,24 @@ public class InMemoryCustomerDaoTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception {
|
||||
final String newFirstname = "Bernard";
|
||||
final String newLastname = "Montgomery";
|
||||
final Customer customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname);
|
||||
boolean result = dao.update(customer);
|
||||
public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws
|
||||
Exception {
|
||||
final var newFirstname = "Bernard";
|
||||
final var newLastname = "Montgomery";
|
||||
final var customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname);
|
||||
var result = dao.update(customer);
|
||||
|
||||
assertTrue(result);
|
||||
|
||||
final Customer cust = dao.getById(CUSTOMER.getId()).get();
|
||||
final var cust = dao.getById(CUSTOMER.getId()).get();
|
||||
assertEquals(newFirstname, cust.getFirstName());
|
||||
assertEquals(newLastname, cust.getLastName());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void retriveShouldReturnTheCustomer() {
|
||||
Optional<Customer> optionalCustomer = dao.getById(CUSTOMER.getId());
|
||||
|
||||
var optionalCustomer = dao.getById(CUSTOMER.getId());
|
||||
|
||||
assertTrue(optionalCustomer.isPresent());
|
||||
assertEquals(CUSTOMER, optionalCustomer.get());
|
||||
}
|
||||
@ -147,15 +145,15 @@ public class InMemoryCustomerDaoTest {
|
||||
|
||||
/**
|
||||
* An arbitrary number which does not correspond to an active Customer id.
|
||||
*
|
||||
*
|
||||
* @return an int of a customer id which doesn't exist
|
||||
*/
|
||||
private int getNonExistingCustomerId() {
|
||||
return 999;
|
||||
}
|
||||
|
||||
|
||||
private void assertCustomerCountIs(int count) throws Exception {
|
||||
try (Stream<Customer> allCustomers = dao.getAll()) {
|
||||
try (var allCustomers = dao.getAll()) {
|
||||
assertEquals(count, allCustomers.count());
|
||||
}
|
||||
}
|
||||
|
@ -59,11 +59,11 @@ import java.time.LocalDateTime;
|
||||
class App {
|
||||
|
||||
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(2));
|
||||
final MessageCollectorMember foo = new MessageCollectorMember("Foo");
|
||||
final MessageCollectorMember bar = new MessageCollectorMember("Bar");
|
||||
final var foo = new MessageCollectorMember("Foo");
|
||||
final var bar = new MessageCollectorMember("Bar");
|
||||
bus.subscribe(foo);
|
||||
bus.publish(StartingData.of(LocalDateTime.now()));
|
||||
bus.publish(MessageData.of("Only Foo should see this"));
|
||||
|
@ -27,7 +27,6 @@ import com.iluwatar.databus.DataType;
|
||||
import com.iluwatar.databus.Member;
|
||||
import com.iluwatar.databus.data.MessageData;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@ -61,6 +60,6 @@ public class MessageCollectorMember implements Member {
|
||||
}
|
||||
|
||||
public List<String> getMessages() {
|
||||
return Collections.unmodifiableList(messages);
|
||||
return List.copyOf(messages);
|
||||
}
|
||||
}
|
||||
|
@ -23,14 +23,14 @@
|
||||
|
||||
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.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.mockito.BDDMockito.then;
|
||||
import static org.mockito.Mockito.never;
|
||||
|
||||
/**
|
||||
* Tests for {@link DataBus}.
|
||||
*
|
||||
@ -52,7 +52,7 @@ public class DataBusTest {
|
||||
@Test
|
||||
public void publishedEventIsReceivedBySubscribedMember() {
|
||||
//given
|
||||
final DataBus dataBus = DataBus.getInstance();
|
||||
final var dataBus = DataBus.getInstance();
|
||||
dataBus.subscribe(member);
|
||||
//when
|
||||
dataBus.publish(event);
|
||||
@ -63,7 +63,7 @@ public class DataBusTest {
|
||||
@Test
|
||||
public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() {
|
||||
//given
|
||||
final DataBus dataBus = DataBus.getInstance();
|
||||
final var dataBus = DataBus.getInstance();
|
||||
dataBus.subscribe(member);
|
||||
dataBus.unsubscribe(member);
|
||||
//when
|
||||
|
@ -23,15 +23,14 @@
|
||||
|
||||
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.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}.
|
||||
*
|
||||
@ -42,9 +41,9 @@ public class MessageCollectorMemberTest {
|
||||
@Test
|
||||
public void collectMessageFromMessageData() {
|
||||
//given
|
||||
final String message = "message";
|
||||
final MessageData messageData = new MessageData(message);
|
||||
final MessageCollectorMember collector = new MessageCollectorMember("collector");
|
||||
final var message = "message";
|
||||
final var messageData = new MessageData(message);
|
||||
final var collector = new MessageCollectorMember("collector");
|
||||
//when
|
||||
collector.accept(messageData);
|
||||
//then
|
||||
@ -54,8 +53,8 @@ public class MessageCollectorMemberTest {
|
||||
@Test
|
||||
public void collectIgnoresMessageFromOtherDataTypes() {
|
||||
//given
|
||||
final StartingData startingData = new StartingData(LocalDateTime.now());
|
||||
final MessageCollectorMember collector = new MessageCollectorMember("collector");
|
||||
final var startingData = new StartingData(LocalDateTime.now());
|
||||
final var collector = new MessageCollectorMember("collector");
|
||||
//when
|
||||
collector.accept(startingData);
|
||||
//then
|
||||
|
@ -23,17 +23,16 @@
|
||||
|
||||
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.data.MessageData;
|
||||
import com.iluwatar.databus.data.StartingData;
|
||||
import com.iluwatar.databus.data.StoppingData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for {@link StatusMember}.
|
||||
@ -45,9 +44,9 @@ public class StatusMemberTest {
|
||||
@Test
|
||||
public void statusRecordsTheStartTime() {
|
||||
//given
|
||||
final LocalDateTime startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9);
|
||||
final StartingData startingData = new StartingData(startTime);
|
||||
final StatusMember statusMember = new StatusMember(1);
|
||||
final var startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9);
|
||||
final var startingData = new StartingData(startTime);
|
||||
final var statusMember = new StatusMember(1);
|
||||
//when
|
||||
statusMember.accept(startingData);
|
||||
//then
|
||||
@ -57,10 +56,10 @@ public class StatusMemberTest {
|
||||
@Test
|
||||
public void statusRecordsTheStopTime() {
|
||||
//given
|
||||
final LocalDateTime stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12);
|
||||
final StoppingData stoppingData = new StoppingData(stop);
|
||||
final var stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12);
|
||||
final var stoppingData = new StoppingData(stop);
|
||||
stoppingData.setDataBus(DataBus.getInstance());
|
||||
final StatusMember statusMember = new StatusMember(1);
|
||||
final var statusMember = new StatusMember(1);
|
||||
//when
|
||||
statusMember.accept(stoppingData);
|
||||
//then
|
||||
@ -70,8 +69,8 @@ public class StatusMemberTest {
|
||||
@Test
|
||||
public void statusIgnoresMessageData() {
|
||||
//given
|
||||
final MessageData messageData = new MessageData("message");
|
||||
final StatusMember statusMember = new StatusMember(1);
|
||||
final var messageData = new MessageData("message");
|
||||
final var statusMember = new StatusMember(1);
|
||||
//when
|
||||
statusMember.accept(messageData);
|
||||
//then
|
||||
|
@ -46,7 +46,7 @@ public class Application {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
LOGGER.info("Start Game Application using Data-Locality pattern");
|
||||
GameEntity gameEntity = new GameEntity(NUM_ENTITIES);
|
||||
var gameEntity = new GameEntity(NUM_ENTITIES);
|
||||
gameEntity.start();
|
||||
gameEntity.update();
|
||||
}
|
||||
|
@ -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.Component;
|
||||
import java.util.stream.IntStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -50,9 +51,7 @@ public class AiComponentManager {
|
||||
*/
|
||||
public void start() {
|
||||
LOGGER.info("Start AI Game Component");
|
||||
for (int i = 0; i < numEntities; i++) {
|
||||
AI_COMPONENTS[i] = new AiComponent();
|
||||
}
|
||||
IntStream.range(0, numEntities).forEach(i -> AI_COMPONENTS[i] = new AiComponent());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -60,10 +59,8 @@ public class AiComponentManager {
|
||||
*/
|
||||
public void update() {
|
||||
LOGGER.info("Update AI Game Component");
|
||||
for (int i = 0; i < numEntities; i++) {
|
||||
if (AI_COMPONENTS.length > i && AI_COMPONENTS[i] != null) {
|
||||
AI_COMPONENTS[i].update();
|
||||
}
|
||||
}
|
||||
IntStream.range(0, numEntities)
|
||||
.filter(i -> AI_COMPONENTS.length > i && AI_COMPONENTS[i] != null)
|
||||
.forEach(i -> AI_COMPONENTS[i].update());
|
||||
}
|
||||
}
|
||||
|
@ -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.PhysicsComponent;
|
||||
import java.util.stream.IntStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -50,9 +51,7 @@ public class PhysicsComponentManager {
|
||||
*/
|
||||
public void start() {
|
||||
LOGGER.info("Start Physics Game Component ");
|
||||
for (int i = 0; i < numEntities; i++) {
|
||||
PHYSICS_COMPONENTS[i] = new PhysicsComponent();
|
||||
}
|
||||
IntStream.range(0, numEntities).forEach(i -> PHYSICS_COMPONENTS[i] = new PhysicsComponent());
|
||||
}
|
||||
|
||||
|
||||
@ -62,10 +61,8 @@ public class PhysicsComponentManager {
|
||||
public void update() {
|
||||
LOGGER.info("Update Physics Game Component ");
|
||||
// Process physics.
|
||||
for (int i = 0; i < numEntities; i++) {
|
||||
if (PHYSICS_COMPONENTS.length > i && PHYSICS_COMPONENTS[i] != null) {
|
||||
PHYSICS_COMPONENTS[i].update();
|
||||
}
|
||||
}
|
||||
IntStream.range(0, numEntities)
|
||||
.filter(i -> PHYSICS_COMPONENTS.length > i && PHYSICS_COMPONENTS[i] != null)
|
||||
.forEach(i -> PHYSICS_COMPONENTS[i].update());
|
||||
}
|
||||
}
|
||||
|
@ -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.RenderComponent;
|
||||
import java.util.stream.IntStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -50,9 +51,7 @@ public class RenderComponentManager {
|
||||
*/
|
||||
public void start() {
|
||||
LOGGER.info("Start Render Game Component ");
|
||||
for (int i = 0; i < numEntities; i++) {
|
||||
RENDER_COMPONENTS[i] = new RenderComponent();
|
||||
}
|
||||
IntStream.range(0, numEntities).forEach(i -> RENDER_COMPONENTS[i] = new RenderComponent());
|
||||
}
|
||||
|
||||
|
||||
@ -62,10 +61,8 @@ public class RenderComponentManager {
|
||||
public void render() {
|
||||
LOGGER.info("Update Render Game Component ");
|
||||
// Process Render.
|
||||
for (int i = 0; i < numEntities; i++) {
|
||||
if (RENDER_COMPONENTS.length > i && RENDER_COMPONENTS[i] != null) {
|
||||
RENDER_COMPONENTS[i].render();
|
||||
}
|
||||
}
|
||||
IntStream.range(0, numEntities)
|
||||
.filter(i -> RENDER_COMPONENTS.length > i && RENDER_COMPONENTS[i] != null)
|
||||
.forEach(i -> RENDER_COMPONENTS[i].render());
|
||||
}
|
||||
}
|
||||
|
@ -23,7 +23,6 @@
|
||||
|
||||
package com.iluwatar.datamapper;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -51,10 +50,10 @@ public final class App {
|
||||
public static void main(final String... args) {
|
||||
|
||||
/* Create new data mapper for type 'first' */
|
||||
final StudentDataMapper mapper = new StudentDataMapperImpl();
|
||||
final var mapper = new StudentDataMapperImpl();
|
||||
|
||||
/* Create new student */
|
||||
Student student = new Student(1, "Adam", 'A');
|
||||
var student = new Student(1, "Adam", 'A');
|
||||
|
||||
/* Add student in respectibe store */
|
||||
mapper.insert(student);
|
||||
@ -62,7 +61,7 @@ public final class App {
|
||||
log.debug(STUDENT_STRING + student + ", is inserted");
|
||||
|
||||
/* 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");
|
||||
|
||||
|
@ -85,7 +85,7 @@ public final class Student implements Serializable {
|
||||
isEqual = true;
|
||||
} else if (inputObject != null && getClass() == inputObject.getClass()) {
|
||||
|
||||
final Student inputStudent = (Student) inputObject;
|
||||
final var inputStudent = (Student) inputObject;
|
||||
|
||||
/* If student id matched */
|
||||
if (this.getStudentId() == inputStudent.getStudentId()) {
|
||||
|
@ -37,71 +37,36 @@ public final class StudentDataMapperImpl implements StudentDataMapper {
|
||||
|
||||
@Override
|
||||
public Optional<Student> find(int studentId) {
|
||||
|
||||
/* 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();
|
||||
return this.getStudents().stream().filter(x -> x.getStudentId() == studentId).findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Student studentToBeUpdated) throws DataMapperException {
|
||||
|
||||
|
||||
/* Check with existing students */
|
||||
if (this.getStudents().contains(studentToBeUpdated)) {
|
||||
|
||||
/* Get the index of student in list */
|
||||
final int index = this.getStudents().indexOf(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");
|
||||
}
|
||||
String name = studentToBeUpdated.getName();
|
||||
Integer index = Optional.of(studentToBeUpdated)
|
||||
.map(Student::getStudentId)
|
||||
.flatMap(this::find)
|
||||
.map(students::indexOf)
|
||||
.orElseThrow(() -> new DataMapperException("Student [" + name + "] is not found"));
|
||||
students.set(index, studentToBeUpdated);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(Student studentToBeInserted) throws DataMapperException {
|
||||
|
||||
/* Check with existing students */
|
||||
if (!this.getStudents().contains(studentToBeInserted)) {
|
||||
|
||||
/* 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");
|
||||
Optional<Student> student = find(studentToBeInserted.getStudentId());
|
||||
if (student.isPresent()) {
|
||||
String name = studentToBeInserted.getName();
|
||||
throw new DataMapperException("Student already [" + name + "] exists");
|
||||
}
|
||||
|
||||
students.add(studentToBeInserted);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Student studentToBeDeleted) throws DataMapperException {
|
||||
|
||||
/* Check with existing students */
|
||||
if (this.getStudents().contains(studentToBeDeleted)) {
|
||||
|
||||
/* 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");
|
||||
if (!students.remove(studentToBeDeleted)) {
|
||||
String name = studentToBeDeleted.getName();
|
||||
throw new DataMapperException("Student [" + name + "] is not found");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -32,7 +32,6 @@ public final class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
final String[] args = {};
|
||||
App.main(args);
|
||||
App.main();
|
||||
}
|
||||
}
|
||||
|
@ -23,11 +23,11 @@
|
||||
|
||||
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.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 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
|
||||
@ -46,11 +46,11 @@ public class DataMapperTest {
|
||||
public void testFirstDataMapper() {
|
||||
|
||||
/* Create new data mapper of first type */
|
||||
final StudentDataMapper mapper = new StudentDataMapperImpl();
|
||||
final var mapper = new StudentDataMapperImpl();
|
||||
|
||||
/* Create new student */
|
||||
int studentId = 1;
|
||||
Student student = new Student(studentId, "Adam", 'A');
|
||||
var studentId = 1;
|
||||
var student = new Student(studentId, "Adam", 'A');
|
||||
|
||||
/* Add student in respectibe db */
|
||||
mapper.insert(student);
|
||||
@ -59,7 +59,7 @@ public class DataMapperTest {
|
||||
assertEquals(studentId, mapper.find(student.getStudentId()).get().getStudentId());
|
||||
|
||||
/* Update existing student object */
|
||||
String updatedName = "AdamUpdated";
|
||||
var updatedName = "AdamUpdated";
|
||||
student = new Student(student.getStudentId(), updatedName, 'A');
|
||||
|
||||
/* Update student in respectibe db */
|
||||
|
@ -23,12 +23,10 @@
|
||||
|
||||
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.assertFalse;
|
||||
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}.
|
||||
@ -36,8 +34,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
public final class StudentTest {
|
||||
|
||||
/**
|
||||
* This API tests the equality behaviour of Student object
|
||||
* Object Equality should work as per logic defined in equals method
|
||||
* This API tests the equality behaviour of Student object Object Equality should work as per
|
||||
* logic defined in equals method
|
||||
*
|
||||
* @throws Exception if any execution error during test
|
||||
*/
|
||||
@ -45,9 +43,9 @@ public final class StudentTest {
|
||||
public void testEquality() throws Exception {
|
||||
|
||||
/* Create some students */
|
||||
final Student firstStudent = new Student(1, "Adam", 'A');
|
||||
final Student secondStudent = new Student(2, "Donald", 'B');
|
||||
final Student secondSameStudent = new Student(2, "Donald", 'B');
|
||||
final var firstStudent = new Student(1, "Adam", 'A');
|
||||
final var secondStudent = new Student(2, "Donald", 'B');
|
||||
final var secondSameStudent = new Student(2, "Donald", 'B');
|
||||
|
||||
/* Check equals functionality: should return 'true' */
|
||||
assertEquals(firstStudent, firstStudent);
|
||||
|
@ -48,16 +48,14 @@ public class CustomerClientApp {
|
||||
* @param args program argument.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
List<CustomerDto> customers = new ArrayList<>();
|
||||
CustomerDto customerOne = new CustomerDto("1", "Kelly", "Brown");
|
||||
CustomerDto customerTwo = new CustomerDto("2", "Alfonso", "Bass");
|
||||
customers.add(customerOne);
|
||||
customers.add(customerTwo);
|
||||
var customerOne = new CustomerDto("1", "Kelly", "Brown");
|
||||
var customerTwo = new CustomerDto("2", "Alfonso", "Bass");
|
||||
var customers = new ArrayList<>(List.of(customerOne, customerTwo));
|
||||
|
||||
CustomerResource customerResource = new CustomerResource(customers);
|
||||
var customerResource = new CustomerResource(customers);
|
||||
|
||||
LOGGER.info("All customers:-");
|
||||
List<CustomerDto> allCustomers = customerResource.getAllCustomers();
|
||||
var allCustomers = customerResource.getAllCustomers();
|
||||
printCustomerDetails(allCustomers);
|
||||
|
||||
LOGGER.info("----------------------------------------------------------");
|
||||
@ -70,7 +68,7 @@ public class CustomerClientApp {
|
||||
LOGGER.info("----------------------------------------------------------");
|
||||
|
||||
LOGGER.info("Adding customer three}");
|
||||
CustomerDto customerThree = new CustomerDto("3", "Lynda", "Blair");
|
||||
var customerThree = new CustomerDto("3", "Lynda", "Blair");
|
||||
customerResource.save(customerThree);
|
||||
allCustomers = customerResource.getAllCustomers();
|
||||
printCustomerDetails(allCustomers);
|
||||
|
@ -23,13 +23,12 @@
|
||||
|
||||
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.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* tests {@link CustomerResource}.
|
||||
@ -37,13 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
public class CustomerResourceTest {
|
||||
@Test
|
||||
public void shouldGetAllCustomers() {
|
||||
CustomerDto customer = new CustomerDto("1", "Melody", "Yates");
|
||||
List<CustomerDto> customers = new ArrayList<>();
|
||||
customers.add(customer);
|
||||
|
||||
CustomerResource customerResource = new CustomerResource(customers);
|
||||
|
||||
List<CustomerDto> allCustomers = customerResource.getAllCustomers();
|
||||
var customers = List.of(new CustomerDto("1", "Melody", "Yates"));
|
||||
var customerResource = new CustomerResource(customers);
|
||||
var allCustomers = customerResource.getAllCustomers();
|
||||
|
||||
assertEquals(1, allCustomers.size());
|
||||
assertEquals("1", allCustomers.get(0).getId());
|
||||
@ -53,12 +48,12 @@ public class CustomerResourceTest {
|
||||
|
||||
@Test
|
||||
public void shouldSaveCustomer() {
|
||||
CustomerDto customer = new CustomerDto("1", "Rita", "Reynolds");
|
||||
CustomerResource customerResource = new CustomerResource(new ArrayList<>());
|
||||
var customer = new CustomerDto("1", "Rita", "Reynolds");
|
||||
var customerResource = new CustomerResource(new ArrayList<>());
|
||||
|
||||
customerResource.save(customer);
|
||||
|
||||
List<CustomerDto> allCustomers = customerResource.getAllCustomers();
|
||||
var allCustomers = customerResource.getAllCustomers();
|
||||
assertEquals("1", allCustomers.get(0).getId());
|
||||
assertEquals("Rita", allCustomers.get(0).getFirstName());
|
||||
assertEquals("Reynolds", allCustomers.get(0).getLastName());
|
||||
@ -66,15 +61,13 @@ public class CustomerResourceTest {
|
||||
|
||||
@Test
|
||||
public void shouldDeleteCustomer() {
|
||||
CustomerDto customer = new CustomerDto("1", "Terry", "Nguyen");
|
||||
List<CustomerDto> customers = new ArrayList<>();
|
||||
customers.add(customer);
|
||||
|
||||
CustomerResource customerResource = new CustomerResource(customers);
|
||||
var customer = new CustomerDto("1", "Terry", "Nguyen");
|
||||
var customers = new ArrayList<>(List.of(customer));
|
||||
var customerResource = new CustomerResource(customers);
|
||||
|
||||
customerResource.delete(customer.getId());
|
||||
|
||||
List<CustomerDto> allCustomers = customerResource.getAllCustomers();
|
||||
var allCustomers = customerResource.getAllCustomers();
|
||||
assertTrue(allCustomers.isEmpty());
|
||||
}
|
||||
|
||||
|
@ -98,12 +98,12 @@ Here's the troll in action
|
||||
|
||||
```java
|
||||
// simple troll
|
||||
Troll troll = new SimpleTroll();
|
||||
var troll = new SimpleTroll();
|
||||
troll.attack(); // The troll tries to grab you!
|
||||
troll.fleeBattle(); // The troll shrieks in horror and runs away!
|
||||
|
||||
// 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.fleeBattle(); // The troll shrieks in horror and runs away!
|
||||
```
|
||||
|
@ -49,14 +49,14 @@ public class App {
|
||||
|
||||
// simple troll
|
||||
LOGGER.info("A simple looking troll approaches.");
|
||||
Troll troll = new SimpleTroll();
|
||||
var troll = new SimpleTroll();
|
||||
troll.attack();
|
||||
troll.fleeBattle();
|
||||
LOGGER.info("Simple troll power {}.\n", troll.getAttackPower());
|
||||
|
||||
// change the behavior of the simple troll by adding a decorator
|
||||
LOGGER.info("A troll with huge club surprises you.");
|
||||
Troll clubbedTroll = new ClubbedTroll(troll);
|
||||
var clubbedTroll = new ClubbedTroll(troll);
|
||||
clubbedTroll.attack();
|
||||
clubbedTroll.fleeBattle();
|
||||
LOGGER.info("Clubbed troll power {}.\n", clubbedTroll.getAttackPower());
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.decorator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,14 +23,14 @@
|
||||
|
||||
package com.iluwatar.decorator;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.internal.verification.VerificationModeFactory.times;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests for {@link ClubbedTroll}
|
||||
*/
|
||||
@ -39,10 +39,10 @@ public class ClubbedTrollTest {
|
||||
@Test
|
||||
public void testClubbedTroll() {
|
||||
// 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 ...
|
||||
final Troll clubbed = new ClubbedTroll(simpleTroll);
|
||||
final var clubbed = new ClubbedTroll(simpleTroll);
|
||||
assertEquals(20, clubbed.getAttackPower());
|
||||
verify(simpleTroll, times(1)).getAttackPower();
|
||||
|
||||
|
@ -23,19 +23,18 @@
|
||||
|
||||
package com.iluwatar.decorator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Tests for {@link SimpleTroll}
|
||||
*/
|
||||
@ -55,7 +54,7 @@ public class SimpleTrollTest {
|
||||
|
||||
@Test
|
||||
public void testTrollActions() {
|
||||
final SimpleTroll troll = new SimpleTroll();
|
||||
final var troll = new SimpleTroll();
|
||||
assertEquals(10, troll.getAttackPower());
|
||||
|
||||
troll.attack();
|
||||
|
@ -51,9 +51,9 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
PrinterController hpPrinterController = new PrinterController(new HpPrinter());
|
||||
PrinterController canonPrinterController = new PrinterController(new CanonPrinter());
|
||||
PrinterController epsonPrinterController = new PrinterController(new EpsonPrinter());
|
||||
var hpPrinterController = new PrinterController(new HpPrinter());
|
||||
var canonPrinterController = new PrinterController(new CanonPrinter());
|
||||
var epsonPrinterController = new PrinterController(new EpsonPrinter());
|
||||
|
||||
hpPrinterController.print(MESSAGE_TO_PRINT);
|
||||
canonPrinterController.print(MESSAGE_TO_PRINT);
|
||||
|
@ -32,8 +32,7 @@ public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -23,22 +23,21 @@
|
||||
|
||||
package com.iluwatar.delegation.simple;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
import com.iluwatar.delegation.simple.printers.CanonPrinter;
|
||||
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
|
||||
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.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Test for Delegation Pattern
|
||||
*/
|
||||
@ -60,7 +59,7 @@ public class DelegateTest {
|
||||
|
||||
@Test
|
||||
public void testCanonPrinter() throws Exception {
|
||||
PrinterController printerController = new PrinterController(new CanonPrinter());
|
||||
var printerController = new PrinterController(new CanonPrinter());
|
||||
printerController.print(MESSAGE);
|
||||
|
||||
assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage());
|
||||
@ -68,7 +67,7 @@ public class DelegateTest {
|
||||
|
||||
@Test
|
||||
public void testHpPrinter() throws Exception {
|
||||
PrinterController printerController = new PrinterController(new HpPrinter());
|
||||
var printerController = new PrinterController(new HpPrinter());
|
||||
printerController.print(MESSAGE);
|
||||
|
||||
assertEquals("HP Printer : Test Message Printed", appender.getLastMessage());
|
||||
@ -76,7 +75,7 @@ public class DelegateTest {
|
||||
|
||||
@Test
|
||||
public void testEpsonPrinter() throws Exception {
|
||||
PrinterController printerController = new PrinterController(new EpsonPrinter());
|
||||
var printerController = new PrinterController(new EpsonPrinter());
|
||||
printerController.print(MESSAGE);
|
||||
|
||||
assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage());
|
||||
|
@ -24,7 +24,6 @@
|
||||
package com.iluwatar.dependency.injection;
|
||||
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
|
||||
/**
|
||||
* Dependency Injection pattern deals with how objects handle their dependencies. The pattern
|
||||
@ -55,18 +54,18 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
SimpleWizard simpleWizard = new SimpleWizard();
|
||||
var simpleWizard = new SimpleWizard();
|
||||
simpleWizard.smoke();
|
||||
|
||||
AdvancedWizard advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
|
||||
var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
|
||||
advancedWizard.smoke();
|
||||
|
||||
AdvancedSorceress advancedSorceress = new AdvancedSorceress();
|
||||
var advancedSorceress = new AdvancedSorceress();
|
||||
advancedSorceress.setTobacco(new SecondBreakfastTobacco());
|
||||
advancedSorceress.smoke();
|
||||
|
||||
Injector injector = Guice.createInjector(new TobaccoModule());
|
||||
GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class);
|
||||
var injector = Guice.createInjector(new TobaccoModule());
|
||||
var guiceWizard = injector.getInstance(GuiceWizard.class);
|
||||
guiceWizard.smoke();
|
||||
}
|
||||
}
|
||||
|
@ -23,13 +23,14 @@
|
||||
|
||||
package com.iluwatar.dependency.injection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
||||
/**
|
||||
* 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
|
||||
* through the setter's parameter
|
||||
* Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to
|
||||
* her through the setter's parameter
|
||||
*/
|
||||
@Test
|
||||
public void testSmokeEveryThing() throws Exception {
|
||||
|
||||
final Tobacco[] tobaccos = {
|
||||
new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()
|
||||
};
|
||||
List<Tobacco> tobaccos = List.of(
|
||||
new OldTobyTobacco(),
|
||||
new RivendellTobacco(),
|
||||
new SecondBreakfastTobacco()
|
||||
);
|
||||
|
||||
for (final Tobacco tobacco : tobaccos) {
|
||||
final AdvancedSorceress advancedSorceress = new AdvancedSorceress();
|
||||
// Verify if the sorceress is smoking the correct tobacco ...
|
||||
tobaccos.forEach(tobacco -> {
|
||||
final var advancedSorceress = new AdvancedSorceress();
|
||||
advancedSorceress.setTobacco(tobacco);
|
||||
advancedSorceress.smoke();
|
||||
// Verify if the sorceress is smoking the correct tobacco ...
|
||||
assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage());
|
||||
|
||||
}
|
||||
String lastMessage = appender.getLastMessage();
|
||||
assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), lastMessage);
|
||||
});
|
||||
|
||||
// ... and nothing else is happening.
|
||||
assertEquals(tobaccos.length, appender.getLogSize());
|
||||
assertEquals(tobaccos.size(), appender.getLogSize());
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -23,13 +23,14 @@
|
||||
|
||||
package com.iluwatar.dependency.injection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 8:40 PM
|
||||
@ -57,21 +58,22 @@ public class AdvancedWizardTest {
|
||||
@Test
|
||||
public void testSmokeEveryThing() throws Exception {
|
||||
|
||||
final Tobacco[] tobaccos = {
|
||||
new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()
|
||||
};
|
||||
List<Tobacco> tobaccos = List.of(
|
||||
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);
|
||||
advancedWizard.smoke();
|
||||
|
||||
// Verify if the wizard is smoking the correct tobacco ...
|
||||
assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage());
|
||||
|
||||
}
|
||||
String lastMessage = appender.getLastMessage();
|
||||
assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
|
||||
});
|
||||
|
||||
// ... and nothing else is happening.
|
||||
assertEquals(tobaccos.length, appender.getLogSize());
|
||||
assertEquals(tobaccos.size(), appender.getLogSize());
|
||||
|
||||
}
|
||||
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.dependency.injection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,16 +23,16 @@
|
||||
|
||||
package com.iluwatar.dependency.injection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 8:57 PM
|
||||
*
|
||||
@ -59,20 +59,22 @@ public class GuiceWizardTest {
|
||||
@Test
|
||||
public void testSmokeEveryThingThroughConstructor() throws Exception {
|
||||
|
||||
final Tobacco[] tobaccos = {
|
||||
new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco()
|
||||
};
|
||||
List<Tobacco> tobaccos = List.of(
|
||||
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);
|
||||
guiceWizard.smoke();
|
||||
|
||||
// Verify if the wizard is smoking the correct tobacco ...
|
||||
assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage());
|
||||
}
|
||||
String lastMessage = appender.getLastMessage();
|
||||
assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
|
||||
});
|
||||
|
||||
// ... and nothing else is happening.
|
||||
assertEquals(tobaccos.length, appender.getLogSize());
|
||||
assertEquals(tobaccos.size(), appender.getLogSize());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -82,30 +84,30 @@ public class GuiceWizardTest {
|
||||
@Test
|
||||
public void testSmokeEveryThingThroughInjectionFramework() throws Exception {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
final Class<? extends Tobacco>[] tobaccos = new Class[]{
|
||||
OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class
|
||||
};
|
||||
List<Class<? extends Tobacco>> tobaccos = List.of(
|
||||
OldTobyTobacco.class,
|
||||
RivendellTobacco.class,
|
||||
SecondBreakfastTobacco.class
|
||||
);
|
||||
|
||||
for (final Class<? extends Tobacco> tobaccoClass : tobaccos) {
|
||||
// Configure the tobacco in the injection framework ...
|
||||
final Injector injector = Guice.createInjector(new AbstractModule() {
|
||||
// Configure the tobacco in the injection framework ...
|
||||
// ... and create a new wizard with it
|
||||
// Verify if the wizard is smoking the correct tobacco ...
|
||||
tobaccos.forEach(tobaccoClass -> {
|
||||
final var injector = Guice.createInjector(new AbstractModule() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Tobacco.class).to(tobaccoClass);
|
||||
}
|
||||
});
|
||||
|
||||
// ... and create a new wizard with it
|
||||
final GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class);
|
||||
final var guiceWizard = injector.getInstance(GuiceWizard.class);
|
||||
guiceWizard.smoke();
|
||||
|
||||
// Verify if the wizard is smoking the correct tobacco ...
|
||||
assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage());
|
||||
}
|
||||
String lastMessage = appender.getLastMessage();
|
||||
assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), lastMessage);
|
||||
});
|
||||
|
||||
// ... and nothing else is happening.
|
||||
assertEquals(tobaccos.length, appender.getLogSize());
|
||||
assertEquals(tobaccos.size(), appender.getLogSize());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -23,13 +23,13 @@
|
||||
|
||||
package com.iluwatar.dependency.injection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 8:26 PM
|
||||
*
|
||||
@ -55,7 +55,7 @@ public class SimpleWizardTest {
|
||||
*/
|
||||
@Test
|
||||
public void testSmoke() {
|
||||
final SimpleWizard simpleWizard = new SimpleWizard();
|
||||
final var simpleWizard = new SimpleWizard();
|
||||
simpleWizard.smoke();
|
||||
assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage());
|
||||
assertEquals(1, appender.getLogSize());
|
||||
|
@ -23,9 +23,7 @@
|
||||
|
||||
package com.iluwatar.dirtyflag;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -61,18 +59,15 @@ public class App {
|
||||
* Program execution point.
|
||||
*/
|
||||
public void run() {
|
||||
|
||||
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
|
||||
final var executorService = Executors.newSingleThreadScheduledExecutor();
|
||||
executorService.scheduleAtFixedRate(new Runnable() {
|
||||
final World world = new World();
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
List<String> countries = world.fetch();
|
||||
var countries = world.fetch();
|
||||
LOGGER.info("Our world currently has the following countries:-");
|
||||
for (String country : countries) {
|
||||
LOGGER.info("\t" + country);
|
||||
}
|
||||
countries.stream().map(country -> "\t" + country).forEach(LOGGER::info);
|
||||
}
|
||||
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
|
||||
}
|
||||
@ -83,8 +78,7 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
App app = new App();
|
||||
|
||||
var app = new App();
|
||||
app.run();
|
||||
}
|
||||
|
||||
|
@ -27,8 +27,8 @@ import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -62,24 +62,18 @@ public class DataFetcher {
|
||||
* @return List of strings
|
||||
*/
|
||||
public List<String> fetch() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource(filename).getFile());
|
||||
var classLoader = getClass().getClassLoader();
|
||||
var file = new File(classLoader.getResource(filename).getFile());
|
||||
|
||||
if (isDirty(file.lastModified())) {
|
||||
LOGGER.info(filename + " is dirty! Re-fetching file content...");
|
||||
|
||||
List<String> data = new ArrayList<String>();
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
data.add(line);
|
||||
}
|
||||
try (var br = new BufferedReader(new FileReader(file))) {
|
||||
return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
return new ArrayList<String>();
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
@ -47,10 +47,8 @@ public class World {
|
||||
* @return List of strings
|
||||
*/
|
||||
public List<String> fetch() {
|
||||
List<String> data = df.fetch();
|
||||
|
||||
var data = df.fetch();
|
||||
countries = data.isEmpty() ? countries : data;
|
||||
|
||||
return countries;
|
||||
}
|
||||
}
|
||||
|
@ -23,19 +23,15 @@
|
||||
|
||||
package org.dirty.flag;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.dirtyflag.App;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests that Dirty-Flag example runs without errors.
|
||||
*/
|
||||
public class AppTest {
|
||||
@Test
|
||||
public void test() throws IOException {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
public void test() {
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -26,31 +26,26 @@ package org.dirty.flag;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.iluwatar.dirtyflag.DataFetcher;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.iluwatar.dirtyflag.DataFetcher;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class DirtyFlagTest {
|
||||
|
||||
@Test
|
||||
public void testIsDirty() {
|
||||
DataFetcher df = new DataFetcher();
|
||||
List<String> countries = df.fetch();
|
||||
var df = new DataFetcher();
|
||||
var countries = df.fetch();
|
||||
assertFalse(countries.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsNotDirty() {
|
||||
DataFetcher df = new DataFetcher();
|
||||
var df = new DataFetcher();
|
||||
df.fetch();
|
||||
List<String> countries = df.fetch();
|
||||
var countries = df.fetch();
|
||||
assertTrue(countries.isEmpty());
|
||||
}
|
||||
}
|
||||
|
@ -23,10 +23,8 @@
|
||||
|
||||
package com.iluwatar.doublebuffer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.tuple.MutablePair;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -48,37 +46,34 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
final var scene = new Scene();
|
||||
List<Pair<Integer, Integer>> drawPixels = new ArrayList<>();
|
||||
Pair<Integer, Integer> pixel1 = new MutablePair<>(1, 1);
|
||||
Pair<Integer, Integer> pixel2 = new MutablePair<>(5, 6);
|
||||
Pair<Integer, Integer> pixel3 = new MutablePair<>(3, 2);
|
||||
drawPixels.add(pixel1);
|
||||
drawPixels.add(pixel2);
|
||||
drawPixels.add(pixel3);
|
||||
scene.draw(drawPixels);
|
||||
var drawPixels1 = List.of(
|
||||
new MutablePair<>(1, 1),
|
||||
new MutablePair<>(5, 6),
|
||||
new MutablePair<>(3, 2)
|
||||
);
|
||||
scene.draw(drawPixels1);
|
||||
var buffer1 = scene.getBuffer();
|
||||
printBlackPixelCoordinate(buffer1);
|
||||
|
||||
drawPixels.clear();
|
||||
Pair<Integer, Integer> pixel4 = new MutablePair<>(3, 7);
|
||||
Pair<Integer, Integer> pixel5 = new MutablePair<>(6, 1);
|
||||
drawPixels.add(pixel4);
|
||||
drawPixels.add(pixel5);
|
||||
scene.draw(drawPixels);
|
||||
Buffer buffer2 = scene.getBuffer();
|
||||
var drawPixels2 = List.of(
|
||||
new MutablePair<>(3, 7),
|
||||
new MutablePair<>(6, 1)
|
||||
);
|
||||
scene.draw(drawPixels2);
|
||||
var buffer2 = scene.getBuffer();
|
||||
printBlackPixelCoordinate(buffer2);
|
||||
}
|
||||
|
||||
private static void printBlackPixelCoordinate(Buffer buffer) {
|
||||
var log = "Black Pixels: ";
|
||||
Pixel[] pixels = buffer.getPixels();
|
||||
StringBuilder log = new StringBuilder("Black Pixels: ");
|
||||
var pixels = buffer.getPixels();
|
||||
for (var i = 0; i < pixels.length; ++i) {
|
||||
if (pixels[i] == Pixel.BLACK) {
|
||||
var y = 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());
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,8 @@
|
||||
|
||||
package com.iluwatar.doublebuffer;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* FrameBuffer implementation class.
|
||||
*/
|
||||
@ -49,9 +51,7 @@ public class FrameBuffer implements Buffer {
|
||||
|
||||
@Override
|
||||
public void clearAll() {
|
||||
for (var i = 0; i < pixels.length; ++i) {
|
||||
pixels[i] = Pixel.WHITE;
|
||||
}
|
||||
Arrays.fill(pixels, Pixel.WHITE);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -57,15 +57,15 @@ public class Scene {
|
||||
*
|
||||
* @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("Current buffer: " + current + " Next buffer: " + next);
|
||||
frameBuffers[next].clearAll();
|
||||
for (Pair<Integer, Integer> coordinate : coordinateList) {
|
||||
coordinateList.forEach(coordinate -> {
|
||||
var x = coordinate.getKey();
|
||||
var y = coordinate.getValue();
|
||||
frameBuffers[next].draw(x, y);
|
||||
}
|
||||
});
|
||||
LOGGER.info("Swap current and next buffer");
|
||||
swap();
|
||||
LOGGER.info("Finish swapping");
|
||||
|
@ -32,8 +32,7 @@ public class AppTest {
|
||||
|
||||
@Test
|
||||
public void testMain() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -23,6 +23,7 @@
|
||||
|
||||
package com.iluwatar.doublebuffer;
|
||||
|
||||
import java.util.Arrays;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
@ -35,10 +36,8 @@ public class FrameBufferTest {
|
||||
public void testClearAll() {
|
||||
try {
|
||||
var field = FrameBuffer.class.getDeclaredField("pixels");
|
||||
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
|
||||
for (int i = 0; i < pixels.length; ++i) {
|
||||
pixels[i] = Pixel.WHITE;
|
||||
}
|
||||
var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
|
||||
Arrays.fill(pixels, Pixel.WHITE);
|
||||
pixels[0] = Pixel.BLACK;
|
||||
var frameBuffer = new FrameBuffer();
|
||||
field.setAccessible(true);
|
||||
@ -54,10 +53,8 @@ public class FrameBufferTest {
|
||||
public void testClear() {
|
||||
try {
|
||||
var field = FrameBuffer.class.getDeclaredField("pixels");
|
||||
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
|
||||
for (int i = 0; i < pixels.length; ++i) {
|
||||
pixels[i] = Pixel.WHITE;
|
||||
}
|
||||
var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
|
||||
Arrays.fill(pixels, Pixel.WHITE);
|
||||
pixels[0] = Pixel.BLACK;
|
||||
var frameBuffer = new FrameBuffer();
|
||||
field.setAccessible(true);
|
||||
@ -80,10 +77,8 @@ public class FrameBufferTest {
|
||||
public void testGetPixels() {
|
||||
try {
|
||||
var field = FrameBuffer.class.getDeclaredField("pixels");
|
||||
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
|
||||
for (int i = 0; i < pixels.length; ++i) {
|
||||
pixels[i] = Pixel.WHITE;
|
||||
}
|
||||
var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
|
||||
Arrays.fill(pixels, Pixel.WHITE);
|
||||
pixels[0] = Pixel.BLACK;
|
||||
var frameBuffer = new FrameBuffer();
|
||||
field.setAccessible(true);
|
||||
|
@ -23,12 +23,10 @@
|
||||
|
||||
package com.iluwatar.doublebuffer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Scene unit tests.
|
||||
*/
|
||||
@ -41,8 +39,8 @@ public class SceneTest {
|
||||
var field1 = Scene.class.getDeclaredField("current");
|
||||
field1.setAccessible(true);
|
||||
field1.set(scene, 0);
|
||||
FrameBuffer[] frameBuffers = new FrameBuffer[2];
|
||||
FrameBuffer frameBuffer = new FrameBuffer();
|
||||
var frameBuffers = new FrameBuffer[2];
|
||||
var frameBuffer = new FrameBuffer();
|
||||
frameBuffer.draw(0, 0);
|
||||
frameBuffers[0] = frameBuffer;
|
||||
var field2 = Scene.class.getDeclaredField("frameBuffers");
|
||||
|
@ -23,9 +23,9 @@
|
||||
|
||||
package com.iluwatar.doublechecked.locking;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -50,15 +50,13 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
final Inventory inventory = new Inventory(1000);
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(3);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
executorService.execute(() -> {
|
||||
while (inventory.addItem(new Item())) {
|
||||
LOGGER.info("Adding another item");
|
||||
}
|
||||
});
|
||||
}
|
||||
final var inventory = new Inventory(1000);
|
||||
var executorService = Executors.newFixedThreadPool(3);
|
||||
IntStream.range(0, 3).<Runnable>mapToObj(i -> () -> {
|
||||
while (inventory.addItem(new Item())) {
|
||||
LOGGER.info("Adding another item");
|
||||
}
|
||||
}).forEach(executorService::execute);
|
||||
|
||||
executorService.shutdown();
|
||||
try {
|
||||
|
@ -24,7 +24,6 @@
|
||||
package com.iluwatar.doublechecked.locking;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
@ -60,8 +59,8 @@ public class Inventory {
|
||||
try {
|
||||
if (items.size() < inventorySize) {
|
||||
items.add(item);
|
||||
LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items
|
||||
.size(), inventorySize);
|
||||
var thread = Thread.currentThread();
|
||||
LOGGER.info("{}: items.size()={}, inventorySize={}", thread, items.size(), inventorySize);
|
||||
return true;
|
||||
}
|
||||
} finally {
|
||||
@ -77,7 +76,7 @@ public class Inventory {
|
||||
* @return All the items of the inventory, as an unmodifiable list
|
||||
*/
|
||||
public final List<Item> getItems() {
|
||||
return Collections.unmodifiableList(items);
|
||||
return List.copyOf(items);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.doublechecked.locking;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,25 +23,24 @@
|
||||
|
||||
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 org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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
|
||||
@ -83,34 +82,32 @@ public class InventoryTest {
|
||||
public void testAddItem() throws Exception {
|
||||
assertTimeout(ofMillis(10000), () -> {
|
||||
// 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 ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
|
||||
for (int i = 0; i < THREAD_COUNT; i++) {
|
||||
executorService.execute(() -> {
|
||||
while (inventory.addItem(new Item())) {};
|
||||
});
|
||||
}
|
||||
final var inventory = new Inventory(INVENTORY_SIZE);
|
||||
final var executorService = Executors.newFixedThreadPool(THREAD_COUNT);
|
||||
IntStream.range(0, THREAD_COUNT).<Runnable>mapToObj(i -> () -> {
|
||||
while (inventory.addItem(new Item())) ;
|
||||
}).forEach(executorService::execute);
|
||||
|
||||
// Wait until all threads have finished
|
||||
executorService.shutdown();
|
||||
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||
|
||||
// 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);
|
||||
assertEquals(INVENTORY_SIZE, items.size());
|
||||
|
||||
assertEquals(INVENTORY_SIZE, appender.getLogSize());
|
||||
|
||||
// ... and check if the inventory size is increasing continuously
|
||||
for (int i = 0; i < items.size(); i++) {
|
||||
assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1)));
|
||||
}
|
||||
IntStream.range(0, items.size())
|
||||
.mapToObj(i -> appender.log.get(i).getFormattedMessage()
|
||||
.contains("items.size()=" + (i + 1)))
|
||||
.forEach(Assertions::assertTrue);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
|
||||
private List<ILoggingEvent> log = new LinkedList<>();
|
||||
|
||||
|
@ -57,16 +57,17 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
// initialize game objects and print their status
|
||||
List<GameObject> objects = List.of(
|
||||
var objects = List.of(
|
||||
new FlamingAsteroid(0, 0, 5, 5),
|
||||
new SpaceStationMir(1, 1, 2, 2),
|
||||
new Meteoroid(10, 10, 15, 15),
|
||||
new SpaceStationIss(12, 12, 14, 14));
|
||||
objects.stream().forEach(o -> LOGGER.info(o.toString()));
|
||||
new SpaceStationIss(12, 12, 14, 14)
|
||||
);
|
||||
objects.forEach(o -> LOGGER.info(o.toString()));
|
||||
LOGGER.info("");
|
||||
|
||||
// collision check
|
||||
objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> {
|
||||
objects.forEach(o1 -> objects.forEach(o2 -> {
|
||||
if (o1 != o2 && o1.intersectsWith(o2)) {
|
||||
o1.collision(o2);
|
||||
}
|
||||
@ -74,7 +75,7 @@ public class App {
|
||||
LOGGER.info("");
|
||||
|
||||
// output eventual object statuses
|
||||
objects.stream().forEach(o -> LOGGER.info(o.toString()));
|
||||
objects.forEach(o -> LOGGER.info(o.toString()));
|
||||
LOGGER.info("");
|
||||
}
|
||||
}
|
||||
|
@ -26,15 +26,12 @@ package com.iluwatar.doubledispatch;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* Application test
|
||||
*
|
||||
*/
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String[] args = {};
|
||||
App.main(args);
|
||||
App.main(new String[]{});
|
||||
}
|
||||
}
|
||||
|
@ -23,13 +23,13 @@
|
||||
|
||||
package com.iluwatar.doubledispatch;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 8:37 PM
|
||||
* Test for Collision
|
||||
* Date: 12/10/15 - 8:37 PM Test for Collision
|
||||
*
|
||||
* @param <O> Type of GameObject
|
||||
* @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 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 description The expected description of the collision
|
||||
*/
|
||||
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(getTestedObject());
|
||||
|
||||
final O tested = getTestedObject();
|
||||
final var tested = getTestedObject();
|
||||
|
||||
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
|
||||
*/
|
||||
private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) {
|
||||
final String targetName = target.getClass().getSimpleName();
|
||||
final String otherName = other.getClass().getSimpleName();
|
||||
final var targetName = target.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 + "] 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
|
||||
*/
|
||||
private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) {
|
||||
final String targetName = target.getClass().getSimpleName();
|
||||
final String otherName = other.getClass().getSimpleName();
|
||||
final var targetName = target.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 + "] not to be damaged after colliding with [" + otherName + "] but it was!";
|
||||
|
||||
|
@ -23,12 +23,12 @@
|
||||
|
||||
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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 11:31 PM
|
||||
*
|
||||
@ -46,7 +46,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
|
||||
*/
|
||||
@Test
|
||||
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(2, asteroid.getTop());
|
||||
assertEquals(3, asteroid.getRight());
|
||||
@ -64,8 +64,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
|
||||
testCollision(
|
||||
new FlamingAsteroid(1, 2, 3, 4),
|
||||
false, true,
|
||||
false, true,
|
||||
"FlamingAsteroid hits FlamingAsteroid."
|
||||
false, true
|
||||
);
|
||||
}
|
||||
|
||||
@ -77,8 +76,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
|
||||
testCollision(
|
||||
new Meteoroid(1, 1, 3, 4),
|
||||
false, false,
|
||||
false, true,
|
||||
"FlamingAsteroid hits Meteoroid."
|
||||
false, true
|
||||
);
|
||||
}
|
||||
|
||||
@ -90,8 +88,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
|
||||
testCollision(
|
||||
new SpaceStationIss(1, 1, 3, 4),
|
||||
true, true,
|
||||
false, true,
|
||||
"FlamingAsteroid hits SpaceStationIss. SpaceStationIss is damaged! SpaceStationIss is set on fire!"
|
||||
false, true
|
||||
);
|
||||
}
|
||||
|
||||
@ -103,8 +100,7 @@ public class FlamingAsteroidTest extends CollisionTest<FlamingAsteroid> {
|
||||
testCollision(
|
||||
new SpaceStationMir(1, 1, 3, 4),
|
||||
true, true,
|
||||
false, true,
|
||||
"FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire!"
|
||||
false, true
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -23,11 +23,11 @@
|
||||
|
||||
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.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 11:31 PM
|
||||
*
|
||||
@ -45,7 +45,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
|
||||
*/
|
||||
@Test
|
||||
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(2, meteoroid.getTop());
|
||||
assertEquals(3, meteoroid.getRight());
|
||||
@ -63,8 +63,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
|
||||
testCollision(
|
||||
new FlamingAsteroid(1, 1, 3, 4),
|
||||
false, true,
|
||||
false, false,
|
||||
"Meteoroid hits FlamingAsteroid."
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -76,8 +75,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
|
||||
testCollision(
|
||||
new Meteoroid(1, 1, 3, 4),
|
||||
false, false,
|
||||
false, false,
|
||||
"Meteoroid hits Meteoroid."
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -89,8 +87,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
|
||||
testCollision(
|
||||
new SpaceStationIss(1, 1, 3, 4),
|
||||
true, false,
|
||||
false, false,
|
||||
"Meteoroid hits SpaceStationIss. SpaceStationIss is damaged!"
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -102,8 +99,7 @@ public class MeteoroidTest extends CollisionTest<Meteoroid> {
|
||||
testCollision(
|
||||
new SpaceStationMir(1, 1, 3, 4),
|
||||
true, false,
|
||||
false, false,
|
||||
"Meteoroid hits SpaceStationMir. SpaceStationMir is damaged!"
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -23,12 +23,12 @@
|
||||
|
||||
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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Unit test for Rectangle
|
||||
*/
|
||||
@ -39,7 +39,7 @@ public class RectangleTest {
|
||||
*/
|
||||
@Test
|
||||
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(2, rectangle.getTop());
|
||||
assertEquals(3, rectangle.getRight());
|
||||
@ -52,7 +52,7 @@ public class RectangleTest {
|
||||
*/
|
||||
@Test
|
||||
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());
|
||||
}
|
||||
|
||||
|
@ -23,11 +23,11 @@
|
||||
|
||||
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.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 11:31 PM
|
||||
*
|
||||
@ -45,7 +45,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
|
||||
*/
|
||||
@Test
|
||||
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(2, iss.getTop());
|
||||
assertEquals(3, iss.getRight());
|
||||
@ -63,8 +63,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
|
||||
testCollision(
|
||||
new FlamingAsteroid(1, 1, 3, 4),
|
||||
false, true,
|
||||
false, false,
|
||||
"SpaceStationIss hits FlamingAsteroid."
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -76,8 +75,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
|
||||
testCollision(
|
||||
new Meteoroid(1, 1, 3, 4),
|
||||
false, false,
|
||||
false, false,
|
||||
"SpaceStationIss hits Meteoroid."
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -89,8 +87,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
|
||||
testCollision(
|
||||
new SpaceStationIss(1, 1, 3, 4),
|
||||
true, false,
|
||||
false, false,
|
||||
"SpaceStationIss hits SpaceStationIss. SpaceStationIss is damaged!"
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -102,8 +99,7 @@ public class SpaceStationIssTest extends CollisionTest<SpaceStationIss> {
|
||||
testCollision(
|
||||
new SpaceStationMir(1, 1, 3, 4),
|
||||
true, false,
|
||||
false, false,
|
||||
"SpaceStationIss hits SpaceStationMir. SpaceStationMir is damaged!"
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -23,11 +23,11 @@
|
||||
|
||||
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.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Date: 12/10/15 - 11:31 PM
|
||||
*
|
||||
@ -45,7 +45,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
|
||||
*/
|
||||
@Test
|
||||
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(2, mir.getTop());
|
||||
assertEquals(3, mir.getRight());
|
||||
@ -63,8 +63,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
|
||||
testCollision(
|
||||
new FlamingAsteroid(1, 1, 3, 4),
|
||||
false, true,
|
||||
false, false,
|
||||
"SpaceStationMir hits FlamingAsteroid."
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -76,8 +75,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
|
||||
testCollision(
|
||||
new Meteoroid(1, 1, 3, 4),
|
||||
false, false,
|
||||
false, false,
|
||||
"SpaceStationMir hits Meteoroid."
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -89,8 +87,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
|
||||
testCollision(
|
||||
new SpaceStationIss(1, 1, 3, 4),
|
||||
true, false,
|
||||
false, false,
|
||||
"SpaceStationMir hits SpaceStationIss. SpaceStationIss is damaged!"
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
@ -102,8 +99,7 @@ public class SpaceStationMirTest extends CollisionTest<SpaceStationMir> {
|
||||
testCollision(
|
||||
new SpaceStationMir(1, 1, 3, 4),
|
||||
true, false,
|
||||
false, false,
|
||||
"SpaceStationMir hits SpaceStationMir. SpaceStationMir is damaged!"
|
||||
false, false
|
||||
);
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user