diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java index 13fe0c3126..7b261b2b8e 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java @@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable { private final BlockingQueue queue; private final int poisonPill; - public NumbersConsumer(BlockingQueue queue, int poisonPill) { + NumbersConsumer(BlockingQueue queue, int poisonPill) { this.queue = queue; this.poisonPill = poisonPill; } diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java index b262097c63..9dcd0a3e47 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java @@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable { private final int poisonPill; private final int poisonPillPerProducer; - public NumbersProducer(BlockingQueue numbersQueue, int poisonPill, int poisonPillPerProducer) { + NumbersProducer(BlockingQueue numbersQueue, int poisonPill, int poisonPillPerProducer) { this.numbersQueue = numbersQueue; this.poisonPill = poisonPill; this.poisonPillPerProducer = poisonPillPerProducer; diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java index 90cd01b69f..d48f317fe7 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java @@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable { private final List outputScraper; private final CountDownLatch countDownLatch; - public BrokenWorker(final List outputScraper, final CountDownLatch countDownLatch) { + BrokenWorker(final List outputScraper, final CountDownLatch countDownLatch) { this.outputScraper = outputScraper; this.countDownLatch = countDownLatch; } diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java index 66be2030e2..4aee5cf89a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java @@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable { private final CountDownLatch callingThreadBlocker; private final CountDownLatch completedThreadCounter; - public WaitingWorker(final List outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) { + WaitingWorker(final List outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) { this.outputScraper = outputScraper; this.readyThreadCounter = readyThreadCounter; diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java index e712fc18d6..389e25719b 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java @@ -7,7 +7,7 @@ public class Worker implements Runnable { private final List outputScraper; private final CountDownLatch countDownLatch; - public Worker(final List outputScraper, final CountDownLatch countDownLatch) { + Worker(final List outputScraper, final CountDownLatch countDownLatch) { this.outputScraper = outputScraper; this.countDownLatch = countDownLatch; } diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java index 69b6d46599..977dae4fdb 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java @@ -7,9 +7,6 @@ import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; -/** - * Created by cv on 24/6/17. - */ public class CyclicBarrierDemo { private CyclicBarrier cyclicBarrier; @@ -19,7 +16,7 @@ public class CyclicBarrierDemo { private int NUM_WORKERS; - public void runSimulation(int numWorkers, int numberOfPartialResults) { + private void runSimulation(int numWorkers, int numberOfPartialResults) { NUM_PARTIAL_RESULTS = numberOfPartialResults; NUM_WORKERS = numWorkers; @@ -49,9 +46,7 @@ public class CyclicBarrierDemo { try { System.out.println(thisThreadName + " waiting for others to reach barrier."); cyclicBarrier.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (BrokenBarrierException e) { + } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java index aa4ca58d6a..5f72758e71 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java +++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java @@ -9,7 +9,7 @@ public class DelayObject implements Delayed { private String data; private long startTime; - public DelayObject(String data, long delayInMilliseconds) { + DelayObject(String data, long delayInMilliseconds) { this.data = data; this.startTime = System.currentTimeMillis() + delayInMilliseconds; } diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java index 8a969bf7aa..d1c1eae9f2 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java +++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java @@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger; public class DelayQueueConsumer implements Runnable { private BlockingQueue queue; private final Integer numberOfElementsToTake; - public final AtomicInteger numberOfConsumedElements = new AtomicInteger(); + final AtomicInteger numberOfConsumedElements = new AtomicInteger(); - public DelayQueueConsumer(BlockingQueue queue, Integer numberOfElementsToTake) { + DelayQueueConsumer(BlockingQueue queue, Integer numberOfElementsToTake) { this.queue = queue; this.numberOfElementsToTake = numberOfElementsToTake; } diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java index 617f19b9ac..f24f4bc385 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java +++ b/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java @@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable { private final Integer numberOfElementsToProduce; private final Integer delayOfEachProducedMessageMilliseconds; - public DelayQueueProducer(BlockingQueue queue, - Integer numberOfElementsToProduce, - Integer delayOfEachProducedMessageMilliseconds) { + DelayQueueProducer(BlockingQueue queue, + Integer numberOfElementsToProduce, + Integer delayOfEachProducedMessageMilliseconds) { this.queue = queue; this.numberOfElementsToProduce = numberOfElementsToProduce; this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds; diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java index 3f1eacd276..c5672706ad 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java +++ b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java @@ -5,7 +5,7 @@ public class Philosopher implements Runnable { private final Object leftFork; private final Object rightFork; - public Philosopher(Object left, Object right) { + Philosopher(Object left, Object right) { this.leftFork = left; this.rightFork = right; } @@ -30,7 +30,6 @@ public class Philosopher implements Runnable { } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return; } } } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java index 471072b333..35bb2aa497 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java @@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask { final private Integer n; - public FactorialSquareCalculator(Integer n) { + FactorialSquareCalculator(Integer n) { this.n = n; } diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java index bcd559dd3b..3329fa599b 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java @@ -3,15 +3,15 @@ package com.baeldung.concurrent.future; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; -public class SquareCalculator { +class SquareCalculator { private final ExecutorService executor; - public SquareCalculator(ExecutorService executor) { + SquareCalculator(ExecutorService executor) { this.executor = executor; } - public Future calculate(Integer input) { + Future calculate(Integer input) { return executor.submit(() -> { Thread.sleep(1000); return input * input; diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java b/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java index 4f061d2efd..f01c675fd2 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java +++ b/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java @@ -13,71 +13,71 @@ import static java.lang.Thread.sleep; public class ReentrantLockWithCondition { - static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class); + private static Logger LOG = LoggerFactory.getLogger(ReentrantLockWithCondition.class); - Stack stack = new Stack<>(); - int CAPACITY = 5; + private Stack stack = new Stack<>(); + private static final int CAPACITY = 5; - ReentrantLock lock = new ReentrantLock(); - Condition stackEmptyCondition = lock.newCondition(); - Condition stackFullCondition = lock.newCondition(); + private ReentrantLock lock = new ReentrantLock(); + private Condition stackEmptyCondition = lock.newCondition(); + private Condition stackFullCondition = lock.newCondition(); - public void pushToStack(String item) throws InterruptedException { - try { - lock.lock(); - if (stack.size() == CAPACITY) { - logger.info(Thread.currentThread().getName() + " wait on stack full"); - stackFullCondition.await(); - } - logger.info("Pushing the item " + item); - stack.push(item); - stackEmptyCondition.signalAll(); - } finally { - lock.unlock(); - } + private void pushToStack(String item) throws InterruptedException { + try { + lock.lock(); + if (stack.size() == CAPACITY) { + LOG.info(Thread.currentThread().getName() + " wait on stack full"); + stackFullCondition.await(); + } + LOG.info("Pushing the item " + item); + stack.push(item); + stackEmptyCondition.signalAll(); + } finally { + lock.unlock(); + } - } + } - public String popFromStack() throws InterruptedException { - try { - lock.lock(); - if (stack.size() == 0) { - logger.info(Thread.currentThread().getName() + " wait on stack empty"); - stackEmptyCondition.await(); - } - return stack.pop(); - } finally { - stackFullCondition.signalAll(); - lock.unlock(); - } - } + private String popFromStack() throws InterruptedException { + try { + lock.lock(); + if (stack.size() == 0) { + LOG.info(Thread.currentThread().getName() + " wait on stack empty"); + stackEmptyCondition.await(); + } + return stack.pop(); + } finally { + stackFullCondition.signalAll(); + lock.unlock(); + } + } - public static void main(String[] args) { - final int threadCount = 2; - ReentrantLockWithCondition object = new ReentrantLockWithCondition(); - final ExecutorService service = Executors.newFixedThreadPool(threadCount); - service.execute(() -> { - for (int i = 0; i < 10; i++) { - try { - object.pushToStack("Item " + i); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + public static void main(String[] args) { + final int threadCount = 2; + ReentrantLockWithCondition object = new ReentrantLockWithCondition(); + final ExecutorService service = Executors.newFixedThreadPool(threadCount); + service.execute(() -> { + for (int i = 0; i < 10; i++) { + try { + object.pushToStack("Item " + i); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } - }); + }); - service.execute(() -> { - for (int i = 0; i < 10; i++) { - try { - logger.info("Item popped " + object.popFromStack()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + service.execute(() -> { + for (int i = 0; i < 10; i++) { + try { + LOG.info("Item popped " + object.popFromStack()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } - }); + }); - service.shutdown(); - } + service.shutdown(); + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java b/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java index b6a4615638..14ae47b2f3 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java +++ b/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java @@ -12,81 +12,77 @@ import static java.lang.Thread.sleep; public class SharedObjectWithLock { - Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class); + private static final Logger LOG = LoggerFactory.getLogger(SharedObjectWithLock.class); - ReentrantLock lock = new ReentrantLock(true); + private ReentrantLock lock = new ReentrantLock(true); - int counter = 0; + private int counter = 0; - public void perform() { + void perform() { - lock.lock(); - logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock"); - try { - logger.info("Thread - " + Thread.currentThread().getName() + " processing"); - counter++; - } catch (Exception exception) { - logger.error(" Interrupted Exception ", exception); - } finally { - lock.unlock(); - logger.info("Thread - " + Thread.currentThread().getName() + " released the lock"); - } - } + lock.lock(); + LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock"); + try { + LOG.info("Thread - " + Thread.currentThread().getName() + " processing"); + counter++; + } catch (Exception exception) { + LOG.error(" Interrupted Exception ", exception); + } finally { + lock.unlock(); + LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock"); + } + } - public void performTryLock() { + private void performTryLock() { - logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock"); - try { - boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS); - if (isLockAcquired) { - try { - logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock"); + LOG.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock"); + try { + boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS); + if (isLockAcquired) { + try { + LOG.info("Thread - " + Thread.currentThread().getName() + " acquired the lock"); - logger.info("Thread - " + Thread.currentThread().getName() + " processing"); - sleep(1000); - } finally { - lock.unlock(); - logger.info("Thread - " + Thread.currentThread().getName() + " released the lock"); + LOG.info("Thread - " + Thread.currentThread().getName() + " processing"); + sleep(1000); + } finally { + lock.unlock(); + LOG.info("Thread - " + Thread.currentThread().getName() + " released the lock"); - } - } - } catch (InterruptedException exception) { - logger.error(" Interrupted Exception ", exception); - } - logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock"); - } + } + } + } catch (InterruptedException exception) { + LOG.error(" Interrupted Exception ", exception); + } + LOG.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock"); + } - public ReentrantLock getLock() { - return lock; - } + public ReentrantLock getLock() { + return lock; + } - boolean isLocked() { - return lock.isLocked(); - } + boolean isLocked() { + return lock.isLocked(); + } - boolean hasQueuedThreads() { - return lock.hasQueuedThreads(); - } + boolean hasQueuedThreads() { + return lock.hasQueuedThreads(); + } - int getCounter() { - return counter; - } + int getCounter() { + return counter; + } - public static void main(String[] args) { + public static void main(String[] args) { - final int threadCount = 2; - final ExecutorService service = Executors.newFixedThreadPool(threadCount); - final SharedObjectWithLock object = new SharedObjectWithLock(); + final int threadCount = 2; + final ExecutorService service = Executors.newFixedThreadPool(threadCount); + final SharedObjectWithLock object = new SharedObjectWithLock(); - service.execute(() -> { - object.perform(); - }); - service.execute(() -> { - object.performTryLock(); - }); + service.execute(object::perform); + service.execute(object::performTryLock); - service.shutdown(); + service.shutdown(); - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java b/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java index 0b0dbc72cb..638bb56b2f 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java @@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock; import static java.lang.Thread.sleep; public class StampedLockDemo { - Map map = new HashMap<>(); - Logger logger = LoggerFactory.getLogger(StampedLockDemo.class); + private Map map = new HashMap<>(); + private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class); - private final StampedLock lock = new StampedLock(); + private final StampedLock lock = new StampedLock(); - public void put(String key, String value) throws InterruptedException { - long stamp = lock.writeLock(); + public void put(String key, String value) throws InterruptedException { + long stamp = lock.writeLock(); - try { - logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp); - map.put(key, value); - } finally { - lock.unlockWrite(stamp); - logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp); - } - } + try { + logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp); + map.put(key, value); + } finally { + lock.unlockWrite(stamp); + logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp); + } + } - public String get(String key) throws InterruptedException { - long stamp = lock.readLock(); - logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp); - try { - sleep(5000); - return map.get(key); + public String get(String key) throws InterruptedException { + long stamp = lock.readLock(); + logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp); + try { + sleep(5000); + return map.get(key); - } finally { - lock.unlockRead(stamp); - logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); + } finally { + lock.unlockRead(stamp); + logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); - } + } - } + } - public String readWithOptimisticLock(String key) throws InterruptedException { - long stamp = lock.tryOptimisticRead(); - String value = map.get(key); + private String readWithOptimisticLock(String key) throws InterruptedException { + long stamp = lock.tryOptimisticRead(); + String value = map.get(key); - if (!lock.validate(stamp)) { - stamp = lock.readLock(); - try { - sleep(5000); - return map.get(key); + if (!lock.validate(stamp)) { + stamp = lock.readLock(); + try { + sleep(5000); + return map.get(key); - } finally { - lock.unlock(stamp); - logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); + } finally { + lock.unlock(stamp); + logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); - } - } - return value; - } + } + } + return value; + } - public static void main(String[] args) { - final int threadCount = 4; - final ExecutorService service = Executors.newFixedThreadPool(threadCount); - StampedLockDemo object = new StampedLockDemo(); + public static void main(String[] args) { + final int threadCount = 4; + final ExecutorService service = Executors.newFixedThreadPool(threadCount); + StampedLockDemo object = new StampedLockDemo(); - Runnable writeTask = () -> { + Runnable writeTask = () -> { - try { - object.put("key1", "value1"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }; - Runnable readTask = () -> { + try { + object.put("key1", "value1"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }; + Runnable readTask = () -> { - try { - object.get("key1"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }; - Runnable readOptimisticTask = () -> { + try { + object.get("key1"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }; + Runnable readOptimisticTask = () -> { - try { - object.readWithOptimisticLock("key1"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }; - service.submit(writeTask); - service.submit(writeTask); - service.submit(readTask); - service.submit(readOptimisticTask); + try { + object.readWithOptimisticLock("key1"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }; + service.submit(writeTask); + service.submit(writeTask); + service.submit(readTask); + service.submit(readOptimisticTask); - service.shutdown(); + service.shutdown(); - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java b/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java index 83b8b34fe9..eeb7aa4b13 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java +++ b/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java @@ -15,106 +15,106 @@ import static java.lang.Thread.sleep; public class SynchronizedHashMapWithRWLock { - static Map syncHashMap = new HashMap<>(); - Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class); + private static Map syncHashMap = new HashMap<>(); + private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class); - private final ReadWriteLock lock = new ReentrantReadWriteLock(); - private final Lock readLock = lock.readLock(); - private final Lock writeLock = lock.writeLock(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final Lock readLock = lock.readLock(); + private final Lock writeLock = lock.writeLock(); - public void put(String key, String value) throws InterruptedException { + public void put(String key, String value) throws InterruptedException { - try { - writeLock.lock(); - logger.info(Thread.currentThread().getName() + " writing"); - syncHashMap.put(key, value); - sleep(1000); - } finally { - writeLock.unlock(); - } + try { + writeLock.lock(); + logger.info(Thread.currentThread().getName() + " writing"); + syncHashMap.put(key, value); + sleep(1000); + } finally { + writeLock.unlock(); + } - } + } - public String get(String key) { - try { - readLock.lock(); - logger.info(Thread.currentThread().getName() + " reading"); - return syncHashMap.get(key); - } finally { - readLock.unlock(); - } - } + public String get(String key) { + try { + readLock.lock(); + logger.info(Thread.currentThread().getName() + " reading"); + return syncHashMap.get(key); + } finally { + readLock.unlock(); + } + } - public String remove(String key) { - try { - writeLock.lock(); - return syncHashMap.remove(key); - } finally { - writeLock.unlock(); - } - } + public String remove(String key) { + try { + writeLock.lock(); + return syncHashMap.remove(key); + } finally { + writeLock.unlock(); + } + } - public boolean containsKey(String key) { - try { - readLock.lock(); - return syncHashMap.containsKey(key); - } finally { - readLock.unlock(); - } - } + public boolean containsKey(String key) { + try { + readLock.lock(); + return syncHashMap.containsKey(key); + } finally { + readLock.unlock(); + } + } - boolean isReadLockAvailable() { - return readLock.tryLock(); - } + boolean isReadLockAvailable() { + return readLock.tryLock(); + } - public static void main(String[] args) throws InterruptedException { + public static void main(String[] args) throws InterruptedException { - final int threadCount = 3; - final ExecutorService service = Executors.newFixedThreadPool(threadCount); - SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock(); + final int threadCount = 3; + final ExecutorService service = Executors.newFixedThreadPool(threadCount); + SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock(); - service.execute(new Thread(new Writer(object), "Writer")); - service.execute(new Thread(new Reader(object), "Reader1")); - service.execute(new Thread(new Reader(object), "Reader2")); + service.execute(new Thread(new Writer(object), "Writer")); + service.execute(new Thread(new Reader(object), "Reader1")); + service.execute(new Thread(new Reader(object), "Reader2")); - service.shutdown(); - } + service.shutdown(); + } - private static class Reader implements Runnable { + private static class Reader implements Runnable { - SynchronizedHashMapWithRWLock object; + SynchronizedHashMapWithRWLock object; - public Reader(SynchronizedHashMapWithRWLock object) { - this.object = object; - } + Reader(SynchronizedHashMapWithRWLock object) { + this.object = object; + } - @Override - public void run() { - for (int i = 0; i < 10; i++) { - object.get("key" + i); - } - } - } + @Override + public void run() { + for (int i = 0; i < 10; i++) { + object.get("key" + i); + } + } + } - private static class Writer implements Runnable { + private static class Writer implements Runnable { - SynchronizedHashMapWithRWLock object; + SynchronizedHashMapWithRWLock object; - public Writer(SynchronizedHashMapWithRWLock object) { - this.object = object; - } + public Writer(SynchronizedHashMapWithRWLock object) { + this.object = object; + } - @Override - public void run() { - for (int i = 0; i < 10; i++) { - try { - object.put("key" + i, "value" + i); - sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } + @Override + public void run() { + for (int i = 0; i < 10; i++) { + try { + object.put("key" + i, "value" + i); + sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java index ce1f57bb93..d5ff5f7842 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java +++ b/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java @@ -2,20 +2,20 @@ package com.baeldung.concurrent.skiplist; import java.time.ZonedDateTime; -public class Event { +class Event { private final ZonedDateTime eventTime; private final String content; - public Event(ZonedDateTime eventTime, String content) { + Event(ZonedDateTime eventTime, String content) { this.eventTime = eventTime; this.content = content; } - public ZonedDateTime getEventTime() { + ZonedDateTime getEventTime() { return eventTime; } - public String getContent() { + String getContent() { return content; } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java index 3aca6b0147..2e501ed368 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java +++ b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java @@ -5,24 +5,24 @@ import java.util.Comparator; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; -public class EventWindowSort { +class EventWindowSort { private final ConcurrentSkipListMap events - = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli())); + = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli())); - public void acceptEvent(Event event) { + void acceptEvent(Event event) { events.put(event.getEventTime(), event.getContent()); } - public ConcurrentNavigableMap getEventsFromLastMinute() { + ConcurrentNavigableMap getEventsFromLastMinute() { return events.tailMap(ZonedDateTime - .now() - .minusMinutes(1)); + .now() + .minusMinutes(1)); } - public ConcurrentNavigableMap getEventsOlderThatOneMinute() { + ConcurrentNavigableMap getEventsOlderThatOneMinute() { return events.headMap(ZonedDateTime - .now() - .minusMinutes(1)); + .now() + .minusMinutes(1)); } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java index 0311d9b0b2..90bc4dceed 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java @@ -13,10 +13,10 @@ public class WaitSleepExample { private static final Object LOCK = new Object(); public static void main(String... args) throws InterruptedException { - sleepWaitInSyncronizedBlocks(); + sleepWaitInSynchronizedBlocks(); } - private static void sleepWaitInSyncronizedBlocks() throws InterruptedException { + private static void sleepWaitInSynchronizedBlocks() throws InterruptedException { Thread.sleep(1000); // called on the thread LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); @@ -25,5 +25,5 @@ public class WaitSleepExample { LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second"); } } - + } diff --git a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java index d66cd0d796..332a6d9263 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java +++ b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java @@ -5,13 +5,13 @@ public class BaeldungSynchronizedBlocks { private int count = 0; private static int staticCount = 0; - public void performSynchronisedTask() { + void performSynchronisedTask() { synchronized (this) { setCount(getCount() + 1); } } - public static void performStaticSyncTask() { + static void performStaticSyncTask() { synchronized (BaeldungSynchronizedBlocks.class) { setStaticCount(getStaticCount() + 1); } @@ -25,11 +25,11 @@ public class BaeldungSynchronizedBlocks { this.count = count; } - public static int getStaticCount() { + static int getStaticCount() { return staticCount; } - public static void setStaticCount(int staticCount) { + private static void setStaticCount(int staticCount) { BaeldungSynchronizedBlocks.staticCount = staticCount; } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java index 1295140b7c..179c6fb9ef 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java +++ b/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java @@ -5,17 +5,17 @@ public class BaeldungSynchronizedMethods { private int sum = 0; private int syncSum = 0; - public static int staticSum = 0; + static int staticSum = 0; - public void calculate() { + void calculate() { setSum(getSum() + 1); } - public synchronized void synchronisedCalculate() { + synchronized void synchronisedCalculate() { setSyncSum(getSyncSum() + 1); } - public static synchronized void syncStaticCalculate() { + static synchronized void syncStaticCalculate() { staticSum = staticSum + 1; } @@ -27,11 +27,11 @@ public class BaeldungSynchronizedMethods { this.sum = sum; } - public int getSyncSum() { + int getSyncSum() { return syncSum; } - public void setSyncSum(int syncSum) { + private void setSyncSum(int syncSum) { this.syncSum = syncSum; } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java index 82f5745b3c..0d727cf0b5 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -6,40 +6,40 @@ import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; -public class UseLocalDate { +class UseLocalDate { - public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { + LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { return LocalDate.of(year, month, dayOfMonth); } - public LocalDate getLocalDateUsingParseMethod(String representation) { + LocalDate getLocalDateUsingParseMethod(String representation) { return LocalDate.parse(representation); } - public LocalDate getLocalDateFromClock() { + LocalDate getLocalDateFromClock() { LocalDate localDate = LocalDate.now(); return localDate; } - public LocalDate getNextDay(LocalDate localDate) { + LocalDate getNextDay(LocalDate localDate) { return localDate.plusDays(1); } - public LocalDate getPreviousDay(LocalDate localDate) { + LocalDate getPreviousDay(LocalDate localDate) { return localDate.minus(1, ChronoUnit.DAYS); } - public DayOfWeek getDayOfWeek(LocalDate localDate) { + DayOfWeek getDayOfWeek(LocalDate localDate) { DayOfWeek day = localDate.getDayOfWeek(); return day; } - public LocalDate getFirstDayOfMonth() { + LocalDate getFirstDayOfMonth() { LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); return firstDayOfMonth; } - public LocalDateTime getStartOfDay(LocalDate localDate) { + LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java index 9bd8f9706c..8d166c413f 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java @@ -5,31 +5,27 @@ import java.time.temporal.ChronoUnit; public class UseLocalTime { - public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { - LocalTime localTime = LocalTime.of(hour, min, seconds); - return localTime; + LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { + return LocalTime.of(hour, min, seconds); } - public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { - LocalTime localTime = LocalTime.parse(timeRepresentation); - return localTime; + LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { + return LocalTime.parse(timeRepresentation); } - public LocalTime getLocalTimeFromClock() { - LocalTime localTime = LocalTime.now(); - return localTime; + private LocalTime getLocalTimeFromClock() { + return LocalTime.now(); } - public LocalTime addAnHour(LocalTime localTime) { - LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS); - return newTime; + LocalTime addAnHour(LocalTime localTime) { + return localTime.plus(1, ChronoUnit.HOURS); } - public int getHourFromLocalTime(LocalTime localTime) { + int getHourFromLocalTime(LocalTime localTime) { return localTime.getHour(); } - public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { + LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { return localTime.withMinute(minute); } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java index 5a42ef83b4..10bc6caec3 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java +++ b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java @@ -3,13 +3,13 @@ package com.baeldung.datetime; import java.time.LocalDate; import java.time.Period; -public class UsePeriod { +class UsePeriod { - public LocalDate modifyDates(LocalDate localDate, Period period) { + LocalDate modifyDates(LocalDate localDate, Period period) { return localDate.plus(period); } - public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) { + Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) { return Period.between(localDate1, localDate2); } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java index 94154ce5c0..1fa413bbf2 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java @@ -8,12 +8,10 @@ import java.util.Date; public class UseToInstant { public LocalDateTime convertDateToLocalDate(Date date) { - LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); - return localDateTime; + return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } public LocalDateTime convertDateToLocalDate(Calendar calendar) { - LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); - return localDateTime; + return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); } } diff --git a/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java index 2d1b17484b..f5e1af0a06 100644 --- a/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -4,10 +4,9 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; -public class UseZonedDateTime { +class UseZonedDateTime { - public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { - ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId); - return zonedDateTime; + ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { + return ZonedDateTime.of(localDateTime, zoneId); } } diff --git a/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java b/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java index f9028bd159..bdc732947f 100644 --- a/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java +++ b/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java @@ -13,8 +13,7 @@ public class DirectoryMonitoringExample { private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class); - - public static final int POLL_INTERVAL = 500; + private static final int POLL_INTERVAL = 500; public static void main(String[] args) throws Exception { FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home")); diff --git a/core-java/src/main/java/com/baeldung/doublecolon/Computer.java b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java index b5d2e70abd..dc0b064013 100644 --- a/core-java/src/main/java/com/baeldung/doublecolon/Computer.java +++ b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java @@ -6,12 +6,12 @@ public class Computer { private String color; private Integer healty; - public Computer(final int age, final String color) { + Computer(final int age, final String color) { this.age = age; this.color = color; } - public Computer(final Integer age, final String color, final Integer healty) { + Computer(final Integer age, final String color, final Integer healty) { this.age = age; this.color = color; this.healty = healty; @@ -28,7 +28,7 @@ public class Computer { this.age = age; } - public String getColor() { + String getColor() { return color; } @@ -36,11 +36,11 @@ public class Computer { this.color = color; } - public Integer getHealty() { + Integer getHealty() { return healty; } - public void setHealty(final Integer healty) { + void setHealty(final Integer healty) { this.healty = healty; } @@ -72,10 +72,7 @@ public class Computer { final Computer computer = (Computer) o; - if (age != null ? !age.equals(computer.age) : computer.age != null) { - return false; - } - return color != null ? color.equals(computer.color) : computer.color == null; + return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null); } diff --git a/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java index d181dfcdf7..317808d893 100644 --- a/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java +++ b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java @@ -7,8 +7,8 @@ import java.util.List; public class ComputerUtils { - public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010); - public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor()); + static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010); + static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor()); public static List filter(final List inventory, final ComputerPredicate p) { @@ -18,7 +18,7 @@ public class ComputerUtils { return result; } - public static void repair(final Computer computer) { + static void repair(final Computer computer) { if (computer.getHealty() < 50) { computer.setHealty(100); } diff --git a/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java index f5c31e9653..79c8d9e383 100644 --- a/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java +++ b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java @@ -13,7 +13,7 @@ public class MacbookPro extends Computer { super(age, color); } - public MacbookPro(Integer age, String color, Integer healty) { + MacbookPro(Integer age, String color, Integer healty) { super(age, color, healty); } diff --git a/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java b/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java index 942efc50cc..c35b69d075 100644 --- a/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java +++ b/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java @@ -15,7 +15,7 @@ public class TimingDynamicInvocationHandler implements InvocationHandler { private Object target; - public TimingDynamicInvocationHandler(Object target) { + TimingDynamicInvocationHandler(Object target) { this.target = target; for(Method method: target.getClass().getDeclaredMethods()) { diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java index b9125c3e2f..66de220057 100644 --- a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java @@ -1,10 +1,10 @@ package com.baeldung.equalshashcode.entities; -import java.awt.Color; +import java.awt.*; public class Square extends Rectangle { - Color color; + private Color color; public Square(double width, Color color) { super(width, width); diff --git a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java index d8d35d5363..4afce56e39 100644 --- a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java +++ b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java @@ -8,7 +8,7 @@ import javax.naming.InitialContext; import javax.naming.NamingException; public class LookupFSJNDI { - InitialContext ctx = null; + private InitialContext ctx = null; public LookupFSJNDI() throws NamingException { super(); diff --git a/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java b/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java new file mode 100644 index 0000000000..1472dd7d6d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/maths/BigDecimalImpl.java @@ -0,0 +1,18 @@ +package com.baeldung.maths; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class BigDecimalImpl { + + public static void main(String[] args) { + + BigDecimal serviceTax = new BigDecimal("56.0084578639"); + serviceTax = serviceTax.setScale(2, RoundingMode.CEILING); + + BigDecimal entertainmentTax = new BigDecimal("23.00689"); + entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR); + + BigDecimal totalTax = serviceTax.add(entertainmentTax); + } +} diff --git a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java new file mode 100644 index 0000000000..dc509429f9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java @@ -0,0 +1,16 @@ +package com.baeldung.maths; + +import java.math.BigInteger; + +public class BigIntegerImpl { + + public static void main(String[] args) { + + BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); + BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); + + BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); + + } + +} diff --git a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java new file mode 100644 index 0000000000..973b987224 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java @@ -0,0 +1,24 @@ +package com.baeldung.maths; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import org.junit.Assert; +import org.junit.Test; + +public class BigDecimalImplTest { + + @Test + public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { + BigDecimal serviceTax = new BigDecimal("56.0084578639"); + serviceTax = serviceTax.setScale(2, RoundingMode.CEILING); + + BigDecimal entertainmentTax = new BigDecimal("23.00689"); + entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR); + + BigDecimal totalTax = serviceTax.add(entertainmentTax); + BigDecimal result = BigDecimal.valueOf(79.01); + + Assert.assertEquals(result, totalTax); + + } +} diff --git a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java new file mode 100644 index 0000000000..040c595065 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java @@ -0,0 +1,22 @@ +package com.baeldung.maths; + +import java.math.BigInteger; + +import org.junit.Assert; + +import org.junit.Test; + +public class BigIntegerImplTest { + + @Test + public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() { + BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); + BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); + + BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); + BigInteger result = new BigInteger("14110718640342675608722521633212952"); + + Assert.assertEquals(result, totalStars); + } + +} diff --git a/guest/memory-leaks/src/test/java/com/baeldung/MemoryLeaksTest.java b/guest/memory-leaks/src/test/java/com/baeldung/MemoryLeaksTest.java index 13052a9487..a8a094b4db 100644 --- a/guest/memory-leaks/src/test/java/com/baeldung/MemoryLeaksTest.java +++ b/guest/memory-leaks/src/test/java/com/baeldung/MemoryLeaksTest.java @@ -26,36 +26,48 @@ //@FixMethodOrder(MethodSorters.NAME_ASCENDING) //@RunWith(JUnit4.class) //public class MemoryLeaksTest { - // private Random random = new Random(); // public static final ArrayList list = new ArrayList(1000000); // -// @Test(expected = OutOfMemoryError.class) +// @Test // public void givenStaticField_whenLotsOfOperations_thenMemoryLeak() throws InterruptedException { -// while (true) { -// int k = random.nextInt(100000); -// System.out.println(k); -// Thread.sleep(10000); //to allow GC do its job -// for (int i = 0; i < k; i++) { -// list.add(random.nextDouble()); -// } +// for (int i = 0; i < 1000000; i++) { +// list.add(random.nextDouble()); // } +// System.gc(); +// Thread.sleep(10000); //to allow GC do its job +// } // +// +// @Test +// public void givenNormalField_whenLotsOfOperations_thenGCWorksFine() throws InterruptedException { +// addElementsToTheList(); +// System.gc(); +// Thread.sleep(10000); //to allow GC do its job +// } +// +// private void addElementsToTheList(){ +// ArrayList list = new ArrayList(1000000); +// for (int i = 0; i < 1000000; i++) { +// list.add(random.nextDouble()); +// } // } // // @SuppressWarnings({ "resource" }) // @Test(expected = OutOfMemoryError.class) -// public void givenLengthString_whenIntern_thenOutOfMemory() throws IOException { +// public void givenLengthString_whenIntern_thenOutOfMemory() throws IOException, InterruptedException { +// Thread.sleep(15000); // String str = new Scanner(new File("src/test/resources/large.txt"), "UTF-8").useDelimiter("\\A") // .next(); +// System.gc(); // str.intern(); -// System.out.println("Done"); +// Thread.sleep(10000); // } - +// // @Test(expected = OutOfMemoryError.class) // public void givenURL_whenUnclosedStream_thenOutOfMemory() throws IOException, URISyntaxException { // String str = ""; -// URLConnection conn = new URL("http://norvig.com/big.txt").openConnection(); +// URLConnection conn = new URL("http:norvig.com/big.txt").openConnection(); // BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); // while (br.readLine() != null) { // str += br.readLine(); @@ -66,7 +78,7 @@ // @SuppressWarnings("unused") // @Test(expected = OutOfMemoryError.class) // public void givenConnection_whenUnclosed_thenOutOfMemory() throws IOException, URISyntaxException { -// URL url = new URL("ftp://speedtest.tele2.net"); +// URL url = new URL("ftp:speedtest.tele2.net"); // URLConnection urlc = url.openConnection(); // InputStream is = urlc.getInputStream(); // String str = ""; diff --git a/jee7/pom.xml b/jee7/pom.xml index e633d2df3d..b5e0d80b6c 100644 --- a/jee7/pom.xml +++ b/jee7/pom.xml @@ -31,6 +31,7 @@ 1.0.0.Final 2.6 + 4.2.3.RELEASE @@ -136,6 +137,34 @@ standard 1.1.2 + + + javax.mvc + javax.mvc-api + 20160715 + + + org.glassfish.ozark + ozark + 20160715 + + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + @@ -378,4 +407,18 @@ + + + + bintray-mvc-spec-maven + bintray + http://dl.bintray.com/mvc-spec/maven + + true + + + false + + + diff --git a/jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java b/jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java new file mode 100755 index 0000000000..f8e7982253 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.springSecurity; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +/** + * Application class required by JAX-RS. If you don't want to have any + * prefix in the URL, you can set the application path to "/". + */ +@ApplicationPath("/") +public class ApplicationConfig extends Application { + +} diff --git a/jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java b/jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java new file mode 100644 index 0000000000..e6a05f7b71 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java @@ -0,0 +1,10 @@ +package com.baeldung.springSecurity; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { + + public SecurityWebApplicationInitializer() { + super(SpringSecurityConfig.class); + } +} diff --git a/jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java b/jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java new file mode 100644 index 0000000000..bda8930f36 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java @@ -0,0 +1,46 @@ +package com.baeldung.springSecurity; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("user1") + .password("user1Pass") + .roles("USER") + .and() + .withUser("admin") + .password("adminPass") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf() + .disable() + .authorizeRequests() + .antMatchers("/auth/login*") + .anonymous() + .antMatchers("/home/admin*") + .hasRole("ADMIN") + .anyRequest() + .authenticated() + .and() + .formLogin() + .loginPage("/auth/login") + .defaultSuccessUrl("/home", true) + .failureUrl("/auth/login?error=true") + .and() + .logout() + .logoutSuccessUrl("/auth/login"); + } +} \ No newline at end of file diff --git a/jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java b/jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java new file mode 100644 index 0000000000..53fd9f4b81 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java @@ -0,0 +1,28 @@ +package com.baeldung.springSecurity.controller; + +import javax.mvc.annotation.Controller; +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/home") +@Controller +public class HomeController { + + @GET + public String home() { + return "home.jsp"; + } + + @GET + @Path("/user") + public String admin() { + return "user.jsp"; + } + + @GET + @Path("/admin") + public String user() { + return "admin.jsp"; + } + +} diff --git a/jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java b/jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java new file mode 100644 index 0000000000..a7e7bb471d --- /dev/null +++ b/jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java @@ -0,0 +1,15 @@ +package com.baeldung.springSecurity.controller; + +import javax.mvc.annotation.Controller; +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/auth/login") +@Controller +public class LoginController { + + @GET + public String login() { + return "login.jsp"; + } +} diff --git a/jee7/src/main/webapp/WEB-INF/views/admin.jsp b/jee7/src/main/webapp/WEB-INF/views/admin.jsp new file mode 100644 index 0000000000..b83ea09f5b --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/views/admin.jsp @@ -0,0 +1,12 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

Welcome to the ADMIN page

+ + ">Logout + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/views/home.jsp b/jee7/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..c6e129c9ce --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,26 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

This is the body of the sample view

+ + + This text is only visible to a user +

+ ">Restricted Admin Page +

+
+ + + This text is only visible to an admin +
+ ">Admin Page +
+
+ + ">Logout + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/views/login.jsp b/jee7/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..d6f2e56f3a --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,26 @@ + + + + +

Login

+ +
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/views/user.jsp b/jee7/src/main/webapp/WEB-INF/views/user.jsp new file mode 100644 index 0000000000..11b8155da7 --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/views/user.jsp @@ -0,0 +1,12 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

Welcome to the Restricted Admin page

+ + ">Logout + + + \ No newline at end of file diff --git a/kotlin-mockito/README.md b/kotlin-mockito/README.md deleted file mode 100644 index 1408bc1ebd..0000000000 --- a/kotlin-mockito/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Relevant articles: - -- [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin) -- [A guide to the “when{}” block in Kotlin](http://www.baeldung.com/kotlin-when) -- [Comprehensive Guide to Null Safety in Kotlin](http://www.baeldung.com/kotlin-null-safety) -- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) -- [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators) -- [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) diff --git a/kotlin-mockito/pom.xml b/kotlin-mockito/pom.xml deleted file mode 100644 index abb43f4109..0000000000 --- a/kotlin-mockito/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - 4.0.0 - - kotlin-mockito - 1.0-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib - ${kotlin.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - junit - junit - ${junit.version} - test - - - com.nhaarman - mockito-kotlin - ${mockito-kotlin.version} - test - - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/test/kotlin - - - - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin.version} - - - compile - - compile - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/main/java - - - - - test-compile - - test-compile - - - - ${project.basedir}/src/test/kotlin - ${project.basedir}/src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler.version} - - - - default-compile - none - - - - default-testCompile - none - - - java-compile - compile - - compile - - - - java-test-compile - test-compile - - testCompile - - - - - - - - - 2.8.9 - 4.12 - 1.1.2-4 - 1.5.0 - 3.5.1 - - - diff --git a/kotlin-mockito/src/main/java/com/baeldung/java/ArrayExample.java b/kotlin-mockito/src/main/java/com/baeldung/java/ArrayExample.java deleted file mode 100644 index ef91db517b..0000000000 --- a/kotlin-mockito/src/main/java/com/baeldung/java/ArrayExample.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.java; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -public class ArrayExample { - - public int sumValues(int[] nums) { - int res = 0; - - for (int x:nums) { - res += x; - } - - return res; - } - - public void writeList() throws IOException { - File file = new File("E://file.txt"); - FileReader fr = new FileReader(file); - fr.close(); - } -} diff --git a/kotlin-mockito/src/main/java/com/baeldung/java/Customer.java b/kotlin-mockito/src/main/java/com/baeldung/java/Customer.java deleted file mode 100644 index 0156bf7b44..0000000000 --- a/kotlin-mockito/src/main/java/com/baeldung/java/Customer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.java; - -public class Customer { - - private String firstName; - private String lastName; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - -} diff --git a/kotlin-mockito/src/main/java/com/baeldung/java/StringUtils.java b/kotlin-mockito/src/main/java/com/baeldung/java/StringUtils.java deleted file mode 100644 index f405924cdf..0000000000 --- a/kotlin-mockito/src/main/java/com/baeldung/java/StringUtils.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.java; - -public class StringUtils { - public static String toUpperCase(String name) { - return name.toUpperCase(); - } -} diff --git a/kotlin-mockito/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java b/kotlin-mockito/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java deleted file mode 100644 index 370f24785a..0000000000 --- a/kotlin-mockito/src/test/java/com/baeldung/kotlin/JavaCallToKotlinUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.kotlin; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class JavaCallToKotlinUnitTest { - @Test - public void givenKotlinClass_whenCallFromJava_shouldProduceResults() { - //when - int res = new MathematicsOperations().addTwoNumbers(2, 4); - - //then - assertEquals(6, res); - - } -} diff --git a/kotlin/pom.xml b/kotlin/pom.xml index bcf5b36385..e88013ab69 100644 --- a/kotlin/pom.xml +++ b/kotlin/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung kotlin 1.0-SNAPSHOT @@ -13,7 +12,6 @@ 1.0.0-SNAPSHOT - central @@ -21,7 +19,6 @@ - org.jetbrains.kotlin @@ -45,9 +42,14 @@ kotlinx-coroutines-core ${kotlinx.version} + + com.nhaarman + mockito-kotlin + ${mockito-kotlin.version} + test + - @@ -123,6 +125,7 @@ 1.1.2 1.1.2 0.15 + 1.5.0 \ No newline at end of file diff --git a/kotlin-mockito/src/main/kotlin/com/baeldung/kotlin/BookService.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt similarity index 100% rename from kotlin-mockito/src/main/kotlin/com/baeldung/kotlin/BookService.kt rename to kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt diff --git a/kotlin-mockito/src/main/kotlin/com/baeldung/kotlin/LendBookManager.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt similarity index 100% rename from kotlin-mockito/src/main/kotlin/com/baeldung/kotlin/LendBookManager.kt rename to kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt diff --git a/kotlin-mockito/src/test/kotlin/com/baeldung/kotlin/LendBookManagerTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt similarity index 100% rename from kotlin-mockito/src/test/kotlin/com/baeldung/kotlin/LendBookManagerTest.kt rename to kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt diff --git a/kotlin-mockito/src/test/kotlin/com/baeldung/kotlin/LendBookManagerTestMockitoKotlin.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt similarity index 100% rename from kotlin-mockito/src/test/kotlin/com/baeldung/kotlin/LendBookManagerTestMockitoKotlin.kt rename to kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt diff --git a/libraries/pom.xml b/libraries/pom.xml index 23fec48075..ee5fb2f977 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -90,6 +90,11 @@ commons-lang3 ${commons-lang.version} + + org.apache.commons + commons-text + ${commons-text.version} + org.apache.commons commons-collections4 @@ -366,6 +371,7 @@ 0.7.0 3.2.4 3.5 + 1.1 1.9.3 1.9.2 1.2 diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java new file mode 100644 index 0000000000..4a0b59404d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java @@ -0,0 +1,35 @@ +package com.baeldung.commons.beanutils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CourseEntity { + private String name; + private List codes; + private Map students = new HashMap(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCodes() { + return codes; + } + + public void setCodes(List codes) { + this.codes = codes; + } + + public void setStudent(String id, Student student) { + students.put(id, student); + } + + public Student getStudent(String enrolledId) { + return students.get(enrolledId); + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java index f519365dab..1f566a782a 100644 --- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java +++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java @@ -3,32 +3,38 @@ package com.baeldung.commons.beanutils; import java.lang.reflect.InvocationTargetException; import java.util.List; +import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; public class CourseService { public static void setValues(Course course, String name, List codes) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the simple properties PropertyUtils.setSimpleProperty(course, "name", name); PropertyUtils.setSimpleProperty(course, "codes", codes); } public static void setIndexedValue(Course course, int codeIndex, String code) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the indexed properties PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code); } public static void setMappedValue(Course course, String enrollId, Student student) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the mapped properties PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student); } public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (String) PropertyUtils.getNestedProperty( course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName); } + + public static void copyProperties(Course course, CourseEntity courseEntity) + throws IllegalAccessException, InvocationTargetException { + BeanUtils.copyProperties(course, courseEntity); + } } diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java index d2ae6d7d55..5407477a00 100644 --- a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java +++ b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java @@ -8,31 +8,46 @@ import org.junit.Assert; import org.junit.Test; public class CourseServiceTest { - + @Test public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Course course = new Course(); String name = "Computer Science"; List codes = Arrays.asList("CS", "CS01"); CourseService.setValues(course, name, codes); - + Assert.assertEquals(name, course.getName()); Assert.assertEquals(2, course.getCodes().size()); Assert.assertEquals("CS", course.getCodes().get(0)); - + CourseService.setIndexedValue(course, 1, "CS02"); Assert.assertEquals("CS02", course.getCodes().get(1)); - + Student student = new Student(); String studentName = "Joe"; student.setName(studentName); - + CourseService.setMappedValue(course, "ST-1", student); Assert.assertEquals(student, course.getEnrolledStudent("ST-1")); - + String accessedStudentName = CourseService.getNestedValue(course, "ST-1", "name"); Assert.assertEquals(studentName, accessedStudentName); } + @Test + public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + Course course = new Course(); + course.setName("Computer Science"); + course.setCodes(Arrays.asList("CS")); + course.setEnrolledStudent("ST-1", new Student()); + + CourseEntity courseEntity = new CourseEntity(); + + CourseService.copyProperties(course, courseEntity); + Assert.assertEquals(course.getName(), courseEntity.getName()); + Assert.assertEquals(course.getCodes(), courseEntity.getCodes()); + Assert.assertNull(courseEntity.getStudent("ST-1")); + } } diff --git a/libraries/src/test/java/com/baeldung/text/DiffTest.java b/libraries/src/test/java/com/baeldung/text/DiffTest.java new file mode 100644 index 0000000000..95370013b6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/DiffTest.java @@ -0,0 +1,18 @@ +package com.baeldung.text; + +import org.apache.commons.text.diff.EditScript; +import org.apache.commons.text.diff.StringsComparator; +import org.junit.Assert; +import org.junit.Test; + +public class DiffTest { + + @Test + public void whenEditScript_thenCorrect() { + StringsComparator cmp = new StringsComparator("ABCFGH", "BCDEFG"); + EditScript script = cmp.getScript(); + int mod = script.getModifications(); + + Assert.assertEquals(4, mod); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java new file mode 100644 index 0000000000..80ca0cfbba --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java @@ -0,0 +1,25 @@ +package com.baeldung.text; + +import org.apache.commons.text.similarity.LongestCommonSubsequence; +import org.apache.commons.text.similarity.LongestCommonSubsequenceDistance; +import org.junit.Assert; +import org.junit.Test; + +public class LongestCommonSubsequenceTest { + + @Test + public void whenCompare_thenCorrect() { + LongestCommonSubsequence lcs = new LongestCommonSubsequence(); + int countLcs = lcs.apply("New York", "New Hampshire"); + + Assert.assertEquals(5, countLcs); + } + + @Test + public void whenCalculateDistance_thenCorrect() { + LongestCommonSubsequenceDistance lcsd = new LongestCommonSubsequenceDistance(); + int countLcsd = lcsd.apply("New York", "New Hampshire"); + + Assert.assertEquals(11, countLcsd); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java new file mode 100644 index 0000000000..a8dbaadc5a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java @@ -0,0 +1,24 @@ +package com.baeldung.text; + +import org.apache.commons.text.StrBuilder; +import org.junit.Assert; +import org.junit.Test; + +public class StrBuilderTest { + + @Test + public void whenReplaced_thenCorrect() { + StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); + strBuilder.replaceAll("example", "new"); + + Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); + } + + @Test + public void whenCleared_thenEmpty() { + StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); + strBuilder.clear(); + + Assert.assertEquals(new StrBuilder(""), strBuilder); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/StrSubstitutorTest.java b/libraries/src/test/java/com/baeldung/text/StrSubstitutorTest.java new file mode 100644 index 0000000000..24e6ff59c8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/StrSubstitutorTest.java @@ -0,0 +1,23 @@ +package com.baeldung.text; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.text.StrSubstitutor; +import org.junit.Assert; +import org.junit.Test; + +public class StrSubstitutorTest { + + @Test + public void whenSubstituted_thenCorrect() { + Map substitutes = new HashMap<>(); + substitutes.put("name", "John"); + substitutes.put("college", "University of Stanford"); + String templateString = "My name is ${name} and I am a student at the ${college}."; + StrSubstitutor sub = new StrSubstitutor(substitutes); + String result = sub.replace(templateString); + + Assert.assertEquals("My name is John and I am a student at the University of Stanford.", result); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperTest.java b/libraries/src/test/java/com/baeldung/text/UnicodeEscaperTest.java new file mode 100644 index 0000000000..5a52bfd0db --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/UnicodeEscaperTest.java @@ -0,0 +1,16 @@ +package com.baeldung.text; + +import org.apache.commons.text.translate.UnicodeEscaper; +import org.junit.Assert; +import org.junit.Test; + +public class UnicodeEscaperTest { + + @Test + public void whenTranslate_thenCorrect() { + UnicodeEscaper ue = UnicodeEscaper.above(0); + String result = ue.translate("ABCD"); + + Assert.assertEquals("\\u0041\\u0042\\u0043\\u0044", result); + } +} diff --git a/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java b/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java new file mode 100644 index 0000000000..b9268d67b3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java @@ -0,0 +1,23 @@ +package com.baeldung.text; + +import org.apache.commons.text.WordUtils; +import org.junit.Assert; +import org.junit.Test; + +public class WordUtilsTest { + + @Test + public void whenCapitalized_thenCorrect() { + String toBeCapitalized = "to be capitalized!"; + String result = WordUtils.capitalize(toBeCapitalized); + + Assert.assertEquals("To Be Capitalized!", result); + } + + @Test + public void whenContainsWords_thenCorrect() { + boolean containsWords = WordUtils.containsAllWords("String to search", "to", "search"); + + Assert.assertTrue(containsWords); + } +} diff --git a/pom.xml b/pom.xml index 43f31d5c98..faf214b567 100644 --- a/pom.xml +++ b/pom.xml @@ -93,7 +93,7 @@ log4j log4j2 lombok - + mapstruct metrics mesos-marathon @@ -121,7 +121,7 @@ selenium-junit-testng solr spark-java - spring-5 + spring-5-mvc spring-akka spring-amqp @@ -140,7 +140,6 @@ spring-data-couchbase-2 spring-data-dynamodb spring-data-elasticsearch - spring-data-javaslang spring-data-mongodb spring-data-neo4j spring-data-redis @@ -226,6 +225,7 @@ spring-drools drools liquibase + spring-boot-property-exp diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 4b373923ef..c2c565aef6 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -39,6 +39,11 @@ org.springframework.boot spring-boot-starter-webflux + + org.projectreactor + reactor-spring + 1.0.1.RELEASE + diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java new file mode 100644 index 0000000000..3a2e1b1a75 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -0,0 +1,86 @@ +package com.baeldung.web.reactive.client; + +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.springframework.http.*; +import org.springframework.http.client.reactive.ClientHttpRequest; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.BodyInserter; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.net.URI; +import java.nio.charset.Charset; +import java.time.ZonedDateTime; +import java.util.Collections; + +@RestController +public class WebClientController { + + @ResponseStatus(HttpStatus.OK) + @GetMapping("/resource") + public void getResource() { + } + + public void demonstrateWebClient() { + // request + WebClient.UriSpec request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); + WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); + + // request body specifications + WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST).uri("/resource"); + WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post().uri(URI.create("/resource")); + + // request header specification + WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); + WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromObject("data")); + + // inserters + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters + .fromPublisher(Subscriber::onComplete, String.class); + + + LinkedMultiValueMap map = new LinkedMultiValueMap<>(); + map.add("key1", "value1"); + map.add("key2", "value2"); + + BodyInserter, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map); + BodyInserter inserter3 = BodyInserters.fromObject("body"); + + // responses + WebClient.ResponseSpec response1 = uri1 + .body(inserter3) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(Charset.forName("UTF-8")) + .ifNoneMatch("*") + .ifModifiedSince(ZonedDateTime.now()) + .retrieve(); + WebClient.ResponseSpec response2 = requestSpec2.retrieve(); + + } + + private WebClient createWebClient() { + return WebClient.create(); + } + + private WebClient createWebClientWithServerURL() { + return WebClient.create("http://localhost:8081"); + } + + private WebClient createWebClientWithServerURLAndDefaultValues() { + return WebClient + .builder() + .baseUrl("http://localhost:8081") + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java new file mode 100644 index 0000000000..4127f22c01 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java @@ -0,0 +1,58 @@ +package com.baeldung.web.client; + +import com.baeldung.Spring5Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.WebHandler; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class WebTestClientTest { + + @LocalServerPort + private int port; + + private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route( + RequestPredicates.GET("/resource"), + request -> ServerResponse.ok().build() + ); + private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); + + @Test + public void testWebTestClientWithServerWebHandler() { + WebTestClient.bindToWebHandler(WEB_HANDLER).build(); + } + + @Test + public void testWebTestClientWithRouterFunction() { + WebTestClient + .bindToRouterFunction(ROUTER_FUNCTION) + .build().get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().isEmpty(); + } + + @Test + public void testWebTestClientWithServerURL() { + WebTestClient + .bindToServer() + .baseUrl("http://localhost:" + port) + .build() + .get() + .uri("/resource") + .exchange() + .expectStatus().is4xxClientError() + .expectBody(); + } + +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/Greeting.java b/spring-all/src/main/java/com/baeldung/contexts/Greeting.java new file mode 100644 index 0000000000..99b473c6c4 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/Greeting.java @@ -0,0 +1,19 @@ +package com.baeldung.contexts; + +public class Greeting { + + private String message; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "Greeting [message=" + message + "]"; + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java new file mode 100644 index 0000000000..c3ff90cf39 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java @@ -0,0 +1,35 @@ +package com.baeldung.contexts.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +@Configuration +public class ApplicationInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); + rootContext.register(RootApplicationConfig.class); + servletContext.addListener(new ContextLoaderListener(rootContext)); + + AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); + normalWebAppContext.register(NormalWebAppConfig.class); + ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext)); + normal.setLoadOnStartup(1); + normal.addMapping("/api/*"); + + AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); + secureWebAppContext.register(SecureWebAppConfig.class); + ServletRegistration.Dynamic secure = servletContext.addServlet("secure-webapp", new DispatcherServlet(secureWebAppContext)); + secure.setLoadOnStartup(1); + secure.addMapping("/s/api/*"); + } + +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java new file mode 100644 index 0000000000..c250cedc49 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.contexts.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) +public class NormalWebAppConfig extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver resolver = new InternalResourceViewResolver(); + resolver.setPrefix("/WEB-INF/view/"); + resolver.setSuffix(".jsp"); + resolver.setViewClass(JstlView.class); + return resolver; + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java new file mode 100644 index 0000000000..59821076d2 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.contexts.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.contexts.Greeting; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.contexts.services" }) +public class RootApplicationConfig { + + @Bean + public Greeting greeting() { + Greeting greeting = new Greeting(); + greeting.setMessage("Hello World !!"); + return greeting; + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java new file mode 100644 index 0000000000..f499a4ceba --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.contexts.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) +public class SecureWebAppConfig extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver resolver = new InternalResourceViewResolver(); + resolver.setPrefix("/WEB-INF/secure/view/"); + resolver.setSuffix(".jsp"); + resolver.setViewClass(JstlView.class); + return resolver; + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java new file mode 100644 index 0000000000..dd70ce8e97 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -0,0 +1,41 @@ +package com.baeldung.contexts.normal; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.ContextLoader; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.contexts.services.ApplicationContextUtilService; +import com.baeldung.contexts.services.GreeterService; + +@Controller +public class HelloWorldController { + + @Autowired + WebApplicationContext webApplicationContext; + + @Autowired + private GreeterService greeterService; + + private void processContext() { + WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext(); + + System.out.println("root context : " + rootContext); + System.out.println("root context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames())); + + System.out.println("context : " + webApplicationContext); + System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames())); + } + + @RequestMapping(path = "/welcome") + public ModelAndView helloWorld() { + processContext(); + String message = "
" + "

" + greeterService.greet() + "

"; + return new ModelAndView("welcome", "message", message); + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java b/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java new file mode 100644 index 0000000000..b46ace91ae --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java @@ -0,0 +1,49 @@ +package com.baeldung.contexts.secure; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.ContextLoader; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.contexts.services.ApplicationContextUtilService; +import com.baeldung.contexts.services.GreeterService; + +@Controller +public class HelloWorldSecureController { + + @Autowired + WebApplicationContext webApplicationContext; + + @Autowired + private GreeterService greeterService; + + @Autowired + @Qualifier("contextAware") + private ApplicationContextUtilService contextUtilService; + + private void processContext() { + ApplicationContext context = contextUtilService.getApplicationContext(); + System.out.println("application context : " + context); + System.out.println("application context Beans: " + Arrays.asList(context.getBeanDefinitionNames())); + + WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext(); + System.out.println("context : " + rootContext); + System.out.println("context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames())); + + System.out.println("context : " + webApplicationContext); + System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames())); + } + + @RequestMapping(path = "/welcome") + public ModelAndView helloWorld() { + processContext(); + String message = "
" + "

" + greeterService.greet() + "

"; + return new ModelAndView("welcome", "message", message); + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java b/spring-all/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java new file mode 100644 index 0000000000..332cb10620 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/services/ApplicationContextUtilService.java @@ -0,0 +1,21 @@ +package com.baeldung.contexts.services; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Service; + +@Service(value="contextAware") +public class ApplicationContextUtilService implements ApplicationContextAware { + + private ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public ApplicationContext getApplicationContext() { + return applicationContext; + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/services/GreeterService.java b/spring-all/src/main/java/com/baeldung/contexts/services/GreeterService.java new file mode 100644 index 0000000000..f68b2fe5af --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/services/GreeterService.java @@ -0,0 +1,19 @@ +package com.baeldung.contexts.services; + +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; + +import com.baeldung.contexts.Greeting; + +@Service +public class GreeterService { + + @Resource + private Greeting greeting; + + public String greet(){ + return greeting.getMessage(); + } + +} diff --git a/spring-all/src/main/webapp/WEB-INF/index.jsp b/spring-all/src/main/webapp/WEB-INF/index.jsp new file mode 100644 index 0000000000..c38169bb95 --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml b/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml new file mode 100644 index 0000000000..d358e2d62b --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml @@ -0,0 +1,19 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml b/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml new file mode 100644 index 0000000000..cd79c64e79 --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml @@ -0,0 +1,16 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml b/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml new file mode 100644 index 0000000000..5bca724670 --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml @@ -0,0 +1,19 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/secure/view/welcome.jsp b/spring-all/src/main/webapp/WEB-INF/secure/view/welcome.jsp new file mode 100644 index 0000000000..49ca0f8e87 --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/secure/view/welcome.jsp @@ -0,0 +1,11 @@ + + + Spring Web Contexts + + +
+
+ Secure Web Application : ${message} +
+ + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-all/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..6a82fb1d5a --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,11 @@ + + + Spring Web Contexts + + +
+
+ Normal Web Application : ${message} +
+ + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web.xml index 3ac9e9ed8c..2050f28f81 100644 --- a/spring-all/src/main/webapp/WEB-INF/web.xml +++ b/spring-all/src/main/webapp/WEB-INF/web.xml @@ -3,7 +3,48 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> - + + + + contextConfigLocation + /WEB-INF/rootApplicationContext.xml + + + + org.springframework.web.context.ContextLoaderListener + + + + + + secure-webapp + + org.springframework.web.servlet.DispatcherServlet + + 1 + + contextConfigLocation + /WEB-INF/secure-webapp-servlet.xml + + + + secure-webapp + /s/api/* + + + + + normal-webapp + + org.springframework.web.servlet.DispatcherServlet + + 1 + + + normal-webapp + /api/* + + test-mvc diff --git a/spring-all/src/main/webapp/index.jsp b/spring-all/src/main/webapp/index.jsp new file mode 100644 index 0000000000..c38169bb95 --- /dev/null +++ b/spring-all/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/spring-boot-property-exp/README.md b/spring-boot-property-exp/README.md new file mode 100644 index 0000000000..5b2552ade7 --- /dev/null +++ b/spring-boot-property-exp/README.md @@ -0,0 +1,2 @@ +## The Module Holds Sources for the Following Articles + - [Automatic Property Expansion with Spring Boot] (http://www.baeldung.com/property-expansion-spring-boot) \ No newline at end of file diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml new file mode 100644 index 0000000000..f554bb5b99 --- /dev/null +++ b/spring-boot-property-exp/pom.xml @@ -0,0 +1,32 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + 4.0.0 + + com.baeldung + spring-boot-property-exp + 0.0.1-SNAPSHOT + + pom + + spring-boot-property-exp + http://maven.apache.org + + + UTF-8 + + + + property-exp-default + property-exp-custom + + + + diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom/pom.xml new file mode 100644 index 0000000000..234404a6c0 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom/pom.xml @@ -0,0 +1,60 @@ + + + spring-boot-property-exp + com.baeldung + 0.0.1-SNAPSHOT + + 4.0.0 + + com.baeldung + property-exp-custom + 0.0.1-SNAPSHOT + jar + + property-exp-custom + http://maven.apache.org + + + UTF-8 + Custom Property Value + + + + + org.springframework.boot + spring-boot-starter + 1.5.4.RELEASE + + + + + + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.7 + + + @ + + true + + + + + + + diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java new file mode 100644 index 0000000000..d88dbf0123 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java @@ -0,0 +1,13 @@ +package com.baeldung.propertyexpansion; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootPropertyExpansionApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootPropertyExpansionApp.class, args); + } + +} diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java new file mode 100644 index 0000000000..920996e120 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java @@ -0,0 +1,37 @@ +package com.baeldung.propertyexpansion.components; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class PropertyLoggerBean { + + private static final Logger log = LoggerFactory.getLogger(PropertyLoggerBean.class); + + @Value("${expanded.project.version}") + private String projectVersion; + + @Value("${expanded.project.property}") + private String projectProperty; + + + @PostConstruct + public void printProperties() { + + log.info(""); + log.info("Properties logged in a bean:"); + log.info("==========================================="); + log.info("Project version : {}", projectVersion); + log.info("Project property : {}", projectProperty); + log.info("==========================================="); + log.info(""); + + } + + + +} diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties new file mode 100644 index 0000000000..545fcc2e46 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties @@ -0,0 +1,2 @@ +expanded.project.version=${project.version} +expanded.project.property=${custom.property} \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt new file mode 100644 index 0000000000..2b5d7f1ee5 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt @@ -0,0 +1,21 @@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@@########@@@@@@@@@@@@@@@@@@@@@@@@...@@@@@@@@@:..@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@#. @@@@@* *@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@#o @@@@@* @@@@@* @@@:*.*@@@@@@@: *8@@@ @@@@&:.#@. @o**@@@@**:@o*o@@:.:@@@@@:.o#@&*:@@@@ +@@@@@@@@@@@@* @@@@@* 8888 8@ @@@8 #@o 8@# .@ @@* :. @* @@@@ @. : &@ ** .@@@@ +@@@@@@@@@@. @ o@@@@@* *@@@o::& .* 8@@@@. @@ 8@@@@. @* @@@@ @. @@@& * @@@@# .@@@@ +@@@@@@@@@& @ @@@@@@* @@@@@@ 8 @@@@ .. o&&&&&&& @@ #@@@@. @* @@@@ @. @@@# * @@@@@ .@@@@ +@@@@@@@@@ @@o @@@@@@@* oooo* 8 @@@& @* @@@ # 88. 88. *& o#: @. @@@# *@ &#& .@@@@ +@@@@@@@@# @@@8 @@@@@@@* .*@@@#. *@@ @@@& :#@@@o .@@: *&@8 @o o@@: @. @@@# *@@#. :8# .@@@@ +@@@@@@@@@ @@@@ &@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# o@@@@ @@@@@ +@@@@@& &@@@@ 8@@@@@@@@@8&8@@@@@#8#@@@o8@#&@@o&@@@&@@8@@&@@@@88@@8#@8&@@##@@@@@@#8@@#8@@88@@@@@ *@@@@@@@ +@@@# #@@@@#. @@@@@@@@@@@@@8@@8#o@&#@@@@o.@o*@@*.@@@.@&:8o8*@@@8&@@#@@@8@@@@8@#@@@8&@@@@@@#@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + +These values are expanded in banner.txt +========================================================== +expanded.project.version value is ${expanded.project.version} + +expanded.project.property value is ${expanded.project.property} +========================================================== \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default/build.gradle new file mode 100644 index 0000000000..f3c5f4a378 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/build.gradle @@ -0,0 +1,50 @@ +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE") + } +} + +apply plugin: 'java' +apply plugin: 'maven' +apply plugin: 'idea' +apply plugin: 'org.springframework.boot' + +group = 'com.baeldung' +version = '0.0.1-SNAPSHOT' + +description = """spring-boot""" + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +repositories { + mavenCentral() +} + +import org.apache.tools.ant.filters.ReplaceTokens +processResources { + with copySpec { + from 'src/main/resources' + include '**/application*.yml' + include '**/application*.yaml' + include '**/application*.properties' + project.properties.findAll().each { prop -> + + if (prop.value != null) { + filter(ReplaceTokens, tokens: [ (prop.key): prop.value]) + filter(ReplaceTokens, tokens: [ ('project.' + prop.key): prop.value]) + } + + } + } +} + +dependencies { + compile("org.springframework.boot:spring-boot-starter") +} diff --git a/spring-boot-property-exp/property-exp-default/gradle.properties b/spring-boot-property-exp/property-exp-default/gradle.properties new file mode 100644 index 0000000000..e0ec84d851 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/gradle.properties @@ -0,0 +1 @@ +custom.property=Custom Gradle Property \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default/pom.xml new file mode 100644 index 0000000000..3629e56111 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + com.baeldung + property-exp-default + 0.0.1-SNAPSHOT + jar + + property-exp-default + http://maven.apache.org + + + UTF-8 + Custom Property Value + + + + + org.springframework.boot + spring-boot-starter + + + + diff --git a/spring-boot-property-exp/property-exp-default/settings.gradle b/spring-boot-property-exp/property-exp-default/settings.gradle new file mode 100644 index 0000000000..faccf1c7f3 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'property-exp-default' diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java new file mode 100644 index 0000000000..d88dbf0123 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java @@ -0,0 +1,13 @@ +package com.baeldung.propertyexpansion; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootPropertyExpansionApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootPropertyExpansionApp.class, args); + } + +} diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java new file mode 100644 index 0000000000..b7427d5eab --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java @@ -0,0 +1,36 @@ +package com.baeldung.propertyexpansion.components; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class PropertyLoggerBean { + + private static final Logger log = LoggerFactory.getLogger(PropertyLoggerBean.class); + + @Value("${expanded.project.version}") + private String projectVersion; + + @Value("${expanded.project.property}") + private String projectProperty; + + @PostConstruct + public void printProperties() { + + log.info(""); + log.info("Properties logged from logger bean"); + log.info("==========================================="); + log.info("Project version : {}", projectVersion); + log.info("Project property : {}", projectProperty); + log.info("==========================================="); + log.info(""); + + } + + + +} diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties new file mode 100644 index 0000000000..4e28ccadaa --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties @@ -0,0 +1,2 @@ +expanded.project.version=@project.version@ +expanded.project.property=@custom.property@ \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt new file mode 100644 index 0000000000..20963b0447 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt @@ -0,0 +1,21 @@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@@########@@@@@@@@@@@@@@@@@@@@@@@@...@@@@@@@@@:..@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@#. @@@@@* *@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@#o @@@@@* @@@@@* @@@:*.*@@@@@@@: *8@@@ @@@@&:.#@. @o**@@@@**:@o*o@@:.:@@@@@:.o#@&*:@@@@ +@@@@@@@@@@@@* @@@@@* 8888 8@ @@@8 #@o 8@# .@ @@* :. @* @@@@ @. : &@ ** .@@@@ +@@@@@@@@@@. @ o@@@@@* *@@@o::& .* 8@@@@. @@ 8@@@@. @* @@@@ @. @@@& * @@@@# .@@@@ +@@@@@@@@@& @ @@@@@@* @@@@@@ 8 @@@@ .. o&&&&&&& @@ #@@@@. @* @@@@ @. @@@# * @@@@@ .@@@@ +@@@@@@@@@ @@o @@@@@@@* oooo* 8 @@@& @* @@@ # 88. 88. *& o#: @. @@@# *@ &#& .@@@@ +@@@@@@@@# @@@8 @@@@@@@* .*@@@#. *@@ @@@& :#@@@o .@@: *&@8 @o o@@: @. @@@# *@@#. :8# .@@@@ +@@@@@@@@@ @@@@ &@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# o@@@@ @@@@@ +@@@@@& &@@@@ 8@@@@@@@@@8&8@@@@@#8#@@@o8@#&@@o&@@@&@@8@@&@@@@88@@8#@8&@@##@@@@@@#8@@#8@@88@@@@@ *@@@@@@@ +@@@# #@@@@#. @@@@@@@@@@@@@8@@8#o@&#@@@@o.@o*@@*.@@@.@&:8o8*@@@8&@@#@@@8@@@@8@#@@@8&@@@@@@#@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + +These values are expanded in banner.txt +========================================================== +{expanded.project.version} is ${expanded.project.version} + +{expanded.project.property} is ${expanded.project.property} +========================================================== \ No newline at end of file diff --git a/spring-data-javaslang/.gitignore b/spring-data-javaslang/.gitignore deleted file mode 100644 index 7ee5423d14..0000000000 --- a/spring-data-javaslang/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target/ -/project/ -.idea -.classpath -.eclipse diff --git a/spring-data-javaslang/pom.xml b/spring-data-javaslang/pom.xml deleted file mode 100644 index 02d214344e..0000000000 --- a/spring-data-javaslang/pom.xml +++ /dev/null @@ -1,109 +0,0 @@ - - - 4.0.0 - spring-data-javaslang - spring-data-javaslang - 0.0.1-SNAPSHOT - - - 2.9.1-01 - 2.3.7-01 - 2.4.8 - 2.0.5 - 1.5.1.RELEASE - 4.3.6.RELEASE - 4.3.6.RELEASE - 4.3.6.RELEASE - ${basedir}/src/test/java - - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - - - - test-app - - verify - - - org.springframework.boot - spring-boot-maven-plugin - - - spring-boot-run - verify - - run - - false - - - - - - - - - - - org.springframework.boot - spring-boot-devtools - true - - - - com.h2database - h2 - 1.4.193 - - - - io.javaslang - javaslang - ${javaslang.version} - - - - org.springframework.data - spring-data-jpa - 1.11.0.RELEASE - - - - org.springframework.boot - spring-boot - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring-boot.version} - - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - - - - org.springframework - spring-context - ${spring-context.version} - - - - org.springframework - spring-core - ${spring-core.version} - - - - \ No newline at end of file diff --git a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/model/Book.java b/spring-data-javaslang/src/main/java/com/baeldung/spring_data/model/Book.java deleted file mode 100644 index 95653abb6c..0000000000 --- a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/model/Book.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.spring_data.model; - -import javaslang.collection.Seq; - -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; - -@Entity -@Table(name = "book") -public class Book { - - @GeneratedValue - @Id - private Long id; - - private String title; - - private Seq authors; - - - public void setTitle(String title){ - this.title = title; - } - - public String getTitle(){ - return this.title; - } - - public Long getId(){ - return this.id; - } - - public void setAuthors(Seq authors){ - this.authors = authors; - } - - public Seq getAuthors(){ - return this.authors; - } -} diff --git a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/model/JavaBook.java b/spring-data-javaslang/src/main/java/com/baeldung/spring_data/model/JavaBook.java deleted file mode 100644 index ab99b0d929..0000000000 --- a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/model/JavaBook.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.spring_data.model; - -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -import java.util.List; - -@Entity -@Table(name = "java_book") -public class JavaBook { - - @GeneratedValue - @Id - private Long id; - - private String title; - - @ElementCollection - private List authors; - - - public void setAuthors(List authors){ - this.authors = authors; - } - - public void setTitle(String title){ - this.title = title; - } - - public String getTitle(){ - return this.title; - } - - public Long getId(){ - return this.id; - } -} - diff --git a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/repository/BookRepository.java b/spring-data-javaslang/src/main/java/com/baeldung/spring_data/repository/BookRepository.java deleted file mode 100644 index 75b6d0b426..0000000000 --- a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/repository/BookRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.spring_data.repository; - -import com.baeldung.spring_data.model.Book; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import javaslang.collection.Seq; -import javaslang.control.Option; - -@Repository -public interface BookRepository extends JpaRepository{ - Book save(Book book); - - Option findById(Long id); - - Option> findByTitleContaining(String title); - -} diff --git a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/repository/JavaBookRepository.java b/spring-data-javaslang/src/main/java/com/baeldung/spring_data/repository/JavaBookRepository.java deleted file mode 100644 index a4aeab85ee..0000000000 --- a/spring-data-javaslang/src/main/java/com/baeldung/spring_data/repository/JavaBookRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.spring_data.repository; - -import com.baeldung.spring_data.model.JavaBook; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface JavaBookRepository extends JpaRepository{ - JavaBook save(JavaBook book); - - JavaBook findById(Long id); - - List findByTitleContaining(String title); -} \ No newline at end of file diff --git a/spring-data-javaslang/src/main/java/com/baeldung/spring_data_app/MainApp.java b/spring-data-javaslang/src/main/java/com/baeldung/spring_data_app/MainApp.java deleted file mode 100644 index d8a194e92e..0000000000 --- a/spring-data-javaslang/src/main/java/com/baeldung/spring_data_app/MainApp.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.spring_data_app; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableJpaRepositories("com.baeldung.spring_data.repository") -@EnableTransactionManagement -@EntityScan("com.baeldung.spring_data.model") -@SpringBootApplication -public class MainApp { - public static void main(String[] args){ - SpringApplication.run(MainApp.class, args); - } -} diff --git a/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringIntegrationTest.java b/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringIntegrationTest.java deleted file mode 100644 index 7a23fa1ef2..0000000000 --- a/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringIntegrationTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung.spring_data_tests; - -import com.baeldung.spring_data.model.Book; -import com.baeldung.spring_data.model.JavaBook; -import com.baeldung.spring_data.repository.BookRepository; -import com.baeldung.spring_data.repository.JavaBookRepository; -import com.baeldung.spring_data_app.MainApp; -import javaslang.collection.List; -import javaslang.collection.Seq; -import javaslang.control.Option; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.ArrayList; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = MainApp.class,webEnvironment = WebEnvironment.NONE) -public class SpringIntegrationTest { - - @Autowired - private JavaBookRepository javaRepository; - - @Autowired - private BookRepository repository; - - @Test - public void should_return_seq(){ - Seq authors = List.of("author1","author2"); - Book testBook = new Book(); - testBook.setTitle("Javaslang in Spring Data Seq Test Return"); - testBook.setAuthors(authors); - Book book = repository.save(testBook); - Option> books = repository.findByTitleContaining("Seq Test"); - - assertThat(books).isNotEmpty(); - } - - - @Test - public void should_return_option_with_book(){ - Seq authors = List.of("author1","author2"); - Book testBook = new Book(); - testBook.setTitle("Javaslang in Spring Data"); - testBook.setAuthors(authors); - Book book = repository.save(testBook); - Option retBook = repository.findById(1L); - - assertThat(retBook.isDefined()).isTrue(); - assertThat(retBook).isNotEmpty(); - } - - @Test - public void should_return_list(){ - ArrayList authors = new ArrayList(); - authors.add("author1"); - authors.add("author2"); - JavaBook testBook = new JavaBook(); - testBook.setTitle("Javaslang in Spring Data Seq Return"); - testBook.setAuthors(authors); - JavaBook book = javaRepository.save(testBook); - java.util.List books = javaRepository.findByTitleContaining("Seq"); - assertThat(books) - .isNotEmpty() - .hasSize(1) - .extracting("title") - .contains("Javaslang in Spring Data Seq Return"); - } - - @Test - public void should_return_book(){ - ArrayList authors = new ArrayList(); - authors.add("author1"); - authors.add("author2"); - JavaBook testBook = new JavaBook(); - testBook.setTitle("Javaslang in Spring Data"); - testBook.setAuthors(authors); - JavaBook book = javaRepository.save(testBook); - JavaBook retBook = javaRepository.findById(1L); - - assertThat(retBook.getId()).isEqualTo(1L); - assertThat(retBook.getTitle()).isEqualTo("Javaslang in Spring Data"); - } -} \ No newline at end of file diff --git a/spring-drools/src/test/java/com/baeldung/spring/drools/service/TaxiFareCalculatorServiceTest.java b/spring-drools/src/test/java/com/baeldung/spring/drools/service/TaxiFareCalculatorServiceIntegrationTest.java similarity index 95% rename from spring-drools/src/test/java/com/baeldung/spring/drools/service/TaxiFareCalculatorServiceTest.java rename to spring-drools/src/test/java/com/baeldung/spring/drools/service/TaxiFareCalculatorServiceIntegrationTest.java index d329300a2b..97bd44316f 100644 --- a/spring-drools/src/test/java/com/baeldung/spring/drools/service/TaxiFareCalculatorServiceTest.java +++ b/spring-drools/src/test/java/com/baeldung/spring/drools/service/TaxiFareCalculatorServiceIntegrationTest.java @@ -1,94 +1,94 @@ -package com.baeldung.spring.drools.service; - -import com.baeldung.spring.drools.model.Fare; -import com.baeldung.spring.drools.model.TaxiRide; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TaxiFareConfiguration.class) -public class TaxiFareCalculatorServiceTest { - - @Autowired - private TaxiFareCalculatorService taxiFareCalculatorService; - - @Test - public void testCalculateFareScenario1() { - TaxiRide taxiRide = new TaxiRide(); - taxiRide.setbNightSurcharge(false); - taxiRide.setDistanceInMile(9L); - Fare rideFare = new Fare(); - Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); - - assertNotNull(totalCharge); - assertEquals(Long.valueOf(70), totalCharge); - } - - @Test - public void testCalculateFareScenario2() { - TaxiRide taxiRide = new TaxiRide(); - taxiRide.setbNightSurcharge(true); - taxiRide.setDistanceInMile(5L); - Fare rideFare = new Fare(); - Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); - - assertNotNull(totalCharge); - assertEquals(Long.valueOf(100), totalCharge); - } - - @Test - public void testCalculateFareScenario3() { - TaxiRide taxiRide = new TaxiRide(); - taxiRide.setbNightSurcharge(false); - taxiRide.setDistanceInMile(50L); - Fare rideFare = new Fare(); - Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); - - assertNotNull(totalCharge); - assertEquals(Long.valueOf(170), totalCharge); - } - - @Test - public void testCalculateFareScenario4() { - TaxiRide taxiRide = new TaxiRide(); - taxiRide.setbNightSurcharge(true); - taxiRide.setDistanceInMile(50L); - Fare rideFare = new Fare(); - Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); - - assertNotNull(totalCharge); - assertEquals(Long.valueOf(250), totalCharge); - } - - @Test - public void testCalculateFareScenario5() { - TaxiRide taxiRide = new TaxiRide(); - taxiRide.setbNightSurcharge(false); - taxiRide.setDistanceInMile(100L); - Fare rideFare = new Fare(); - Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); - - assertNotNull(totalCharge); - assertEquals(Long.valueOf(220), totalCharge); - } - - @Test - public void testCalculateFareScenario6() { - TaxiRide taxiRide = new TaxiRide(); - taxiRide.setbNightSurcharge(true); - taxiRide.setDistanceInMile(100L); - Fare rideFare = new Fare(); - Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); - - assertNotNull(totalCharge); - assertEquals(Long.valueOf(350), totalCharge); - } - -} +package com.baeldung.spring.drools.service; + +import com.baeldung.spring.drools.model.Fare; +import com.baeldung.spring.drools.model.TaxiRide; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaxiFareConfiguration.class) +public class TaxiFareCalculatorServiceIntegrationTest { + + @Autowired + private TaxiFareCalculatorService taxiFareCalculatorService; + + @Test + public void testCalculateFareScenario1() { + TaxiRide taxiRide = new TaxiRide(); + taxiRide.setbNightSurcharge(false); + taxiRide.setDistanceInMile(9L); + Fare rideFare = new Fare(); + Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); + + assertNotNull(totalCharge); + assertEquals(Long.valueOf(70), totalCharge); + } + + @Test + public void testCalculateFareScenario2() { + TaxiRide taxiRide = new TaxiRide(); + taxiRide.setbNightSurcharge(true); + taxiRide.setDistanceInMile(5L); + Fare rideFare = new Fare(); + Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); + + assertNotNull(totalCharge); + assertEquals(Long.valueOf(100), totalCharge); + } + + @Test + public void testCalculateFareScenario3() { + TaxiRide taxiRide = new TaxiRide(); + taxiRide.setbNightSurcharge(false); + taxiRide.setDistanceInMile(50L); + Fare rideFare = new Fare(); + Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); + + assertNotNull(totalCharge); + assertEquals(Long.valueOf(170), totalCharge); + } + + @Test + public void testCalculateFareScenario4() { + TaxiRide taxiRide = new TaxiRide(); + taxiRide.setbNightSurcharge(true); + taxiRide.setDistanceInMile(50L); + Fare rideFare = new Fare(); + Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); + + assertNotNull(totalCharge); + assertEquals(Long.valueOf(250), totalCharge); + } + + @Test + public void testCalculateFareScenario5() { + TaxiRide taxiRide = new TaxiRide(); + taxiRide.setbNightSurcharge(false); + taxiRide.setDistanceInMile(100L); + Fare rideFare = new Fare(); + Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); + + assertNotNull(totalCharge); + assertEquals(Long.valueOf(220), totalCharge); + } + + @Test + public void testCalculateFareScenario6() { + TaxiRide taxiRide = new TaxiRide(); + taxiRide.setbNightSurcharge(true); + taxiRide.setDistanceInMile(100L); + Fare rideFare = new Fare(); + Long totalCharge = taxiFareCalculatorService.calculateFare(taxiRide, rideFare); + + assertNotNull(totalCharge); + assertEquals(Long.valueOf(350), totalCharge); + } + +} diff --git a/vavr/src/main/java/com/baeldung/vavr/Person.java b/vavr/src/main/java/com/baeldung/vavr/Person.java index 0c6c427c73..bd497c0b77 100644 --- a/vavr/src/main/java/com/baeldung/vavr/Person.java +++ b/vavr/src/main/java/com/baeldung/vavr/Person.java @@ -4,7 +4,7 @@ public class Person { private String name; private int age; - public Person(String name, int age) { + Person(String name, int age) { super(); this.name = name; this.age = age; diff --git a/vavr/src/main/java/com/baeldung/vavr/PersonValidator.java b/vavr/src/main/java/com/baeldung/vavr/PersonValidator.java index efaa74c710..f53bdad7ec 100644 --- a/vavr/src/main/java/com/baeldung/vavr/PersonValidator.java +++ b/vavr/src/main/java/com/baeldung/vavr/PersonValidator.java @@ -4,10 +4,10 @@ import io.vavr.collection.Seq; import io.vavr.control.Validation; class PersonValidator { - String NAME_ERR = "Invalid characters in name: "; - String AGE_ERR = "Age must be at least 0"; + private static final String NAME_ERR = "Invalid characters in name: "; + private static final String AGE_ERR = "Age must be at least 0"; - public Validation, Person> validatePerson(String name, int age) { + Validation, Person> validatePerson(String name, int age) { return Validation.combine(validateName(name), validateAge(age)).ap(Person::new); } diff --git a/vavr/src/main/java/com/baeldung/vavr/exception/handling/VavrTry.java b/vavr/src/main/java/com/baeldung/vavr/exception/handling/VavrTry.java index 3a9399c4f0..af10a91c33 100644 --- a/vavr/src/main/java/com/baeldung/vavr/exception/handling/VavrTry.java +++ b/vavr/src/main/java/com/baeldung/vavr/exception/handling/VavrTry.java @@ -5,14 +5,14 @@ import com.baeldung.vavr.exception.handling.client.HttpClient; import com.baeldung.vavr.exception.handling.client.Response; import io.vavr.control.Try; -public class VavrTry { +class VavrTry { private final HttpClient httpClient; - public VavrTry(HttpClient httpClient) { + VavrTry(HttpClient httpClient) { this.httpClient = httpClient; } - public Try getResponse() { + Try getResponse() { return Try.of(httpClient::call); } } diff --git a/xml/src/test/resources/Customer1.xml b/xml/src/test/resources/Customer1.xml old mode 100755 new mode 100644