Java 11 migrate remaining q-r (#1121)

* Moves queue-load-leveling to Java 11

* Moves reactor to Java 11

* Moves reader-writer-lock to Java 11

* Moves repository to Java 11

* Moves resource-acquisition-is-initialization to Java 11

* Moves retry to Java 11

* Moves role-object to Java 11
This commit is contained in:
Anurag Agarwal 2020-01-04 22:13:12 +05:30 committed by Ilkka Seppälä
parent cd2a2e7711
commit 20ea465b7f
52 changed files with 424 additions and 554 deletions

View File

@ -78,17 +78,17 @@ public class App {
try {
// Create a MessageQueue object.
MessageQueue msgQueue = new MessageQueue();
var msgQueue = new MessageQueue();
LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads.");
// Create three TaskGenerator threads. Each of them will submit different number of jobs.
final Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5);
final Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1);
final Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2);
final var taskRunnable1 = new TaskGenerator(msgQueue, 5);
final var taskRunnable2 = new TaskGenerator(msgQueue, 1);
final var taskRunnable3 = new TaskGenerator(msgQueue, 2);
// Create e service which should process the submitted jobs.
final Runnable srvRunnable = new ServiceExecutor(msgQueue);
final var srvRunnable = new ServiceExecutor(msgQueue);
// Create a ThreadPool of 2 threads and
// submit all Runnable task for execution to executor..

View File

@ -40,7 +40,7 @@ public class MessageQueue {
// Default constructor when called creates Blocking Queue object.
public MessageQueue() {
this.blkQueue = new ArrayBlockingQueue<Message>(1024);
this.blkQueue = new ArrayBlockingQueue<>(1024);
}
/**
@ -62,13 +62,11 @@ public class MessageQueue {
* them. Retrieves and removes the head of this queue, or returns null if this queue is empty.
*/
public Message retrieveMsg() {
Message retrievedMsg = null;
try {
retrievedMsg = blkQueue.poll();
return blkQueue.poll();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return retrievedMsg;
return null;
}
}

View File

@ -46,7 +46,7 @@ public class ServiceExecutor implements Runnable {
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Message msg = msgQueue.retrieveMsg();
var msg = msgQueue.retrieveMsg();
if (null != msg) {
LOGGER.info(msg.toString() + " is served.");

View File

@ -63,12 +63,11 @@ public class TaskGenerator implements Task, Runnable {
* submission TaskGenerator thread will sleep for 1 second.
*/
public void run() {
int count = this.msgCount;
var count = this.msgCount;
try {
while (count > 0) {
String statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName();
var statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName();
this.submit(new Message(statusMsg));
LOGGER.info(statusMsg);

View File

@ -25,15 +25,12 @@ package com.iluwatar.queue.load.leveling;
import org.junit.jupiter.api.Test;
import java.io.IOException;
/**
* Application Test
*/
public class AppTest {
@Test
public void test() throws IOException {
String[] args = {};
App.main(args);
public void test() {
App.main(new String[]{});
}
}

View File

@ -23,21 +23,19 @@
package com.iluwatar.queue.load.leveling;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
*
* Test case for submitting and retrieving messages from Blocking Queue.
*
*/
public class MessageQueueTest {
@Test
public void messageQueueTest() {
MessageQueue msgQueue = new MessageQueue();
var msgQueue = new MessageQueue();
// submit message
msgQueue.submitMsg(new Message("MessageQueue Test"));

View File

@ -23,14 +23,12 @@
package com.iluwatar.queue.load.leveling;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
*
* Test case for creating and checking the Message.
*
*/
public class MessageTest {
@ -38,8 +36,8 @@ public class MessageTest {
public void messageTest() {
// Parameterized constructor test.
String testMsg = "Message Test";
Message msg = new Message(testMsg);
var testMsg = "Message Test";
var msg = new Message(testMsg);
assertEquals(testMsg, msg.getMsg());
}
}

View File

@ -26,25 +26,23 @@ package com.iluwatar.queue.load.leveling;
import org.junit.jupiter.api.Test;
/**
*
* Test case for submitting Message to Blocking Queue by TaskGenerator
* and retrieve the message by ServiceExecutor.
*
* Test case for submitting Message to Blocking Queue by TaskGenerator and retrieve the message by
* ServiceExecutor.
*/
public class TaskGenSrvExeTest {
@Test
public void taskGeneratorTest() {
MessageQueue msgQueue = new MessageQueue();
var msgQueue = new MessageQueue();
// Create a task generator thread with 1 job to submit.
Runnable taskRunnable = new TaskGenerator(msgQueue, 1);
Thread taskGenThr = new Thread(taskRunnable);
var taskRunnable = new TaskGenerator(msgQueue, 1);
var taskGenThr = new Thread(taskRunnable);
taskGenThr.start();
// Create a service executor thread.
Runnable srvRunnable = new ServiceExecutor(msgQueue);
Thread srvExeThr = new Thread(srvRunnable);
var srvRunnable = new ServiceExecutor(msgQueue);
var srvExeThr = new Thread(srvRunnable);
srvExeThr.start();
}

View File

@ -124,15 +124,17 @@ public class App {
* This represents application specific business logic that dispatcher will call on appropriate
* events. These events are read events in our example.
*/
LoggingHandler loggingHandler = new LoggingHandler();
var loggingHandler = new LoggingHandler();
/*
* Our application binds to multiple channels and uses same logging handler to handle incoming
* log requests.
*/
reactor.registerChannel(tcpChannel(6666, loggingHandler))
reactor
.registerChannel(tcpChannel(6666, loggingHandler))
.registerChannel(tcpChannel(6667, loggingHandler))
.registerChannel(udpChannel(6668, loggingHandler)).start();
.registerChannel(udpChannel(6668, loggingHandler))
.start();
}
/**
@ -144,20 +146,20 @@ public class App {
public void stop() throws InterruptedException, IOException {
reactor.stop();
dispatcher.stop();
for (AbstractNioChannel channel : channels) {
for (var channel : channels) {
channel.getJavaChannel().close();
}
}
private AbstractNioChannel tcpChannel(int port, ChannelHandler handler) throws IOException {
NioServerSocketChannel channel = new NioServerSocketChannel(port, handler);
var channel = new NioServerSocketChannel(port, handler);
channel.bind();
channels.add(channel);
return channel;
}
private AbstractNioChannel udpChannel(int port, ChannelHandler handler) throws IOException {
NioDatagramChannel channel = new NioDatagramChannel(port, handler);
var channel = new NioDatagramChannel(port, handler);
channel.bind();
channels.add(channel);
return channel;

View File

@ -25,7 +25,6 @@ package com.iluwatar.reactor.app;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
@ -55,7 +54,7 @@ public class AppClient {
* @throws IOException if any I/O error occurs.
*/
public static void main(String[] args) throws IOException {
AppClient appClient = new AppClient();
var appClient = new AppClient();
appClient.start();
}
@ -118,8 +117,8 @@ public class AppClient {
@Override
public void run() {
try (Socket socket = new Socket(InetAddress.getLocalHost(), serverPort)) {
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream);
var outputStream = socket.getOutputStream();
var writer = new PrintWriter(outputStream);
sendLogRequests(writer, socket.getInputStream());
} catch (IOException e) {
LOGGER.error("error sending requests", e);
@ -128,12 +127,12 @@ public class AppClient {
}
private void sendLogRequests(PrintWriter writer, InputStream inputStream) throws IOException {
for (int i = 0; i < 4; i++) {
for (var i = 0; i < 4; i++) {
writer.println(clientName + " - Log request: " + i);
writer.flush();
byte[] data = new byte[1024];
int read = inputStream.read(data, 0, data.length);
var data = new byte[1024];
var read = inputStream.read(data, 0, data.length);
if (read == 0) {
LOGGER.info("Read zero bytes");
} else {
@ -167,17 +166,17 @@ public class AppClient {
@Override
public void run() {
try (DatagramSocket socket = new DatagramSocket()) {
for (int i = 0; i < 4; i++) {
try (var socket = new DatagramSocket()) {
for (var i = 0; i < 4; i++) {
String message = clientName + " - Log request: " + i;
DatagramPacket request =
new DatagramPacket(message.getBytes(), message.getBytes().length, remoteAddress);
var message = clientName + " - Log request: " + i;
var bytes = message.getBytes();
var request = new DatagramPacket(bytes, bytes.length, remoteAddress);
socket.send(request);
byte[] data = new byte[1024];
DatagramPacket reply = new DatagramPacket(data, data.length);
var data = new byte[1024];
var reply = new DatagramPacket(data, data.length);
socket.receive(reply);
if (reply.getLength() == 0) {
LOGGER.info("Read zero bytes");

View File

@ -54,7 +54,7 @@ public class LoggingHandler implements ChannelHandler {
doLogging((ByteBuffer) readObject);
sendReply(channel, key);
} else if (readObject instanceof DatagramPacket) {
DatagramPacket datagram = (DatagramPacket) readObject;
var datagram = (DatagramPacket) readObject;
doLogging(datagram.getData());
sendReply(channel, datagram, key);
} else {
@ -71,14 +71,14 @@ public class LoggingHandler implements ChannelHandler {
* Create a reply acknowledgement datagram packet setting the receiver to the sender of incoming
* message.
*/
DatagramPacket replyPacket = new DatagramPacket(ByteBuffer.wrap(ACK));
var replyPacket = new DatagramPacket(ByteBuffer.wrap(ACK));
replyPacket.setReceiver(incomingPacket.getSender());
channel.write(replyPacket, key);
}
private static void sendReply(AbstractNioChannel channel, SelectionKey key) {
ByteBuffer buffer = ByteBuffer.wrap(ACK);
var buffer = ByteBuffer.wrap(ACK);
channel.write(buffer, key);
}

View File

@ -46,8 +46,7 @@ public abstract class AbstractNioChannel {
private final SelectableChannel channel;
private final ChannelHandler handler;
private final Map<SelectableChannel, Queue<Object>> channelToPendingWrites =
new ConcurrentHashMap<>();
private final Map<SelectableChannel, Queue<Object>> channelToPendingWrites;
private NioReactor reactor;
/**
@ -59,6 +58,7 @@ public abstract class AbstractNioChannel {
public AbstractNioChannel(ChannelHandler handler, SelectableChannel channel) {
this.handler = handler;
this.channel = channel;
this.channelToPendingWrites = new ConcurrentHashMap<>();
}
/**
@ -117,18 +117,14 @@ public abstract class AbstractNioChannel {
* whole pending block of data at once.
*/
void flush(SelectionKey key) throws IOException {
Queue<Object> pendingWrites = channelToPendingWrites.get(key.channel());
while (true) {
Object pendingWrite = pendingWrites.poll();
if (pendingWrite == null) {
// We don't have anything more to write so channel is interested in reading more data
reactor.changeOps(key, SelectionKey.OP_READ);
break;
}
var pendingWrites = channelToPendingWrites.get(key.channel());
Object pendingWrite;
while ((pendingWrite = pendingWrites.poll()) != null) {
// ask the concrete channel to make sense of data and write it to java channel
doWrite(pendingWrite, key);
}
// We don't have anything more to write so channel is interested in reading more data
reactor.changeOps(key, SelectionKey.OP_READ);
}
/**
@ -162,7 +158,7 @@ public abstract class AbstractNioChannel {
* @param key the key which is writable.
*/
public void write(Object data, SelectionKey key) {
Queue<Object> pendingWrites = this.channelToPendingWrites.get(key.channel());
var pendingWrites = this.channelToPendingWrites.get(key.channel());
if (pendingWrites == null) {
synchronized (this.channelToPendingWrites) {
pendingWrites = this.channelToPendingWrites.get(key.channel());

View File

@ -73,15 +73,15 @@ public class NioDatagramChannel extends AbstractNioChannel {
*/
@Override
public DatagramPacket read(SelectionKey key) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketAddress sender = ((DatagramChannel) key.channel()).receive(buffer);
var buffer = ByteBuffer.allocate(1024);
var sender = ((DatagramChannel) key.channel()).receive(buffer);
/*
* It is required to create a DatagramPacket because we need to preserve which socket address
* acts as destination for sending reply packets.
*/
buffer.flip();
DatagramPacket packet = new DatagramPacket(buffer);
var packet = new DatagramPacket(buffer);
packet.setSender(sender);
return packet;
@ -115,7 +115,7 @@ public class NioDatagramChannel extends AbstractNioChannel {
*/
@Override
protected void doWrite(Object pendingWrite, SelectionKey key) throws IOException {
DatagramPacket pendingPacket = (DatagramPacket) pendingWrite;
var pendingPacket = (DatagramPacket) pendingWrite;
getJavaChannel().send(pendingPacket.getData(), pendingPacket.getReceiver());
}

View File

@ -27,10 +27,7 @@ import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -119,20 +116,15 @@ public class NioReactor {
* @throws IOException if any I/O error occurs.
*/
public NioReactor registerChannel(AbstractNioChannel channel) throws IOException {
SelectionKey key = channel.getJavaChannel().register(selector, channel.getInterestedOps());
var key = channel.getJavaChannel().register(selector, channel.getInterestedOps());
key.attach(channel);
channel.setReactor(this);
return this;
}
private void eventLoop() throws IOException {
while (true) {
// honor interrupt request
if (Thread.interrupted()) {
break;
}
while (!Thread.interrupted()) {
// honor any pending commands first
processPendingCommands();
@ -145,12 +137,11 @@ public class NioReactor {
/*
* Represents the events that have occurred on registered handles.
*/
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
var keys = selector.selectedKeys();
var iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
var key = iterator.next();
if (!key.isValid()) {
iterator.remove();
continue;
@ -162,9 +153,9 @@ public class NioReactor {
}
private void processPendingCommands() {
Iterator<Runnable> iterator = pendingCommands.iterator();
var iterator = pendingCommands.iterator();
while (iterator.hasNext()) {
Runnable command = iterator.next();
var command = iterator.next();
command.run();
iterator.remove();
}
@ -185,15 +176,14 @@ public class NioReactor {
}
private static void onChannelWritable(SelectionKey key) throws IOException {
AbstractNioChannel channel = (AbstractNioChannel) key.attachment();
var channel = (AbstractNioChannel) key.attachment();
channel.flush(key);
}
private void onChannelReadable(SelectionKey key) {
try {
// reads the incoming data in context of reactor main loop. Can this be improved?
Object readObject = ((AbstractNioChannel) key.attachment()).read(key);
var readObject = ((AbstractNioChannel) key.attachment()).read(key);
dispatchReadEvent(key, readObject);
} catch (IOException e) {
try {
@ -212,10 +202,10 @@ public class NioReactor {
}
private void onChannelAcceptable(SelectionKey key) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
var serverSocketChannel = (ServerSocketChannel) key.channel();
var socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);
var readKey = socketChannel.register(selector, SelectionKey.OP_READ);
readKey.attach(key.attachment());
}

View File

@ -83,9 +83,9 @@ public class NioServerSocketChannel extends AbstractNioChannel {
*/
@Override
public ByteBuffer read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = socketChannel.read(buffer);
var socketChannel = (SocketChannel) key.channel();
var buffer = ByteBuffer.allocate(1024);
var read = socketChannel.read(buffer);
buffer.flip();
if (read == -1) {
throw new IOException("Socket closed");
@ -100,9 +100,9 @@ public class NioServerSocketChannel extends AbstractNioChannel {
*/
@Override
public void bind() throws IOException {
getJavaChannel().socket().bind(
new InetSocketAddress(InetAddress.getLocalHost(), port));
getJavaChannel().configureBlocking(false);
var javaChannel = getJavaChannel();
javaChannel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
javaChannel.configureBlocking(false);
LOGGER.info("Bound TCP socket at port: {}", port);
}
@ -112,7 +112,7 @@ public class NioServerSocketChannel extends AbstractNioChannel {
*/
@Override
protected void doWrite(Object pendingWrite, SelectionKey key) throws IOException {
ByteBuffer pendingBuffer = (ByteBuffer) pendingWrite;
var pendingBuffer = (ByteBuffer) pendingWrite;
((SocketChannel) key.channel()).write(pendingBuffer);
}
}

View File

@ -25,14 +25,12 @@ package com.iluwatar.reactor.app;
import com.iluwatar.reactor.framework.SameThreadDispatcher;
import com.iluwatar.reactor.framework.ThreadPoolDispatcher;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
*
* This class tests the Distributed Logging service by starting a Reactor and then sending it
* concurrent logging requests using multiple clients.
*/
@ -49,10 +47,10 @@ public class ReactorTest {
@Test
public void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedException {
LOGGER.info("testAppUsingThreadPoolDispatcher start");
App app = new App(new ThreadPoolDispatcher(2));
var app = new App(new ThreadPoolDispatcher(2));
app.start();
AppClient client = new AppClient();
var client = new AppClient();
client.start();
// allow clients to send requests. Artificial delay.
@ -77,10 +75,10 @@ public class ReactorTest {
@Test
public void testAppUsingSameThreadDispatcher() throws IOException, InterruptedException {
LOGGER.info("testAppUsingSameThreadDispatcher start");
App app = new App(new SameThreadDispatcher());
var app = new App(new SameThreadDispatcher());
app.start();
AppClient client = new AppClient();
var client = new AppClient();
client.start();
// allow clients to send requests. Artificial delay.

View File

@ -23,11 +23,9 @@
package com.iluwatar.reader.writer.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -58,19 +56,21 @@ public class App {
*/
public static void main(String[] args) {
ExecutorService executeService = Executors.newFixedThreadPool(10);
ReaderWriterLock lock = new ReaderWriterLock();
var executeService = Executors.newFixedThreadPool(10);
var lock = new ReaderWriterLock();
// Start writers
IntStream.range(0, 5)
.forEach(i -> executeService.submit(new Writer("Writer " + i, lock.writeLock(),
ThreadLocalRandom.current().nextLong(5000))));
for (var i = 0; i < 5; i++) {
var writingTime = ThreadLocalRandom.current().nextLong(5000);
executeService.submit(new Writer("Writer " + i, lock.writeLock(), writingTime));
}
LOGGER.info("Writers added...");
// Start readers
IntStream.range(0, 5)
.forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(),
ThreadLocalRandom.current().nextLong(10))));
for (var i = 0; i < 5; i++) {
var readingTime = ThreadLocalRandom.current().nextLong(10);
executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime));
}
LOGGER.info("Readers added...");
try {
@ -81,9 +81,10 @@ public class App {
}
// Start readers
IntStream.range(6, 10)
.forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(),
ThreadLocalRandom.current().nextLong(10))));
for (var i = 6; i < 10; i++) {
var readingTime = ThreadLocalRandom.current().nextLong(10);
executeService.submit(new Reader("Reader " + i, lock.readLock(), readingTime));
}
LOGGER.info("More readers added...");

View File

@ -43,7 +43,7 @@ public class ReaderWriterLock implements ReadWriteLock {
private static final Logger LOGGER = LoggerFactory.getLogger(ReaderWriterLock.class);
private Object readerMutex = new Object();
private final Object readerMutex = new Object();
private int currentReaderCount;
@ -57,7 +57,7 @@ public class ReaderWriterLock implements ReadWriteLock {
*
* <p>This is the most important field in this class to control the access for reader/writer.
*/
private Set<Object> globalMutex = new HashSet<>();
private final Set<Object> globalMutex = new HashSet<>();
private ReadLock readerLock = new ReadLock();
private WriteLock writerLock = new WriteLock();
@ -114,8 +114,8 @@ public class ReaderWriterLock implements ReadWriteLock {
try {
globalMutex.wait();
} catch (InterruptedException e) {
LOGGER
.info("InterruptedException while waiting for globalMutex in acquireForReaders", e);
var message = "InterruptedException while waiting for globalMutex in acquireForReaders";
LOGGER.info(message, e);
Thread.currentThread().interrupt();
}
}
@ -125,7 +125,6 @@ public class ReaderWriterLock implements ReadWriteLock {
@Override
public void unlock() {
synchronized (readerMutex) {
currentReaderCount--;
// Release the lock only when it is the last reader, it is ensure that the lock is released
@ -142,7 +141,7 @@ public class ReaderWriterLock implements ReadWriteLock {
}
@Override
public void lockInterruptibly() throws InterruptedException {
public void lockInterruptibly() {
throw new UnsupportedOperationException();
}
@ -152,7 +151,7 @@ public class ReaderWriterLock implements ReadWriteLock {
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
public boolean tryLock(long time, TimeUnit unit) {
throw new UnsupportedOperationException();
}
@ -170,7 +169,6 @@ public class ReaderWriterLock implements ReadWriteLock {
@Override
public void lock() {
synchronized (globalMutex) {
// Wait until the lock is free.
@ -189,7 +187,6 @@ public class ReaderWriterLock implements ReadWriteLock {
@Override
public void unlock() {
synchronized (globalMutex) {
globalMutex.remove(this);
// Notify the waiter, other writer or reader
@ -198,7 +195,7 @@ public class ReaderWriterLock implements ReadWriteLock {
}
@Override
public void lockInterruptibly() throws InterruptedException {
public void lockInterruptibly() {
throw new UnsupportedOperationException();
}
@ -208,7 +205,7 @@ public class ReaderWriterLock implements ReadWriteLock {
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
public boolean tryLock(long time, TimeUnit unit) {
throw new UnsupportedOperationException();
}

View File

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

View File

@ -23,19 +23,17 @@
package com.iluwatar.reader.writer.lock;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.reader.writer.lock.utils.InMemoryAppender;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hongshuwei@gmail.com
*/
@ -61,12 +59,12 @@ public class ReaderAndWriterTest {
@Test
public void testReadAndWrite() throws Exception {
ReaderWriterLock lock = new ReaderWriterLock();
var lock = new ReaderWriterLock();
Reader reader1 = new Reader("Reader 1", lock.readLock());
Writer writer1 = new Writer("Writer 1", lock.writeLock());
var reader1 = new Reader("Reader 1", lock.readLock());
var writer1 = new Writer("Writer 1", lock.writeLock());
ExecutorService executeService = Executors.newFixedThreadPool(2);
var executeService = Executors.newFixedThreadPool(2);
executeService.submit(reader1);
// Let reader1 execute first
Thread.sleep(150);
@ -91,11 +89,11 @@ public class ReaderAndWriterTest {
@Test
public void testWriteAndRead() throws Exception {
ExecutorService executeService = Executors.newFixedThreadPool(2);
ReaderWriterLock lock = new ReaderWriterLock();
var executeService = Executors.newFixedThreadPool(2);
var lock = new ReaderWriterLock();
Reader reader1 = new Reader("Reader 1", lock.readLock());
Writer writer1 = new Writer("Writer 1", lock.writeLock());
var reader1 = new Reader("Reader 1", lock.readLock());
var writer1 = new Writer("Writer 1", lock.writeLock());
executeService.submit(writer1);
// Let writer1 execute first

View File

@ -23,20 +23,18 @@
package com.iluwatar.reader.writer.lock;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
import com.iluwatar.reader.writer.lock.utils.InMemoryAppender;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
/**
* @author hongshuwei@gmail.com
*/
@ -62,11 +60,11 @@ public class ReaderTest {
@Test
public void testRead() throws Exception {
ExecutorService executeService = Executors.newFixedThreadPool(2);
ReaderWriterLock lock = new ReaderWriterLock();
var executeService = Executors.newFixedThreadPool(2);
var lock = new ReaderWriterLock();
Reader reader1 = spy(new Reader("Reader 1", lock.readLock()));
Reader reader2 = spy(new Reader("Reader 2", lock.readLock()));
var reader1 = spy(new Reader("Reader 1", lock.readLock()));
var reader2 = spy(new Reader("Reader 2", lock.readLock()));
executeService.submit(reader1);
Thread.sleep(150);

View File

@ -23,20 +23,18 @@
package com.iluwatar.reader.writer.lock;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
import com.iluwatar.reader.writer.lock.utils.InMemoryAppender;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
/**
* @author hongshuwei@gmail.com
*/
@ -62,11 +60,11 @@ public class WriterTest {
@Test
public void testWrite() throws Exception {
ExecutorService executeService = Executors.newFixedThreadPool(2);
ReaderWriterLock lock = new ReaderWriterLock();
var executeService = Executors.newFixedThreadPool(2);
var lock = new ReaderWriterLock();
Writer writer1 = spy(new Writer("Writer 1", lock.writeLock()));
Writer writer2 = spy(new Writer("Writer 2", lock.writeLock()));
var writer1 = spy(new Writer("Writer 1", lock.writeLock()));
var writer2 = spy(new Writer("Writer 2", lock.writeLock()));
executeService.submit(writer1);
// Let write1 execute first

View File

@ -26,10 +26,9 @@ package com.iluwatar.reader.writer.lock.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.LoggerFactory;
/**
* InMemory Log Appender Util.

View File

@ -24,7 +24,6 @@
package com.iluwatar.repository;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@ -55,14 +54,13 @@ public class App {
*/
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
PersonRepository repository = context.getBean(PersonRepository.class);
var context = new ClassPathXmlApplicationContext("applicationContext.xml");
var repository = context.getBean(PersonRepository.class);
Person peter = new Person("Peter", "Sagan", 17);
Person nasta = new Person("Nasta", "Kuzminova", 25);
Person john = new Person("John", "lawrence", 35);
Person terry = new Person("Terry", "Law", 36);
var peter = new Person("Peter", "Sagan", 17);
var nasta = new Person("Nasta", "Kuzminova", 25);
var john = new Person("John", "lawrence", 35);
var terry = new Person("Terry", "Law", 36);
// Add new Person records
repository.save(peter);
@ -74,17 +72,15 @@ public class App {
LOGGER.info("Count Person records: {}", repository.count());
// Print all records
List<Person> persons = (List<Person>) repository.findAll();
for (Person person : persons) {
LOGGER.info(person.toString());
}
var persons = (List<Person>) repository.findAll();
persons.stream().map(Person::toString).forEach(LOGGER::info);
// Update Person
nasta.setName("Barbora");
nasta.setSurname("Spotakova");
repository.save(nasta);
LOGGER.info("Find by id 2: {}", repository.findById(2L).get());
repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p));
// Remove record from Person
repository.deleteById(2L);
@ -93,16 +89,15 @@ public class App {
LOGGER.info("Count Person records: {}", repository.count());
// find by name
Optional<Person> p = repository.findOne(new PersonSpecifications.NameEqualSpec("John"));
LOGGER.info("Find by John is {}", p.get());
repository
.findOne(new PersonSpecifications.NameEqualSpec("John"))
.ifPresent(p -> LOGGER.info("Find by John is {}", p));
// find by age
persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
LOGGER.info("Find Person with age between 20,40: ");
for (Person person : persons) {
LOGGER.info(person.toString());
}
persons.stream().map(Person::toString).forEach(LOGGER::info);
repository.deleteAll();

View File

@ -25,7 +25,6 @@ package com.iluwatar.repository;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
@ -55,7 +54,7 @@ public class AppConfig {
*/
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource basicDataSource = new BasicDataSource();
var basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("org.h2.Driver");
basicDataSource.setUrl("jdbc:h2:~/databases/person");
basicDataSource.setUsername("sa");
@ -68,13 +67,11 @@ public class AppConfig {
*/
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager =
new LocalContainerEntityManagerFactoryBean();
var entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource());
entityManager.setPackagesToScan("com.iluwatar");
entityManager.setPersistenceProvider(new HibernatePersistenceProvider());
entityManager.setJpaProperties(jpaProperties());
return entityManager;
}
@ -82,7 +79,7 @@ public class AppConfig {
* Properties for Jpa.
*/
private static Properties jpaProperties() {
Properties properties = new Properties();
var properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
return properties;
@ -93,7 +90,7 @@ public class AppConfig {
*/
@Bean
public JpaTransactionManager transactionManager() throws SQLException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
var transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@ -104,15 +101,13 @@ public class AppConfig {
* @param args command line args
*/
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(AppConfig.class);
var repository = context.getBean(PersonRepository.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
AppConfig.class);
PersonRepository repository = context.getBean(PersonRepository.class);
Person peter = new Person("Peter", "Sagan", 17);
Person nasta = new Person("Nasta", "Kuzminova", 25);
Person john = new Person("John", "lawrence", 35);
Person terry = new Person("Terry", "Law", 36);
var peter = new Person("Peter", "Sagan", 17);
var nasta = new Person("Nasta", "Kuzminova", 25);
var john = new Person("John", "lawrence", 35);
var terry = new Person("Terry", "Law", 36);
// Add new Person records
repository.save(peter);
@ -124,17 +119,15 @@ public class AppConfig {
LOGGER.info("Count Person records: {}", repository.count());
// Print all records
List<Person> persons = (List<Person>) repository.findAll();
for (Person person : persons) {
LOGGER.info(person.toString());
}
var persons = (List<Person>) repository.findAll();
persons.stream().map(Person::toString).forEach(LOGGER::info);
// Update Person
nasta.setName("Barbora");
nasta.setSurname("Spotakova");
repository.save(nasta);
LOGGER.info("Find by id 2: {}", repository.findById(2L).get());
repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p));
// Remove record from Person
repository.deleteById(2L);
@ -143,16 +136,15 @@ public class AppConfig {
LOGGER.info("Count Person records: {}", repository.count());
// find by name
Optional<Person> p = repository.findOne(new PersonSpecifications.NameEqualSpec("John"));
LOGGER.info("Find by John is {}", p.get());
repository
.findOne(new PersonSpecifications.NameEqualSpec("John"))
.ifPresent(p -> LOGGER.info("Find by John is {}", p));
// find by age
persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
LOGGER.info("Find Person with age between 20,40: ");
for (Person person : persons) {
LOGGER.info(person.toString());
}
persons.stream().map(Person::toString).forEach(LOGGER::info);
context.close();

View File

@ -92,9 +92,8 @@ public class Person {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
final var prime = 31;
var result = 1;
result = prime * result + age;
result = prime * result + (id == null ? 0 : id.hashCode());
result = prime * result + (name == null ? 0 : name.hashCode());
@ -113,7 +112,7 @@ public class Person {
if (getClass() != obj.getClass()) {
return false;
}
Person other = (Person) obj;
var other = (Person) obj;
if (age != other.age) {
return false;
}
@ -132,13 +131,9 @@ public class Person {
return false;
}
if (surname == null) {
if (other.surname != null) {
return false;
return other.surname == null;
}
} else if (!surname.equals(other.surname)) {
return false;
}
return true;
return surname.equals(other.surname);
}
}

View File

@ -50,9 +50,7 @@ public class PersonSpecifications {
@Override
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.between(root.get("age"), from, to);
}
}
@ -72,9 +70,7 @@ public class PersonSpecifications {
* Get predicate.
*/
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.equal(root.get("name"), this.name);
}
}

View File

@ -23,7 +23,13 @@
package com.iluwatar.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.Lists;
import java.util.List;
import javax.annotation.Resource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -31,16 +37,9 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query
* by {@link org.springframework.data.jpa.domain.Specification} are also test.
*
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {AppConfig.class})
@ -49,33 +48,30 @@ public class AnnotationBasedRepositoryTest {
@Resource
private PersonRepository repository;
Person peter = new Person("Peter", "Sagan", 17);
Person nasta = new Person("Nasta", "Kuzminova", 25);
Person john = new Person("John", "lawrence", 35);
Person terry = new Person("Terry", "Law", 36);
private Person peter = new Person("Peter", "Sagan", 17);
private Person nasta = new Person("Nasta", "Kuzminova", 25);
private Person john = new Person("John", "lawrence", 35);
private Person terry = new Person("Terry", "Law", 36);
List<Person> persons = List.of(peter, nasta, john, terry);
private List<Person> persons = List.of(peter, nasta, john, terry);
/**
* Prepare data for test
*/
@BeforeEach
public void setup() {
repository.saveAll(persons);
}
@Test
public void testFindAll() {
List<Person> actuals = Lists.newArrayList(repository.findAll());
var actuals = Lists.newArrayList(repository.findAll());
assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals));
}
@Test
public void testSave() {
Person terry = repository.findByName("Terry");
var terry = repository.findByName("Terry");
terry.setSurname("Lee");
terry.setAge(47);
repository.save(terry);
@ -87,8 +83,7 @@ public class AnnotationBasedRepositoryTest {
@Test
public void testDelete() {
Person terry = repository.findByName("Terry");
var terry = repository.findByName("Terry");
repository.delete(terry);
assertEquals(3, repository.count());
@ -97,31 +92,26 @@ public class AnnotationBasedRepositoryTest {
@Test
public void testCount() {
assertEquals(4, repository.count());
}
@Test
public void testFindAllByAgeBetweenSpec() {
List<Person> persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
var persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
assertEquals(3, persons.size());
assertTrue(persons.stream().allMatch((item) -> {
return item.getAge() > 20 && item.getAge() < 40;
}));
assertTrue(persons.stream().allMatch((item) -> item.getAge() > 20 && item.getAge() < 40));
}
@Test
public void testFindOneByNameEqualSpec() {
Optional<Person> actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry"));
var actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry"));
assertTrue(actual.isPresent());
assertEquals(terry, actual.get());
}
@AfterEach
public void cleanup() {
repository.deleteAll();
}

View File

@ -23,6 +23,12 @@
package com.iluwatar.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -30,16 +36,8 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* This case is Just for test the Annotation Based configuration
*
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {AppConfig.class})
@ -62,12 +60,11 @@ public class AppConfigTest {
@Test
@Transactional
public void testQuery() throws SQLException {
ResultSet resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1");
var resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1");
var expected = "1";
String result = null;
String expected = "1";
while (resultSet.next()) {
result = resultSet.getString(1);
}
assertEquals(expected, result);
}

View File

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

View File

@ -23,7 +23,13 @@
package com.iluwatar.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.Lists;
import java.util.List;
import javax.annotation.Resource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -31,12 +37,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query
* by {@link org.springframework.data.jpa.domain.Specification} are also test.
@ -48,33 +48,30 @@ public class RepositoryTest {
@Resource
private PersonRepository repository;
Person peter = new Person("Peter", "Sagan", 17);
Person nasta = new Person("Nasta", "Kuzminova", 25);
Person john = new Person("John", "lawrence", 35);
Person terry = new Person("Terry", "Law", 36);
private Person peter = new Person("Peter", "Sagan", 17);
private Person nasta = new Person("Nasta", "Kuzminova", 25);
private Person john = new Person("John", "lawrence", 35);
private Person terry = new Person("Terry", "Law", 36);
List<Person> persons = List.of(peter, nasta, john, terry);
private List<Person> persons = List.of(peter, nasta, john, terry);
/**
* Prepare data for test
*/
@BeforeEach
public void setup() {
repository.saveAll(persons);
}
@Test
public void testFindAll() {
List<Person> actuals = Lists.newArrayList(repository.findAll());
var actuals = Lists.newArrayList(repository.findAll());
assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals));
}
@Test
public void testSave() {
Person terry = repository.findByName("Terry");
var terry = repository.findByName("Terry");
terry.setSurname("Lee");
terry.setAge(47);
repository.save(terry);
@ -86,8 +83,7 @@ public class RepositoryTest {
@Test
public void testDelete() {
Person terry = repository.findByName("Terry");
var terry = repository.findByName("Terry");
repository.delete(terry);
assertEquals(3, repository.count());
@ -96,14 +92,12 @@ public class RepositoryTest {
@Test
public void testCount() {
assertEquals(4, repository.count());
}
@Test
public void testFindAllByAgeBetweenSpec() {
List<Person> persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
var persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
assertEquals(3, persons.size());
assertTrue(persons.stream().allMatch(item -> item.getAge() > 20 && item.getAge() < 40));
@ -111,14 +105,13 @@ public class RepositoryTest {
@Test
public void testFindOneByNameEqualSpec() {
Optional<Person> actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry"));
var actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry"));
assertTrue(actual.isPresent());
assertEquals(terry, actual.get());
}
@AfterEach
public void cleanup() {
repository.deleteAll();
}

View File

@ -54,11 +54,11 @@ public class App {
*/
public static void main(String[] args) throws Exception {
try (SlidingDoor slidingDoor = new SlidingDoor()) {
try (var ignored = new SlidingDoor()) {
LOGGER.info("Walking in.");
}
try (TreasureChest treasureChest = new TreasureChest()) {
try (var ignored = new TreasureChest()) {
LOGGER.info("Looting contents.");
}
}

View File

@ -38,7 +38,7 @@ public class SlidingDoor implements AutoCloseable {
}
@Override
public void close() throws Exception {
public void close() {
LOGGER.info("Sliding door closes.");
}
}

View File

@ -24,7 +24,6 @@
package com.iluwatar.resource.acquisition.is.initialization;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -40,7 +39,7 @@ public class TreasureChest implements Closeable {
}
@Override
public void close() throws IOException {
public void close() {
LOGGER.info("Treasure chest closes.");
}
}

View File

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

View File

@ -23,19 +23,18 @@
package com.iluwatar.resource.acquisition.is.initialization;
import static org.junit.jupiter.api.Assertions.assertTrue;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Date: 12/28/15 - 9:31 PM
*
@ -56,8 +55,8 @@ public class ClosableTest {
}
@Test
public void testOpenClose() throws Exception {
try (final SlidingDoor door = new SlidingDoor(); final TreasureChest chest = new TreasureChest()) {
public void testOpenClose() {
try (final var ignored = new SlidingDoor(); final var ignored1 = new TreasureChest()) {
assertTrue(appender.logContains("Sliding door opens."));
assertTrue(appender.logContains("Treasure chest opens."));
}

View File

@ -78,7 +78,7 @@ to recover from this error.
We can model a 'recoverable' scenario by instantiating `FindCustomer` like this:
```java
final BusinessOperation<String> op = new FindCustomer(
final var op = new FindCustomer(
"12345",
new CustomerNotFoundException("not found"),
new CustomerNotFoundException("still not found"),
@ -97,7 +97,7 @@ worker thread in the database subsystem typically needs 50ms to
this:
```java
final BusinessOperation<String> op = new Retry<>(
final var op = new Retry<>(
new FindCustomer(
"1235",
new CustomerNotFoundException("not found"),

View File

@ -90,14 +90,14 @@ public final class App {
}
private static void errorWithRetry() throws Exception {
final Retry<String> retry = new Retry<>(
final var retry = new Retry<>(
new FindCustomer("123", new CustomerNotFoundException("not found")),
3, //3 attempts
100, //100 ms delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
);
op = retry;
final String customerId = op.perform();
final var customerId = op.perform();
LOG.info(String.format(
"However, retrying the operation while ignoring a recoverable error will eventually yield "
+ "the result %s after a number of attempts %s", customerId, retry.attempts()
@ -105,14 +105,14 @@ public final class App {
}
private static void errorWithRetryExponentialBackoff() throws Exception {
final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
final var retry = new RetryExponentialBackoff<>(
new FindCustomer("123", new CustomerNotFoundException("not found")),
6, //6 attempts
30000, //30 s max delay between attempts
e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
);
op = retry;
final String customerId = op.perform();
final var customerId = op.perform();
LOG.info(String.format(
"However, retrying the operation while ignoring a recoverable error will eventually yield "
+ "the result %s after a number of attempts %s", customerId, retry.attempts()

View File

@ -100,8 +100,8 @@ public final class RetryExponentialBackoff<T> implements BusinessOperation<T> {
}
try {
long testDelay = (long) Math.pow(2, this.attempts()) * 1000 + RANDOM.nextInt(1000);
long delay = testDelay < this.maxDelay ? testDelay : maxDelay;
var testDelay = (long) Math.pow(2, this.attempts()) * 1000 + RANDOM.nextInt(1000);
var delay = Math.min(testDelay, this.maxDelay);
Thread.sleep(delay);
} catch (InterruptedException f) {
//ignore

View File

@ -23,12 +23,12 @@
package com.iluwatar.retry;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link FindCustomer}.
*
@ -40,10 +40,7 @@ public class FindCustomerTest {
*/
@Test
public void noExceptions() throws Exception {
assertThat(
new FindCustomer("123").perform(),
is("123")
);
assertThat(new FindCustomer("123").perform(), is("123"));
}
/**
@ -53,9 +50,8 @@ public class FindCustomerTest {
*/
@Test
public void oneException() {
assertThrows(BusinessException.class, () -> {
new FindCustomer("123", new BusinessException("test")).perform();
});
var findCustomer = new FindCustomer("123", new BusinessException("test"));
assertThrows(BusinessException.class, findCustomer::perform);
}
/**
@ -65,7 +61,7 @@ public class FindCustomerTest {
*/
@Test
public void resultAfterExceptions() throws Exception {
final BusinessOperation<String> op = new FindCustomer(
final var op = new FindCustomer(
"123",
new CustomerNotFoundException("not found"),
new DatabaseNotAvailableException("not available")
@ -81,9 +77,6 @@ public class FindCustomerTest {
//ignore
}
assertThat(
op.perform(),
is("123")
);
assertThat(op.perform(), is("123"));
}
}

View File

@ -23,11 +23,12 @@
package com.iluwatar.retry;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link Retry}.
*
@ -38,9 +39,9 @@ public class RetryExponentialBackoffTest {
* Should contain all errors thrown.
*/
@Test
public void errors() throws Exception {
final BusinessException e = new BusinessException("unhandled");
final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
public void errors() {
final var e = new BusinessException("unhandled");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
@ -53,10 +54,7 @@ public class RetryExponentialBackoffTest {
//ignore
}
assertThat(
retry.errors(),
hasItem(e)
);
assertThat(retry.errors(), hasItem(e));
}
/**
@ -65,8 +63,8 @@ public class RetryExponentialBackoffTest {
*/
@Test
public void attempts() {
final BusinessException e = new BusinessException("unhandled");
final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
final var e = new BusinessException("unhandled");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
@ -79,20 +77,17 @@ public class RetryExponentialBackoffTest {
//ignore
}
assertThat(
retry.attempts(),
is(1)
);
assertThat(retry.attempts(), is(1));
}
/**
* Final number of attempts should be equal to the number of attempts asked because we are
* asking it to ignore the exception that will be thrown.
* Final number of attempts should be equal to the number of attempts asked because we are asking
* it to ignore the exception that will be thrown.
*/
@Test
public void ignore() throws Exception {
final BusinessException e = new CustomerNotFoundException("customer not found");
final RetryExponentialBackoff<String> retry = new RetryExponentialBackoff<>(
public void ignore() {
final var e = new CustomerNotFoundException("customer not found");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
@ -106,9 +101,6 @@ public class RetryExponentialBackoffTest {
//ignore
}
assertThat(
retry.attempts(),
is(2)
);
assertThat(retry.attempts(), is(2));
}
}

View File

@ -23,12 +23,12 @@
package com.iluwatar.retry;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link Retry}.
*
@ -40,10 +40,11 @@ public class RetryTest {
*/
@Test
public void errors() {
final BusinessException e = new BusinessException("unhandled");
final Retry<String> retry = new Retry<>(
final var e = new BusinessException("unhandled");
final var retry = new Retry<String>(
() -> {
throw e; },
throw e;
},
2,
0
);
@ -53,10 +54,7 @@ public class RetryTest {
//ignore
}
assertThat(
retry.errors(),
hasItem(e)
);
assertThat(retry.errors(), hasItem(e));
}
/**
@ -65,10 +63,11 @@ public class RetryTest {
*/
@Test
public void attempts() {
final BusinessException e = new BusinessException("unhandled");
final Retry<String> retry = new Retry<>(
final var e = new BusinessException("unhandled");
final var retry = new Retry<String>(
() -> {
throw e; },
throw e;
},
2,
0
);
@ -78,22 +77,20 @@ public class RetryTest {
//ignore
}
assertThat(
retry.attempts(),
is(1)
);
assertThat(retry.attempts(), is(1));
}
/**
* Final number of attempts should be equal to the number of attempts asked because we are
* asking it to ignore the exception that will be thrown.
* Final number of attempts should be equal to the number of attempts asked because we are asking
* it to ignore the exception that will be thrown.
*/
@Test
public void ignore() throws Exception {
final BusinessException e = new CustomerNotFoundException("customer not found");
final Retry<String> retry = new Retry<>(
public void ignore() {
final var e = new CustomerNotFoundException("customer not found");
final var retry = new Retry<String>(
() -> {
throw e; },
throw e;
},
2,
0,
ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass())
@ -104,10 +101,7 @@ public class RetryTest {
//ignore
}
assertThat(
retry.attempts(),
is(2)
);
assertThat(retry.attempts(), is(2));
}
}

View File

@ -30,37 +30,31 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Role Object pattern suggests to model context-specific views
* of an object as separate role objects which are
* dynamically attached to and removed from the core object.
* We call the resulting composite object structure,
* consisting of the core and its role objects, a subject.
* A subject often plays several roles and the same role is likely to
* be played by different subjects.
* As an example consider two different customers playing the role of borrower and
* investor, respectively. Both roles could as well be played by a single {@link Customer} object.
* The common superclass for customer-specific roles is provided by {@link CustomerRole},
* which also supports the {@link Customer} interface.
* The Role Object pattern suggests to model context-specific views of an object as separate role
* objects which are dynamically attached to and removed from the core object. We call the resulting
* composite object structure, consisting of the core and its role objects, a subject. A subject
* often plays several roles and the same role is likely to be played by different subjects. As an
* example consider two different customers playing the role of borrower and investor, respectively.
* Both roles could as well be played by a single {@link Customer} object. The common superclass for
* customer-specific roles is provided by {@link CustomerRole}, which also supports the {@link
* Customer} interface.
*
* <p>The {@link CustomerRole} class is abstract and not meant to be instantiated.
* Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole}
* or {@link InvestorRole}, define and implement the interface for specific roles. It is only
* these subclasses which are instantiated at runtime.
* The {@link BorrowerRole} class defines the context-specific view of {@link Customer}
* objects as needed by the loan department.
* It defines additional operations to manage the customers
* credits and securities. Similarly, the {@link InvestorRole} class adds operations specific
* to the investment departments view of customers.
* A client like the loan application may either work with objects of the {@link CustomerRole}
* class, using the interface class {@link Customer}, or with objects of concrete
* {@link CustomerRole} subclasses. Suppose the loan application knows a particular
* {@link Customer} instance through its {@link Customer} interface. The loan application
* may want to check whether the {@link Customer} object plays the role of Borrower.
* To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For
* the purpose of our example, lets assume we can name roles with enum.
* If the {@link Customer} object can play the role named Borrower, the loan application will
* ask it to return a reference to the corresponding object.
* The loan application may now use this reference to call Borrower-specific operations.
* Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link
* InvestorRole}, define and implement the interface for specific roles. It is only these subclasses
* which are instantiated at runtime. The {@link BorrowerRole} class defines the context-specific
* view of {@link Customer} objects as needed by the loan department. It defines additional
* operations to manage the customers credits and securities. Similarly, the {@link InvestorRole}
* class adds operations specific to the investment departments view of customers. A client like
* the loan application may either work with objects of the {@link CustomerRole} class, using the
* interface class {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses.
* Suppose the loan application knows a particular {@link Customer} instance through its {@link
* Customer} interface. The loan application may want to check whether the {@link Customer} object
* plays the role of Borrower. To this end it calls {@link Customer#hasRole(Role)} with a suitable
* role specification. For the purpose of our example, lets assume we can name roles with enum. If
* the {@link Customer} object can play the role named Borrower, the loan application will ask it
* to return a reference to the corresponding object. The loan application may now use this
* reference to call Borrower-specific operations.
*/
public class ApplicationRoleObject {
@ -72,13 +66,13 @@ public class ApplicationRoleObject {
* @param args program arguments
*/
public static void main(String[] args) {
Customer customer = Customer.newCustomer(Borrower, Investor);
var customer = Customer.newCustomer(Borrower, Investor);
logger.info(" the new customer created : {}", customer);
boolean hasBorrowerRole = customer.hasRole(Borrower);
var hasBorrowerRole = customer.hasRole(Borrower);
logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
boolean hasInvestorRole = customer.hasRole(Investor);
var hasInvestorRole = customer.hasRole(Investor);
logger.info(" customer has an investor role - {}", hasInvestorRole);
customer.getRole(Investor, InvestorRole.class)

View File

@ -23,6 +23,7 @@
package com.iluwatar.roleobject;
import java.util.Arrays;
import java.util.Optional;
/**
@ -32,6 +33,7 @@ public abstract class Customer {
/**
* Add specific role @see {@link Role}.
*
* @param role to add
* @return true if the operation has been successful otherwise false
*/
@ -39,6 +41,7 @@ public abstract class Customer {
/**
* Check specific role @see {@link Role}.
*
* @param role to check
* @return true if the role exists otherwise false
*/
@ -47,6 +50,7 @@ public abstract class Customer {
/**
* Remove specific role @see {@link Role}.
*
* @param role to remove
* @return true if the operation has been successful otherwise false
*/
@ -54,6 +58,7 @@ public abstract class Customer {
/**
* Get specific instance associated with this role @see {@link Role}.
*
* @param role to get
* @param expectedRole instance class expected to get
* @return optional with value if the instance exists and corresponds expected class
@ -67,14 +72,13 @@ public abstract class Customer {
/**
* Create {@link Customer} with given roles.
*
* @param role roles
* @return Customer
*/
public static Customer newCustomer(Role... role) {
Customer customer = newCustomer();
for (Role r : role) {
customer.addRole(r);
}
var customer = newCustomer();
Arrays.stream(role).forEach(customer::addRole);
return customer;
}

View File

@ -73,7 +73,7 @@ public class CustomerCore extends Customer {
@Override
public String toString() {
String roles = Arrays.toString(this.roles.keySet().toArray());
var roles = Arrays.toString(this.roles.keySet().toArray());
return "Customer{roles=" + roles + "}";
}
}

View File

@ -24,7 +24,6 @@
package com.iluwatar.roleobject;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -48,7 +47,7 @@ public enum Role {
*/
@SuppressWarnings("unchecked")
public <T extends CustomerRole> Optional<T> instance() {
Class<? extends CustomerRole> typeCst = this.typeCst;
var typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.newInstance());
} catch (InstantiationException | IllegalAccessException e) {

View File

@ -25,16 +25,12 @@ package com.iluwatar.roleobject;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class BorrowerRoleTest {
@Test
public void borrowTest() {
BorrowerRole borrowerRole = new BorrowerRole();
var borrowerRole = new BorrowerRole();
borrowerRole.setName("test");
String res = "Borrower test wants to get some money.";
Assert.assertEquals(borrowerRole.borrow(),res);
Assert.assertEquals(borrowerRole.borrow(), "Borrower test wants to get some money.");
}
}

View File

@ -22,71 +22,61 @@
*/
package com.iluwatar.roleobject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.*;
public class CustomerCoreTest {
@Test
public void addRole() {
CustomerCore core = new CustomerCore();
boolean add = core.addRole(Role.Borrower);
assertTrue(add);
var core = new CustomerCore();
assertTrue(core.addRole(Role.Borrower));
}
@Test
public void hasRole() {
CustomerCore core = new CustomerCore();
var core = new CustomerCore();
core.addRole(Role.Borrower);
boolean has = core.hasRole(Role.Borrower);
assertTrue(has);
boolean notHas = core.hasRole(Role.Investor);
assertFalse(notHas);
assertTrue(core.hasRole(Role.Borrower));
assertFalse(core.hasRole(Role.Investor));
}
@Test
public void remRole() {
CustomerCore core = new CustomerCore();
var core = new CustomerCore();
core.addRole(Role.Borrower);
Optional<BorrowerRole> bRole = core.getRole(Role.Borrower, BorrowerRole.class);
var bRole = core.getRole(Role.Borrower, BorrowerRole.class);
assertTrue(bRole.isPresent());
boolean res = core.remRole(Role.Borrower);
assertTrue(res);
assertTrue(core.remRole(Role.Borrower));
Optional<BorrowerRole> empt = core.getRole(Role.Borrower, BorrowerRole.class);
var empt = core.getRole(Role.Borrower, BorrowerRole.class);
assertFalse(empt.isPresent());
}
@Test
public void getRole() {
CustomerCore core = new CustomerCore();
var core = new CustomerCore();
core.addRole(Role.Borrower);
Optional<BorrowerRole> bRole = core.getRole(Role.Borrower, BorrowerRole.class);
var bRole = core.getRole(Role.Borrower, BorrowerRole.class);
assertTrue(bRole.isPresent());
Optional<InvestorRole> nonRole = core.getRole(Role.Borrower, InvestorRole.class);
var nonRole = core.getRole(Role.Borrower, InvestorRole.class);
assertFalse(nonRole.isPresent());
Optional<InvestorRole> invRole = core.getRole(Role.Investor, InvestorRole.class);
var invRole = core.getRole(Role.Investor, InvestorRole.class);
assertFalse(invRole.isPresent());
}
@Test
public void toStringTest() {
CustomerCore core = new CustomerCore();
var core = new CustomerCore();
core.addRole(Role.Borrower);
assertEquals(core.toString(), "Customer{roles=[Borrower]}");

View File

@ -29,10 +29,9 @@ public class InvestorRoleTest {
@Test
public void investTest() {
InvestorRole investorRole = new InvestorRole();
var investorRole = new InvestorRole();
investorRole.setName("test");
investorRole.setAmountToInvest(10);
String res = "Investor test has invested 10 dollars";
Assert.assertEquals(investorRole.invest(), res);
Assert.assertEquals(investorRole.invest(), "Investor test has invested 10 dollars");
}
}

View File

@ -25,15 +25,11 @@ package com.iluwatar.roleobject;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.*;
public class RoleTest {
@Test
public void instanceTest() {
Optional<CustomerRole> instance = Role.Borrower.instance();
var instance = Role.Borrower.instance();
Assert.assertTrue(instance.isPresent());
Assert.assertEquals(instance.get().getClass(), BorrowerRole.class);
}