From 20ea465b7fa00477fb2afa66a4b2d67155c34384 Mon Sep 17 00:00:00 2001 From: Anurag Agarwal Date: Sat, 4 Jan 2020 22:13:12 +0530 Subject: [PATCH] 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 --- .../com/iluwatar/queue/load/leveling/App.java | 10 +- .../queue/load/leveling/MessageQueue.java | 10 +- .../queue/load/leveling/ServiceExecutor.java | 2 +- .../queue/load/leveling/TaskGenerator.java | 5 +- .../iluwatar/queue/load/leveling/AppTest.java | 7 +- .../queue/load/leveling/MessageQueueTest.java | 14 +-- .../queue/load/leveling/MessageTest.java | 14 +-- .../load/leveling/TaskGenSrvExeTest.java | 20 ++-- .../java/com/iluwatar/reactor/app/App.java | 14 ++- .../com/iluwatar/reactor/app/AppClient.java | 27 +++-- .../iluwatar/reactor/app/LoggingHandler.java | 6 +- .../reactor/framework/AbstractNioChannel.java | 20 ++-- .../reactor/framework/NioDatagramChannel.java | 8 +- .../reactor/framework/NioReactor.java | 36 +++--- .../framework/NioServerSocketChannel.java | 14 +-- .../com/iluwatar/reactor/app/ReactorTest.java | 20 ++-- .../com/iluwatar/reader/writer/lock/App.java | 27 ++--- .../reader/writer/lock/ReaderWriterLock.java | 19 ++- .../iluwatar/reader/writer/lock/AppTest.java | 5 +- .../writer/lock/ReaderAndWriterTest.java | 26 ++--- .../reader/writer/lock/ReaderTest.java | 20 ++-- .../reader/writer/lock/WriterTest.java | 20 ++-- .../writer/lock/utils/InMemoryAppender.java | 3 +- .../java/com/iluwatar/repository/App.java | 31 +++-- .../com/iluwatar/repository/AppConfig.java | 42 +++---- .../java/com/iluwatar/repository/Person.java | 15 +-- .../repository/PersonSpecifications.java | 4 - .../AnnotationBasedRepositoryTest.java | 48 +++----- .../iluwatar/repository/AppConfigTest.java | 21 ++-- .../java/com/iluwatar/repository/AppTest.java | 5 +- .../iluwatar/repository/RepositoryTest.java | 43 +++---- .../acquisition/is/initialization/App.java | 4 +- .../is/initialization/SlidingDoor.java | 2 +- .../is/initialization/TreasureChest.java | 3 +- .../is/initialization/AppTest.java | 5 +- .../is/initialization/ClosableTest.java | 9 +- retry/README.md | 4 +- .../src/main/java/com/iluwatar/retry/App.java | 8 +- .../retry/RetryExponentialBackoff.java | 4 +- .../com/iluwatar/retry/FindCustomerTest.java | 27 ++--- .../retry/RetryExponentialBackoffTest.java | 68 +++++------ .../java/com/iluwatar/retry/RetryTest.java | 46 ++++---- .../roleobject/ApplicationRoleObject.java | 58 +++++---- .../com/iluwatar/roleobject/Customer.java | 12 +- .../com/iluwatar/roleobject/CustomerCore.java | 2 +- .../com/iluwatar/roleobject/CustomerRole.java | 2 +- .../java/com/iluwatar/roleobject/Role.java | 3 +- .../roleobject/ApplicationRoleObjectTest.java | 8 +- .../iluwatar/roleobject/BorrowerRoleTest.java | 16 +-- .../iluwatar/roleobject/CustomerCoreTest.java | 110 ++++++++---------- .../iluwatar/roleobject/InvestorRoleTest.java | 15 ++- .../com/iluwatar/roleobject/RoleTest.java | 16 +-- 52 files changed, 424 insertions(+), 554 deletions(-) diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java index ba7aac954..c73caf242 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java @@ -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.. diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java index 6d55d026b..339ea2867 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java @@ -40,7 +40,7 @@ public class MessageQueue { // Default constructor when called creates Blocking Queue object. public MessageQueue() { - this.blkQueue = new ArrayBlockingQueue(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; } -} \ No newline at end of file +} diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java index e490e9dd7..2a33286a0 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java @@ -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."); diff --git a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java index 885e51652..492b58623 100644 --- a/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java +++ b/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java @@ -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); diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java index b8d772f39..55c9528e6 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java @@ -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[]{}); } } \ No newline at end of file diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java index 0333a666d..b712853f6 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java @@ -23,25 +23,23 @@ 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")); - + // retrieve message assertEquals("MessageQueue Test", msgQueue.retrieveMsg().getMsg()); } diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java index 4dad77162..15b90078c 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java @@ -23,23 +23,21 @@ 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 { - + @Test 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()); } } diff --git a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java index a6cd3d36c..1e81c5d11 100644 --- a/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java +++ b/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java @@ -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(); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/App.java b/reactor/src/main/java/com/iluwatar/reactor/app/App.java index 0804f8862..3bd8176a6 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/App.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/App.java @@ -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; diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java index a15437396..ec6022621 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java @@ -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"); diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java index edf7e26fd..8babaa3a0 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/LoggingHandler.java @@ -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); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java index 6b356d021..7adf18166 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/AbstractNioChannel.java @@ -46,8 +46,7 @@ public abstract class AbstractNioChannel { private final SelectableChannel channel; private final ChannelHandler handler; - private final Map> channelToPendingWrites = - new ConcurrentHashMap<>(); + private final Map> 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 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 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()); diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java index ba4b68231..13657cdb2 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioDatagramChannel.java @@ -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()); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java index becf1fd2d..1a0b17386 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -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; - } - + // honor interrupt request + 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 keys = selector.selectedKeys(); - - Iterator 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 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()); } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java index 7c52a95c3..04673f01d 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioServerSocketChannel.java @@ -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); } } diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java index 4b2f0348a..76ddfbdba 100644 --- a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java +++ b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -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. */ @@ -42,17 +40,17 @@ public class ReactorTest { /** * Test the application using pooled thread dispatcher. - * - * @throws IOException if any I/O error occurs. + * + * @throws IOException if any I/O error occurs. * @throws InterruptedException if interrupted while stopping the application. */ @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. @@ -70,17 +68,17 @@ public class ReactorTest { /** * Test the application using same thread dispatcher. - * - * @throws IOException if any I/O error occurs. + * + * @throws IOException if any I/O error occurs. * @throws InterruptedException if interrupted while stopping the application. */ @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. diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java index f59ba10cc..c482ab7e7 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java @@ -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..."); diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java index d578b0f21..99c9b056b 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java @@ -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 { * *

This is the most important field in this class to control the access for reader/writer. */ - private Set globalMutex = new HashSet<>(); + private final Set 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(); } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java index 0c323724e..a0175e259 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java @@ -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[]{}); } } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java index 1f6edfa3c..ffd1dd4a4 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java @@ -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 diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java index 849cf32ba..284a1bc3b 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java @@ -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); diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java index 60c78e573..00edf8b54 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java @@ -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 diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java index 98f14a82b..c7e8bc02a 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java @@ -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. diff --git a/repository/src/main/java/com/iluwatar/repository/App.java b/repository/src/main/java/com/iluwatar/repository/App.java index ac932b815..0308db473 100644 --- a/repository/src/main/java/com/iluwatar/repository/App.java +++ b/repository/src/main/java/com/iluwatar/repository/App.java @@ -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 persons = (List) repository.findAll(); - for (Person person : persons) { - LOGGER.info(person.toString()); - } + var persons = (List) 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 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(); diff --git a/repository/src/main/java/com/iluwatar/repository/AppConfig.java b/repository/src/main/java/com/iluwatar/repository/AppConfig.java index 197205773..50a23026f 100644 --- a/repository/src/main/java/com/iluwatar/repository/AppConfig.java +++ b/repository/src/main/java/com/iluwatar/repository/AppConfig.java @@ -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 persons = (List) repository.findAll(); - for (Person person : persons) { - LOGGER.info(person.toString()); - } + var persons = (List) 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 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(); diff --git a/repository/src/main/java/com/iluwatar/repository/Person.java b/repository/src/main/java/com/iluwatar/repository/Person.java index e83f0ce46..ee1602ace 100644 --- a/repository/src/main/java/com/iluwatar/repository/Person.java +++ b/repository/src/main/java/com/iluwatar/repository/Person.java @@ -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; - } - } else if (!surname.equals(other.surname)) { - return false; + return other.surname == null; } - return true; + return surname.equals(other.surname); } } diff --git a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java index 149c2488e..f91c0a6e1 100644 --- a/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java +++ b/repository/src/main/java/com/iluwatar/repository/PersonSpecifications.java @@ -50,9 +50,7 @@ public class PersonSpecifications { @Override public Predicate toPredicate(Root 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 root, CriteriaQuery query, CriteriaBuilder cb) { - return cb.equal(root.get("name"), this.name); - } } diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index 3b0bff608..6b47cbe9a 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -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,51 +37,41 @@ 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 }) +@SpringBootTest(classes = {AppConfig.class}) 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 persons = List.of(peter, nasta, john, terry); + private List persons = List.of(peter, nasta, john, terry); /** * Prepare data for test */ @BeforeEach public void setup() { - repository.saveAll(persons); } @Test public void testFindAll() { - - List 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 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 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(); } diff --git a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java index c9f292029..403f793af 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -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,19 +36,11 @@ 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 }) +@SpringBootTest(classes = {AppConfig.class}) public class AppConfigTest { @Autowired @@ -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); } diff --git a/repository/src/test/java/com/iluwatar/repository/AppTest.java b/repository/src/test/java/com/iluwatar/repository/AppTest.java index 8889833f6..b12f03d8c 100644 --- a/repository/src/test/java/com/iluwatar/repository/AppTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AppTest.java @@ -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[]{}); } } diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 614f18dba..ad9587aca 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -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,50 +37,41 @@ 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(properties = { "locations=classpath:applicationContext.xml" }) +@SpringBootTest(properties = {"locations=classpath:applicationContext.xml"}) 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 persons = List.of(peter, nasta, john, terry); + private List persons = List.of(peter, nasta, john, terry); /** * Prepare data for test */ @BeforeEach public void setup() { - repository.saveAll(persons); } @Test public void testFindAll() { - - List 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 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 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(); } diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java index 293675e99..08b62ee8b 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java @@ -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."); } } diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java index d890eb4c3..c311f939a 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java @@ -38,7 +38,7 @@ public class SlidingDoor implements AutoCloseable { } @Override - public void close() throws Exception { + public void close() { LOGGER.info("Sliding door closes."); } } diff --git a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java index 26eab1405..2e8595b14 100644 --- a/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java +++ b/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java @@ -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."); } } diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java index 0e58779af..dedeee7e0 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java @@ -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[]{}); } } diff --git a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java index 10a85c6ef..7bba17553 100644 --- a/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java +++ b/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java @@ -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.")); } diff --git a/retry/README.md b/retry/README.md index 27325331d..0f8345412 100644 --- a/retry/README.md +++ b/retry/README.md @@ -78,7 +78,7 @@ to recover from this error. We can model a 'recoverable' scenario by instantiating `FindCustomer` like this: ```java -final BusinessOperation 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 op = new Retry<>( +final var op = new Retry<>( new FindCustomer( "1235", new CustomerNotFoundException("not found"), diff --git a/retry/src/main/java/com/iluwatar/retry/App.java b/retry/src/main/java/com/iluwatar/retry/App.java index 594c48295..06f43c29f 100644 --- a/retry/src/main/java/com/iluwatar/retry/App.java +++ b/retry/src/main/java/com/iluwatar/retry/App.java @@ -90,14 +90,14 @@ public final class App { } private static void errorWithRetry() throws Exception { - final Retry 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 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() diff --git a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java index c074f9cd4..54faf4306 100644 --- a/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java +++ b/retry/src/main/java/com/iluwatar/retry/RetryExponentialBackoff.java @@ -100,8 +100,8 @@ public final class RetryExponentialBackoff implements BusinessOperation { } 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 diff --git a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java index b52763099..295d8d763 100644 --- a/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java +++ b/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -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,33 +40,29 @@ public class FindCustomerTest { */ @Test public void noExceptions() throws Exception { - assertThat( - new FindCustomer("123").perform(), - is("123") - ); + assertThat(new FindCustomer("123").perform(), is("123")); } /** * Throws the given exception. - * + * * @throws Exception the expected exception */ @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); } /** * Should first throw the given exceptions, then return the given result. - * + * * @throws Exception not an expected exception */ @Test public void resultAfterExceptions() throws Exception { - final BusinessOperation op = new FindCustomer( - "123", + 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")); } } diff --git a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java index f07d665af..3ca739fbf 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryExponentialBackoffTest.java @@ -23,26 +23,27 @@ 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}. * * @author George Aristy (george.aristy@gmail.com) */ public class RetryExponentialBackoffTest { - /** - * Should contain all errors thrown. - */ + /** + * Should contain all errors thrown. + */ @Test - public void errors() throws Exception { - final BusinessException e = new BusinessException("unhandled"); - final RetryExponentialBackoff retry = new RetryExponentialBackoff<>( - () -> { - throw e; + public void errors() { + final var e = new BusinessException("unhandled"); + final var retry = new RetryExponentialBackoff( + () -> { + throw e; }, 2, 0 @@ -53,22 +54,19 @@ public class RetryExponentialBackoffTest { //ignore } - assertThat( - retry.errors(), - hasItem(e) - ); + assertThat(retry.errors(), hasItem(e)); } - /** - * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking - * it to attempt twice. - */ + /** + * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking + * it to attempt twice. + */ @Test public void attempts() { - final BusinessException e = new BusinessException("unhandled"); - final RetryExponentialBackoff retry = new RetryExponentialBackoff<>( - () -> { - throw e; + final var e = new BusinessException("unhandled"); + final var retry = new RetryExponentialBackoff( + () -> { + throw e; }, 2, 0 @@ -79,22 +77,19 @@ 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 retry = new RetryExponentialBackoff<>( - () -> { - throw e; + public void ignore() { + final var e = new CustomerNotFoundException("customer not found"); + final var retry = new RetryExponentialBackoff( + () -> { + throw e; }, 2, 0, @@ -106,9 +101,6 @@ public class RetryExponentialBackoffTest { //ignore } - assertThat( - retry.attempts(), - is(2) - ); + assertThat(retry.attempts(), is(2)); } } diff --git a/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/retry/src/test/java/com/iluwatar/retry/RetryTest.java index 64df9d14d..b36b6a561 100644 --- a/retry/src/test/java/com/iluwatar/retry/RetryTest.java +++ b/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -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 retry = new Retry<>( + final var e = new BusinessException("unhandled"); + final var retry = new Retry( () -> { - 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 retry = new Retry<>( + final var e = new BusinessException("unhandled"); + final var retry = new Retry( () -> { - 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 retry = new Retry<>( + public void ignore() { + final var e = new CustomerNotFoundException("customer not found"); + final var retry = new Retry( () -> { - 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)); } } \ No newline at end of file diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java index eb76ef34a..0fc028893 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java @@ -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. * *

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 customer’s - * credits and securities. Similarly, the {@link InvestorRole} class adds operations specific - * to the investment department’s 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, let’s 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 customer’s credits and securities. Similarly, the {@link InvestorRole} + * class adds operations specific to the investment department’s 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, let’s 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) diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java index 1d21c5cc8..bca450a38 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java @@ -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; } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java index 670a53904..966d0e3f0 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java @@ -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 + "}"; } } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java index 7f1805924..b961c210e 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java @@ -26,5 +26,5 @@ package com.iluwatar.roleobject; /** * Key abstraction for segregated roles. */ -public abstract class CustomerRole extends CustomerCore{ +public abstract class CustomerRole extends CustomerCore { } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java index 74863ad84..cbc6cc79b 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Role.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -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 Optional instance() { - Class typeCst = this.typeCst; + var typeCst = this.typeCst; try { return (Optional) Optional.of(typeCst.newInstance()); } catch (InstantiationException | IllegalAccessException e) { diff --git a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java index 831781d71..eb8d57f4f 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java @@ -26,8 +26,8 @@ import org.junit.Test; public class ApplicationRoleObjectTest { - @Test - public void mainTest() { - ApplicationRoleObject.main(new String[]{}); - } + @Test + public void mainTest() { + ApplicationRoleObject.main(new String[]{}); + } } \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java index 0c0f92fc2..e04f91acc 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java @@ -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(); - borrowerRole.setName("test"); - String res = "Borrower test wants to get some money."; - - Assert.assertEquals(borrowerRole.borrow(),res); - } + @Test + public void borrowTest() { + var borrowerRole = new BorrowerRole(); + borrowerRole.setName("test"); + Assert.assertEquals(borrowerRole.borrow(), "Borrower test wants to get some money."); + } } \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java index 1b2987400..50c96986a 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java @@ -22,82 +22,72 @@ */ 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); + @Test + public void addRole() { + var core = new CustomerCore(); + assertTrue(core.addRole(Role.Borrower)); + } - } + @Test + public void hasRole() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); + assertTrue(core.hasRole(Role.Borrower)); + assertFalse(core.hasRole(Role.Investor)); + } - @Test - public void hasRole() { - CustomerCore core = new CustomerCore(); - core.addRole(Role.Borrower); + @Test + public void remRole() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); - boolean has = core.hasRole(Role.Borrower); - assertTrue(has); + var bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); - boolean notHas = core.hasRole(Role.Investor); - assertFalse(notHas); - } + assertTrue(core.remRole(Role.Borrower)); - @Test - public void remRole() { - CustomerCore core = new CustomerCore(); - core.addRole(Role.Borrower); + var empt = core.getRole(Role.Borrower, BorrowerRole.class); + assertFalse(empt.isPresent()); + } - Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); - assertTrue(bRole.isPresent()); + @Test + public void getRole() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); - boolean res = core.remRole(Role.Borrower); - assertTrue(res); + var bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); - Optional empt = core.getRole(Role.Borrower, BorrowerRole.class); - assertFalse(empt.isPresent()); + var nonRole = core.getRole(Role.Borrower, InvestorRole.class); + assertFalse(nonRole.isPresent()); - } - - @Test - public void getRole() { - CustomerCore core = new CustomerCore(); - core.addRole(Role.Borrower); - - Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); - assertTrue(bRole.isPresent()); - - Optional nonRole = core.getRole(Role.Borrower, InvestorRole.class); - assertFalse(nonRole.isPresent()); - - Optional invRole = core.getRole(Role.Investor, InvestorRole.class); - assertFalse(invRole.isPresent()); + var invRole = core.getRole(Role.Investor, InvestorRole.class); + assertFalse(invRole.isPresent()); + } - } + @Test + public void toStringTest() { + var core = new CustomerCore(); + core.addRole(Role.Borrower); + assertEquals(core.toString(), "Customer{roles=[Borrower]}"); + + core = new CustomerCore(); + core.addRole(Role.Investor); + assertEquals(core.toString(), "Customer{roles=[Investor]}"); + + core = new CustomerCore(); + assertEquals(core.toString(), "Customer{roles=[]}"); - @Test - public void toStringTest() { - CustomerCore core = new CustomerCore(); - core.addRole(Role.Borrower); - assertEquals(core.toString(), "Customer{roles=[Borrower]}"); - - core = new CustomerCore(); - core.addRole(Role.Investor); - assertEquals(core.toString(), "Customer{roles=[Investor]}"); - - core = new CustomerCore(); - assertEquals(core.toString(), "Customer{roles=[]}"); - - - } + } } \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java index 06afa1016..7f8410cca 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java @@ -27,12 +27,11 @@ import org.junit.Test; public class InvestorRoleTest { - @Test - public void investTest() { - InvestorRole investorRole = new InvestorRole(); - investorRole.setName("test"); - investorRole.setAmountToInvest(10); - String res = "Investor test has invested 10 dollars"; - Assert.assertEquals(investorRole.invest(), res); - } + @Test + public void investTest() { + var investorRole = new InvestorRole(); + investorRole.setName("test"); + investorRole.setAmountToInvest(10); + Assert.assertEquals(investorRole.invest(), "Investor test has invested 10 dollars"); + } } \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java index 6ae5b0cd8..29161de3f 100644 --- a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java +++ b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java @@ -25,16 +25,12 @@ 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 instance = Role.Borrower.instance(); - Assert.assertTrue(instance.isPresent()); - Assert.assertEquals(instance.get().getClass(),BorrowerRole.class); - } + @Test + public void instanceTest() { + var instance = Role.Borrower.instance(); + Assert.assertTrue(instance.isPresent()); + Assert.assertEquals(instance.get().getClass(), BorrowerRole.class); + } } \ No newline at end of file