Merge branch 'master' into bael-965
This commit is contained in:
commit
0f49c26335
|
@ -6,7 +6,7 @@ public class NumbersConsumer implements Runnable {
|
|||
private final BlockingQueue<Integer> queue;
|
||||
private final int poisonPill;
|
||||
|
||||
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||
this.queue = queue;
|
||||
this.poisonPill = poisonPill;
|
||||
}
|
||||
|
|
|
@ -9,7 +9,7 @@ public class NumbersProducer implements Runnable {
|
|||
private final int poisonPill;
|
||||
private final int poisonPillPerProducer;
|
||||
|
||||
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||
NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||
this.numbersQueue = numbersQueue;
|
||||
this.poisonPill = poisonPill;
|
||||
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||
|
|
|
@ -7,7 +7,7 @@ public class BrokenWorker implements Runnable {
|
|||
private final List<String> outputScraper;
|
||||
private final CountDownLatch countDownLatch;
|
||||
|
||||
public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||
BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||
this.outputScraper = outputScraper;
|
||||
this.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@ public class WaitingWorker implements Runnable {
|
|||
private final CountDownLatch callingThreadBlocker;
|
||||
private final CountDownLatch completedThreadCounter;
|
||||
|
||||
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||
WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||
|
||||
this.outputScraper = outputScraper;
|
||||
this.readyThreadCounter = readyThreadCounter;
|
||||
|
|
|
@ -7,7 +7,7 @@ public class Worker implements Runnable {
|
|||
private final List<String> outputScraper;
|
||||
private final CountDownLatch countDownLatch;
|
||||
|
||||
public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||
Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||
this.outputScraper = outputScraper;
|
||||
this.countDownLatch = countDownLatch;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -7,9 +7,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||
public class DelayQueueConsumer implements Runnable {
|
||||
private BlockingQueue<DelayObject> queue;
|
||||
private final Integer numberOfElementsToTake;
|
||||
public final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
||||
final AtomicInteger numberOfConsumedElements = new AtomicInteger();
|
||||
|
||||
public DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
||||
DelayQueueConsumer(BlockingQueue<DelayObject> queue, Integer numberOfElementsToTake) {
|
||||
this.queue = queue;
|
||||
this.numberOfElementsToTake = numberOfElementsToTake;
|
||||
}
|
||||
|
|
|
@ -9,9 +9,9 @@ public class DelayQueueProducer implements Runnable {
|
|||
private final Integer numberOfElementsToProduce;
|
||||
private final Integer delayOfEachProducedMessageMilliseconds;
|
||||
|
||||
public DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
DelayQueueProducer(BlockingQueue<DelayObject> queue,
|
||||
Integer numberOfElementsToProduce,
|
||||
Integer delayOfEachProducedMessageMilliseconds) {
|
||||
this.queue = queue;
|
||||
this.numberOfElementsToProduce = numberOfElementsToProduce;
|
||||
this.delayOfEachProducedMessageMilliseconds = delayOfEachProducedMessageMilliseconds;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -7,7 +7,7 @@ public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
|||
|
||||
final private Integer n;
|
||||
|
||||
public FactorialSquareCalculator(Integer n) {
|
||||
FactorialSquareCalculator(Integer n) {
|
||||
this.n = n;
|
||||
}
|
||||
|
||||
|
|
|
@ -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<Integer> calculate(Integer input) {
|
||||
Future<Integer> calculate(Integer input) {
|
||||
return executor.submit(() -> {
|
||||
Thread.sleep(1000);
|
||||
return input * input;
|
||||
|
|
|
@ -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<String> stack = new Stack<>();
|
||||
int CAPACITY = 5;
|
||||
private Stack<String> 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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -12,93 +12,93 @@ import java.util.concurrent.locks.StampedLock;
|
|||
import static java.lang.Thread.sleep;
|
||||
|
||||
public class StampedLockDemo {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
|
||||
private Map<String, String> 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();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -15,106 +15,106 @@ import static java.lang.Thread.sleep;
|
|||
|
||||
public class SynchronizedHashMapWithRWLock {
|
||||
|
||||
static Map<String, String> syncHashMap = new HashMap<>();
|
||||
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
|
||||
private static Map<String, String> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<ZonedDateTime, String> 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<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsFromLastMinute() {
|
||||
return events.tailMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
public ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
ConcurrentNavigableMap<ZonedDateTime, String> getEventsOlderThatOneMinute() {
|
||||
return events.headMap(ZonedDateTime
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
.now()
|
||||
.minusMinutes(1));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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"));
|
||||
|
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -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<Computer> filter(final List<Computer> 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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -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()) {
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -26,36 +26,48 @@
|
|||
//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
//@RunWith(JUnit4.class)
|
||||
//public class MemoryLeaksTest {
|
||||
|
||||
// private Random random = new Random();
|
||||
// public static final ArrayList<Double> list = new ArrayList<Double>(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<Double> list = new ArrayList<Double>(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 = "";
|
||||
|
|
43
jee7/pom.xml
43
jee7/pom.xml
|
@ -31,6 +31,7 @@
|
|||
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
|
||||
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<org.springframework.security.version>4.2.3.RELEASE</org.springframework.security.version>
|
||||
</properties>
|
||||
|
||||
<prerequisites>
|
||||
|
@ -136,6 +137,34 @@
|
|||
<artifactId>standard</artifactId>
|
||||
<version>1.1.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.mvc</groupId>
|
||||
<artifactId>javax.mvc-api</artifactId>
|
||||
<version>20160715</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.ozark</groupId>
|
||||
<artifactId>ozark</artifactId>
|
||||
<version>20160715</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -378,4 +407,18 @@
|
|||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>bintray-mvc-spec-maven</id>
|
||||
<name>bintray</name>
|
||||
<url>http://dl.bintray.com/mvc-spec/maven</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
||||
|
|
|
@ -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 {
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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";
|
||||
}
|
||||
|
||||
}
|
|
@ -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";
|
||||
}
|
||||
}
|
|
@ -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" %>
|
||||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>Welcome to the ADMIN page</h1>
|
||||
|
||||
<a href="<c:url value="/logout" />">Logout</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -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" %>
|
||||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>This is the body of the sample view</h1>
|
||||
|
||||
<security:authorize access="hasRole('USER')">
|
||||
This text is only visible to a user
|
||||
<br/> <br/>
|
||||
<a href="<c:url value="/home/user" />">Restricted Admin Page</a>
|
||||
<br/> <br/>
|
||||
</security:authorize>
|
||||
|
||||
<security:authorize access="hasRole('ADMIN')">
|
||||
This text is only visible to an admin
|
||||
<br/>
|
||||
<a href="<c:url value="/home/admin" />">Admin Page</a>
|
||||
<br/>
|
||||
</security:authorize>
|
||||
|
||||
<a href="<c:url value="/logout" />">Logout</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,26 @@
|
|||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>Login</h1>
|
||||
|
||||
<form name='f' action="/auth/login" method='POST'>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>User:</td>
|
||||
<td><input type='text' name='username' value=''></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Password:</td>
|
||||
<td><input type='password' name='password'/></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input name="submit" type="submit" value="submit"/></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -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" %>
|
||||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>Welcome to the Restricted Admin page</h1>
|
||||
|
||||
<a href="<c:url value="/logout" />">Logout</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -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)
|
|
@ -1,121 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>kotlin-mockito</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nhaarman</groupId>
|
||||
<artifactId>mockito-kotlin</artifactId>
|
||||
<version>${mockito-kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
|
||||
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<version>${kotlin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile</id>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/main/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>test-compile</id>
|
||||
<goals>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/test/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler.version}</version>
|
||||
<executions>
|
||||
<!-- Replacing default-compile as it is treated specially
|
||||
by maven -->
|
||||
<execution>
|
||||
<id>default-compile</id>
|
||||
<phase>none</phase>
|
||||
</execution>
|
||||
<!-- Replacing default-testCompile as it is treated specially
|
||||
by maven -->
|
||||
<execution>
|
||||
<id>default-testCompile</id>
|
||||
<phase>none</phase>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>java-compile</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>java-test-compile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<mockito.version>2.8.9</mockito.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<kotlin.version>1.1.2-4</kotlin.version>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
<maven-compiler.version>3.5.1</maven-compiler.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
package com.baeldung.java;
|
||||
|
||||
public class StringUtils {
|
||||
public static String toUpperCase(String name) {
|
||||
return name.toUpperCase();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
||||
}
|
|
@ -3,7 +3,6 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>kotlin</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
|
@ -13,7 +12,6 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
|
@ -21,7 +19,6 @@
|
|||
</repository>
|
||||
</repositories>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
|
@ -45,9 +42,14 @@
|
|||
<artifactId>kotlinx-coroutines-core</artifactId>
|
||||
<version>${kotlinx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nhaarman</groupId>
|
||||
<artifactId>mockito-kotlin</artifactId>
|
||||
<version>${mockito-kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -123,6 +125,7 @@
|
|||
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
|
||||
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
|
||||
<kotlinx.version>0.15</kotlinx.version>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -90,6 +90,11 @@
|
|||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
@ -366,6 +371,7 @@
|
|||
<multiverse.version>0.7.0</multiverse.version>
|
||||
<cglib.version>3.2.4</cglib.version>
|
||||
<commons-lang.version>3.5</commons-lang.version>
|
||||
<commons-text.version>1.1</commons-text.version>
|
||||
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
||||
<jasypt.version>1.9.2</jasypt.version>
|
||||
<javatuples.version>1.2</javatuples.version>
|
||||
|
|
|
@ -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<String> codes;
|
||||
private Map<String, Student> students = new HashMap<String, Student>();
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getCodes() {
|
||||
return codes;
|
||||
}
|
||||
|
||||
public void setCodes(List<String> codes) {
|
||||
this.codes = codes;
|
||||
}
|
||||
|
||||
public void setStudent(String id, Student student) {
|
||||
students.put(id, student);
|
||||
}
|
||||
|
||||
public Student getStudent(String enrolledId) {
|
||||
return students.get(enrolledId);
|
||||
}
|
||||
}
|
|
@ -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<String> 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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<String> 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"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<Character> script = cmp.getScript();
|
||||
int mod = script.getModifications();
|
||||
|
||||
Assert.assertEquals(4, mod);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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<String, String> 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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
6
pom.xml
6
pom.xml
|
@ -93,7 +93,7 @@
|
|||
<module>log4j</module>
|
||||
<module>log4j2</module>
|
||||
<module>lombok</module>
|
||||
|
||||
<!-- <module>kotlin</module>-->
|
||||
<module>mapstruct</module>
|
||||
<module>metrics</module>
|
||||
<module>mesos-marathon</module>
|
||||
|
@ -121,7 +121,7 @@
|
|||
<module>selenium-junit-testng</module>
|
||||
<module>solr</module>
|
||||
<module>spark-java</module>
|
||||
<module>spring-5</module>
|
||||
<!-- <module>spring-5</module>-->
|
||||
<module>spring-5-mvc</module>
|
||||
<module>spring-akka</module>
|
||||
<module>spring-amqp</module>
|
||||
|
@ -140,7 +140,6 @@
|
|||
<module>spring-data-couchbase-2</module>
|
||||
<module>spring-data-dynamodb</module>
|
||||
<module>spring-data-elasticsearch</module>
|
||||
<module>spring-data-javaslang</module>
|
||||
<module>spring-data-mongodb</module>
|
||||
<module>spring-data-neo4j</module>
|
||||
<module>spring-data-redis</module>
|
||||
|
@ -226,6 +225,7 @@
|
|||
<module>spring-drools</module>
|
||||
<module>drools</module>
|
||||
<module>liquibase</module>
|
||||
<module>spring-boot-property-exp</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -39,6 +39,11 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectreactor</groupId>
|
||||
<artifactId>reactor-spring</artifactId>
|
||||
<version>1.0.1.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
|
|
|
@ -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<WebClient.RequestBodySpec> request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST);
|
||||
WebClient.UriSpec<WebClient.RequestBodySpec> 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<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters
|
||||
.fromPublisher(Subscriber::onComplete, String.class);
|
||||
|
||||
|
||||
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
|
||||
map.add("key1", "value1");
|
||||
map.add("key2", "value2");
|
||||
|
||||
BodyInserter<MultiValueMap<String, ?>, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map);
|
||||
BodyInserter<String, ReactiveHttpOutputMessage> 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
}
|
|
@ -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/*");
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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 = "<br><div style='text-align:center;'>" + "<h3> " + greeterService.greet() + "</h3></div>";
|
||||
return new ModelAndView("welcome", "message", message);
|
||||
}
|
||||
}
|
|
@ -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 = "<br><div style='text-align:center;'>" + "<h3> " + greeterService.greet() + "</h3></div>";
|
||||
return new ModelAndView("welcome", "message", message);
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
<html>
|
||||
<body>
|
||||
<h2>Hello World!</h2>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,19 @@
|
|||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<context:component-scan base-package="com.baeldung.contexts.normal" />
|
||||
|
||||
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
|
||||
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
|
||||
<property name="prefix" value="/WEB-INF/view/" />
|
||||
<property name="suffix" value=".jsp" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -0,0 +1,16 @@
|
|||
<?xml version = "1.0" encoding = "UTF-8"?>
|
||||
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
|
||||
|
||||
<context:component-scan base-package="com.baeldung.contexts.services" />
|
||||
|
||||
<bean id="greeting" class="ccom.baeldung.contexts.Greeting">
|
||||
<property name="message" value="Hello World !!" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -0,0 +1,19 @@
|
|||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<context:component-scan base-package="com.baeldung.contexts.secure" />
|
||||
|
||||
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
|
||||
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
|
||||
<property name="prefix" value="/WEB-INF/secure/view/" />
|
||||
<property name="suffix" value=".jsp" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -0,0 +1,11 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>Spring Web Contexts</title>
|
||||
</head>
|
||||
<body>
|
||||
<br>
|
||||
<div style="padding: 10px; border-radius: 10px; font-size: 30px; text-align: center;">
|
||||
Secure Web Application : ${message}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,11 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>Spring Web Contexts</title>
|
||||
</head>
|
||||
<body>
|
||||
<br>
|
||||
<div style="padding: 10px; border-radius: 10px; font-size: 30px; text-align: center;">
|
||||
Normal Web Application : ${message}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -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">
|
||||
|
||||
|
||||
<!-- load root application context -->
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>/WEB-INF/rootApplicationContext.xml</param-value>
|
||||
</context-param>
|
||||
<listener>
|
||||
<listener-class>
|
||||
org.springframework.web.context.ContextLoaderListener
|
||||
</listener-class>
|
||||
</listener>
|
||||
|
||||
<!-- secure web app context -->
|
||||
<servlet>
|
||||
<servlet-name>secure-webapp</servlet-name>
|
||||
<servlet-class>
|
||||
org.springframework.web.servlet.DispatcherServlet
|
||||
</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
<init-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>/WEB-INF/secure-webapp-servlet.xml</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>secure-webapp</servlet-name>
|
||||
<url-pattern>/s/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!-- normal web app context -->
|
||||
<servlet>
|
||||
<servlet-name>normal-webapp</servlet-name>
|
||||
<servlet-class>
|
||||
org.springframework.web.servlet.DispatcherServlet
|
||||
</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>normal-webapp</servlet-name>
|
||||
<url-pattern>/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>test-mvc</servlet-name>
|
||||
<servlet-class>
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
<html>
|
||||
<body>
|
||||
<h2>Hello World!</h2>
|
||||
</body>
|
||||
</html>
|
|
@ -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)
|
|
@ -0,0 +1,32 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-boot-property-exp</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>spring-boot-property-exp</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>property-exp-default</module>
|
||||
<module>property-exp-custom</module>
|
||||
</modules>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,60 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>spring-boot-property-exp</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>property-exp-custom</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>property-exp-custom</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<custom.property>Custom Property Value</custom.property>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.5.4.RELEASE</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${basedir}/src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
<includes>
|
||||
<include>**/application*.yml</include>
|
||||
<include>**/application*.yaml</include>
|
||||
<include>**/application*.properties</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<delimiters>
|
||||
<delimiter>@</delimiter>
|
||||
</delimiters>
|
||||
<useDefaultDelimiters>true</useDefaultDelimiters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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("");
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
expanded.project.version=${project.version}
|
||||
expanded.project.property=${custom.property}
|
|
@ -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}
|
||||
==========================================================
|
|
@ -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")
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
custom.property=Custom Gradle Property
|
|
@ -0,0 +1,33 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.5.4.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>property-exp-default</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>property-exp-default</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<custom.property>Custom Property Value</custom.property>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue