Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-09-20 13:35:33 +02:00
commit 8aa9a65548
480 changed files with 17025 additions and 1299 deletions

2
.gitignore vendored
View File

@ -41,3 +41,5 @@ SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
*.springBeans

View File

@ -23,4 +23,4 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
CI - Jenkins
================================
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials/)**
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/github%20projects%20Jobs/job/tutorials/)**

View File

@ -8,3 +8,4 @@
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)

View File

@ -1,3 +1,5 @@
package com.baeldung.algorithms.binarysearch;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

View File

@ -0,0 +1,38 @@
package com.baeldung.algorithms.linkedlist;
public class CycleDetectionBruteForce {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) {
return new CycleDetectionResult<>(false, null);
}
Node<T> it1 = head;
int nodesTraversedByOuter = 0;
while (it1 != null && it1.next != null) {
it1 = it1.next;
nodesTraversedByOuter++;
int x = nodesTraversedByOuter;
Node<T> it2 = head;
int noOfTimesCurrentNodeVisited = 0;
while (x > 0) {
it2 = it2.next;
if (it2 == it1) {
noOfTimesCurrentNodeVisited++;
}
if (noOfTimesCurrentNodeVisited == 2) {
return new CycleDetectionResult<>(true, it1);
}
x--;
}
}
return new CycleDetectionResult<>(false, null);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.algorithms.linkedlist;
public class CycleDetectionByFastAndSlowIterators {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) {
return new CycleDetectionResult<>(false, null);
}
Node<T> slow = head;
Node<T> fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return new CycleDetectionResult<>(true, fast);
}
}
return new CycleDetectionResult<>(false, null);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.algorithms.linkedlist;
import java.util.HashSet;
import java.util.Set;
public class CycleDetectionByHashing {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) {
return new CycleDetectionResult<>(false, null);
}
Set<Node<T>> set = new HashSet<>();
Node<T> node = head;
while (node != null) {
if (set.contains(node)) {
return new CycleDetectionResult<>(true, node);
}
set.add(node);
node = node.next;
}
return new CycleDetectionResult<>(false, null);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.algorithms.linkedlist;
public class CycleDetectionResult<T> {
boolean cycleExists;
Node<T> node;
public CycleDetectionResult(boolean cycleExists, Node<T> node) {
super();
this.cycleExists = cycleExists;
this.node = node;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.algorithms.linkedlist;
public class CycleRemovalBruteForce {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
return result.cycleExists;
}
/**
* @param loopNodeParam - reference to the node where Flyods cycle
* finding algorithm ends, i.e. the fast and the slow iterators
* meet.
* @param head - reference to the head of the list
*/
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
Node<T> it = head;
while (it != null) {
if (isNodeReachableFromLoopNode(it, loopNodeParam)) {
Node<T> loopStart = it;
findEndNodeAndBreakCycle(loopStart);
break;
}
it = it.next;
}
}
private static <T> boolean isNodeReachableFromLoopNode(Node<T> it, Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam;
do {
if (it == loopNode) {
return true;
}
loopNode = loopNode.next;
} while (loopNode.next != loopNodeParam);
return false;
}
private static <T> void findEndNodeAndBreakCycle(Node<T> loopStartParam) {
Node<T> loopStart = loopStartParam;
while (loopStart.next != loopStartParam) {
loopStart = loopStart.next;
}
loopStart.next = null;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.algorithms.linkedlist;
public class CycleRemovalByCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
return result.cycleExists;
}
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
int cycleLength = calculateCycleLength(loopNodeParam);
Node<T> cycleLengthAdvancedIterator = head;
Node<T> it = head;
for (int i = 0; i < cycleLength; i++) {
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
}
while (it.next != cycleLengthAdvancedIterator.next) {
it = it.next;
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
}
cycleLengthAdvancedIterator.next = null;
}
private static <T> int calculateCycleLength(Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam;
int length = 1;
while (loopNode.next != loopNodeParam) {
length++;
loopNode = loopNode.next;
}
return length;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.algorithms.linkedlist;
public class CycleRemovalWithoutCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
return result.cycleExists;
}
private static <T> void removeCycle(Node<T> meetingPointParam, Node<T> head) {
Node<T> loopNode = meetingPointParam;
Node<T> it = head;
while (loopNode.next != it.next) {
it = it.next;
loopNode = loopNode.next;
}
loopNode.next = null;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.algorithms.linkedlist;
public class Node<T> {
T data;
Node<T> next;
public static <T> Node<T> createNewNode(T data, Node<T> next) {
Node<T> node = new Node<T>();
node.data = data;
node.next = next;
return node;
}
public static <T> void traverseList(Node<T> root) {
if (root == null) {
return;
}
Node<T> node = root;
while (node != null) {
System.out.println(node.data);
node = node.next;
}
}
public static <T> Node<T> getTail(Node<T> root) {
if (root == null) {
return null;
}
Node<T> node = root;
while (node.next != null) {
node = node.next;
}
return node;
}
}

View File

@ -0,0 +1,194 @@
package com.baeldung.algorithms.string.search;
import java.math.BigInteger;
import java.util.Random;
public class StringSearchAlgorithms {
public static long getBiggerPrime(int m) {
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
return prime.longValue();
}
public static long getLowerPrime(long number) {
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
return prime.longValue();
}
private static int getNumberOfBits(final int number) {
return Integer.SIZE - Integer.numberOfLeadingZeros(number);
}
private static int getNumberOfBits(final long number) {
return Long.SIZE - Long.numberOfLeadingZeros(number);
}
public static int simpleTextSearch(char[] pattern, char[] text) {
int patternSize = pattern.length;
int textSize = text.length;
int i = 0;
while ((i + patternSize) <= textSize) {
int j = 0;
while (text[i + j] == pattern[j]) {
j += 1;
if (j >= patternSize)
return i;
}
i += 1;
}
return -1;
}
public static int RabinKarpMethod(char[] pattern, char[] text) {
int patternSize = pattern.length; // m
int textSize = text.length; // n
long prime = getBiggerPrime(patternSize);
long r = 1;
for (int i = 0; i < patternSize - 1; i++) {
r *= 2;
r = r % prime;
}
long[] t = new long[textSize];
t[0] = 0;
long pfinger = 0;
for (int j = 0; j < patternSize; j++) {
t[0] = (2 * t[0] + text[j]) % prime;
pfinger = (2 * pfinger + pattern[j]) % prime;
}
int i = 0;
boolean passed = false;
int diff = textSize - patternSize;
for (i = 0; i <= diff; i++) {
if (t[i] == pfinger) {
passed = true;
for (int k = 0; k < patternSize; k++) {
if (text[i + k] != pattern[k]) {
passed = false;
break;
}
}
if (passed) {
return i;
}
}
if (i < diff) {
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
t[i + 1] = ((value % prime) + prime) % prime;
}
}
return -1;
}
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
int patternSize = pattern.length; // m
int textSize = text.length; // n
int i = 0, j = 0;
int[] shift = KnuthMorrisPrattShift(pattern);
while ((i + patternSize) <= textSize) {
while (text[i + j] == pattern[j]) {
j += 1;
if (j >= patternSize)
return i;
}
if (j > 0) {
i += shift[j - 1];
j = Math.max(j - shift[j - 1], 0);
} else {
i++;
j = 0;
}
}
return -1;
}
public static int[] KnuthMorrisPrattShift(char[] pattern) {
int patternSize = pattern.length;
int[] shift = new int[patternSize];
shift[0] = 1;
int i = 1, j = 0;
while ((i + j) < patternSize) {
if (pattern[i + j] == pattern[j]) {
shift[i + j] = i;
j++;
} else {
if (j == 0)
shift[i] = i + 1;
if (j > 0) {
i = i + shift[j - 1];
j = Math.max(j - shift[j - 1], 0);
} else {
i = i + 1;
j = 0;
}
}
}
return shift;
}
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
int patternSize = pattern.length;
int textSize = text.length;
int i = 0, j = 0;
while ((i + patternSize) <= textSize) {
j = patternSize - 1;
while (text[i + j] == pattern[j]) {
j--;
if (j < 0)
return i;
}
i++;
}
return -1;
}
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
int shift[] = new int[256];
for (int k = 0; k < 256; k++) {
shift[k] = pattern.length;
}
for (int k = 0; k < pattern.length - 1; k++) {
shift[pattern[k]] = pattern.length - 1 - k;
}
int i = 0, j = 0;
while ((i + pattern.length) <= text.length) {
j = pattern.length - 1;
while (text[i + j] == pattern[j]) {
j -= 1;
if (j < 0)
return i;
}
i = i + shift[text[i + pattern.length - 1]];
}
return -1;
}
}

View File

@ -0,0 +1,25 @@
package algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
public class StringSearchAlgorithmsTest {
@Test
public void testStringSearchAlgorithms(){
String text = "This is some nice text.";
String pattern = "some";
int realPosition = text.indexOf(pattern);
Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
}
}

View File

@ -1,9 +1,11 @@
package algorithms.binarysearch;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.binarysearch.BinarySearch;
public class BinarySearchTest {

View File

@ -0,0 +1,23 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionBruteForceTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionBruteForceTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionByFastAndSlowIteratorsTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByHashingTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleDetectionByHashingTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.algorithms.linkedlist;
import java.util.Arrays;
import java.util.Collection;
import org.junit.runners.Parameterized.Parameters;
public class CycleDetectionTestBase {
@Parameters
public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] {
{ createList(), false },
{ createListWithLoop(), true },
{ createListWithFullCycle(), true },
{ createListWithSingleNodeInCycle(), true }
});
}
public static Node<Integer> createList() {
Node<Integer> root = Node.createNewNode(10, null);
for (int i = 9; i >= 1; --i) {
Node<Integer> current = Node.createNewNode(i, root);
root = current;
}
return root;
}
public static Node<Integer> createListWithLoop() {
Node<Integer> node = createList();
createLoop(node);
return node;
}
public static Node<Integer> createListWithFullCycle() {
Node<Integer> head = createList();
Node<Integer> tail = Node.getTail(head);
tail.next = head;
return head;
}
public static Node<Integer> createListWithSingleNodeInCycle() {
Node<Integer> head = createList();
Node<Integer> tail = Node.getTail(head);
tail.next = tail;
return head;
}
public static void createLoop(Node<Integer> root) {
Node<Integer> tail = Node.getTail(root);
Node<Integer> middle = root;
for (int i = 1; i <= 4; i++) {
middle = middle.next;
}
tail.next = middle;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalBruteForceTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleRemovalBruteForceTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleRemovalByCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
public CycleRemovalWithoutCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -0,0 +1,2 @@
### Relevant articles
- [Introduction to Apache Shiro](http://www.baeldung.com/apache-shiro)

2
bootique/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Bootique](http://www.baeldung.com/bootique)

View File

@ -0,0 +1,35 @@
package com.baeldung.stream;
import static org.junit.Assert.fail;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.Test;
public class SupplierStreamTest {
@Test(expected = IllegalStateException.class)
public void givenStream_whenStreamUsedTwice_thenThrowException() {
Stream<String> stringStream = Stream.of("A", "B", "C", "D");
Optional<String> result1 = stringStream.findAny();
System.out.println(result1.get());
Optional<String> result2 = stringStream.findFirst();
System.out.println(result2.get());
}
@Test
public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() {
try {
Supplier<Stream<String>> streamSupplier = () -> Stream.of("A", "B", "C", "D");
Optional<String> result1 = streamSupplier.get().findAny();
System.out.println(result1.get());
Optional<String> result2 = streamSupplier.get().findFirst();
System.out.println(result2.get());
} catch (IllegalStateException e) {
fail();
}
}
}

View File

@ -8,7 +8,7 @@
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
@ -16,3 +16,4 @@
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)

View File

@ -0,0 +1,24 @@
package com.baeldung.java9.compactstring;
import java.util.List;
import static java.util.stream.Collectors.toList;
import java.util.stream.IntStream;
public class CompactStringDemo {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
List strings = IntStream.rangeClosed(1, 10_000_000)
.mapToObj(Integer::toString).collect(toList());
long totalTime = System.currentTimeMillis() - startTime;
System.out.println("Generated " + strings.size() + " strings in "
+ totalTime + " ms.");
startTime = System.currentTimeMillis();
String appended = (String) strings.stream().limit(100_000)
.reduce("", (left, right) -> left.toString() + right.toString());
totalTime = System.currentTimeMillis() - startTime;
System.out.println("Created string of length " + appended.length()
+ " in " + totalTime + " ms.");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.concurrent.callable;
import java.util.concurrent.Callable;
public class FactorialTask implements Callable<Integer> {
int number;
public FactorialTask(int number) {
this.number = number;
}
public Integer call() throws InvalidParamaterException {
int fact=1;
if(number < 0)
throw new InvalidParamaterException("Number must be positive");
for(int count=number;count>1;count--){
fact=fact * count;
}
return fact;
}
private class InvalidParamaterException extends Exception {
public InvalidParamaterException(String message) {
super(message);
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.concurrent.runnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EventLoggingTask implements Runnable{
private Logger logger = LoggerFactory.getLogger(EventLoggingTask.class);
@Override
public void run() {
String messge="Message read from the event queue";
logger.info("Message read from event queue is "+messge);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.concurrent.runnable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TaskRunner {
private static ExecutorService executorService;
public static void main(String[] args) {
executeTask();
}
private static void executeTask() {
executorService= Executors.newSingleThreadExecutor();
EventLoggingTask task = new EventLoggingTask();
Future future = executorService.submit(task);
executorService.shutdown();
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.concurrent.callable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static junit.framework.Assert.assertEquals;
public class FactorialTaskManualTest {
private ExecutorService executorService;
@Before
public void setup(){
executorService = Executors.newSingleThreadExecutor();
}
@Test
public void whenTaskSubmitted_ThenFutureResultObtained() throws ExecutionException, InterruptedException {
FactorialTask task = new FactorialTask(5);
Future<Integer> future= executorService.submit(task);
assertEquals(120,future.get().intValue());
}
@Test(expected = ExecutionException.class)
public void whenException_ThenCallableThrowsIt() throws ExecutionException, InterruptedException {
FactorialTask task = new FactorialTask(-5);
Future<Integer> future= executorService.submit(task);
Integer result=future.get().intValue();
}
@Test
public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){
FactorialTask task = new FactorialTask(-5);
Future<Integer> future= executorService.submit(task);
assertEquals(false,future.isDone());
}
@After
public void cleanup(){
executorService.shutdown();
}
}

View File

@ -18,7 +18,7 @@ public class BaeldungSychronizedBlockTest {
IntStream.range(0, 1000)
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount());
}
@ -29,7 +29,7 @@ public class BaeldungSychronizedBlockTest {
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
}

View File

@ -99,4 +99,10 @@
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)

View File

@ -80,7 +80,7 @@
</dependency>
<!-- logging -->
<dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
@ -187,15 +187,35 @@
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>com.darwinsys</groupId>
<artifactId>hirondelle-date4j</artifactId>
<version>${hirondelle-date4j.version}</version>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies>
<build>
@ -224,6 +244,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
@ -357,6 +378,8 @@
</arguments>
</configuration>
</plugin>
</plugins>
</build>
@ -391,12 +414,37 @@
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase>-->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
@ -418,9 +466,10 @@
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version>
<fscontext.version>4.6-b01</fscontext.version>
<joda-time.version>2.9.9</joda-time.version>
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
@ -428,9 +477,8 @@
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>
</project>

View File

@ -5,9 +5,16 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class AdapterPatternDriver {
public static void main(String args[]) {
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph.");
LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph.");
LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph.");
Movable bugattiVeyron = new BugattiVeyron();
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.getSpeed() + " Kmph.");
Movable mcLaren = new McLaren();
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
LOG.info("McLaren F1 top speed is " + mcLarenAdapter.getSpeed() + " Kmph.");
Movable astonMartin = new AstonMartin();
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
LOG.info("McLaren F1 top speed is " + astonMartinAdapter.getSpeed() + " Kmph.");
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.designpatterns.adapter;
public class AstonMartin implements Movable {
@Override
public double getSpeed() {
return 220;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.designpatterns.adapter;
public class BugattiVeyron implements Movable {
@Override
public double getSpeed() {
return 268;
}
}

View File

@ -1,15 +0,0 @@
package com.baeldung.designpatterns.adapter;
public class LuxuryCarsSpeed {
public double bugattiVeyronInMPH() {
return 268;
}
public double mcLarenInMPH() {
return 241;
}
public double astonMartinInMPH() {
return 220;
}
}

View File

@ -1,9 +0,0 @@
package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsSpeedAdapter {
public double bugattiVeyronInKMPH();
public double mcLarenInKMPH();
public double astonMartinInKMPH();
}

View File

@ -1,26 +0,0 @@
package com.baeldung.designpatterns.adapter;
public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter {
@Override
public double bugattiVeyronInKMPH() {
double mph = super.bugattiVeyronInMPH();
return convertMPHtoKMPH(mph);
}
@Override
public double mcLarenInKMPH() {
double mph = super.mcLarenInMPH();
return convertMPHtoKMPH(mph);
}
@Override
public double astonMartinInKMPH() {
double mph = super.astonMartinInMPH();
return convertMPHtoKMPH(mph);
}
private double convertMPHtoKMPH(double mph) {
return mph * 1.60934;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.designpatterns.adapter;
public class McLaren implements Movable {
@Override
public double getSpeed() {
return 241;
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.adapter;
public interface Movable {
// returns speed in MPH
double getSpeed();
}

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.adapter;
public interface MovableAdapter {
// returns speed in KMPH
double getSpeed();
}

View File

@ -0,0 +1,19 @@
package com.baeldung.designpatterns.adapter;
public class MovableAdapterImpl implements MovableAdapter {
private Movable luxuryCars;
public MovableAdapterImpl(Movable luxuryCars) {
this.luxuryCars = luxuryCars;
}
@Override
public double getSpeed() {
double mph = luxuryCars.getSpeed();
return convertMPHtoKMPH(mph);
}
private double convertMPHtoKMPH(double mph) {
return mph * 1.60934;
}
}

View File

@ -1,12 +1,8 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Blue implements Color {
@Override
public void fillColor() {
LOG.info("Color : Blue");
public String fill() {
return "Color is Blue";
}
}

View File

@ -5,10 +5,10 @@ public class BridgePatternDriver {
public static void main(String[] args) {
//a square with red color
Shape square = new Square(new Red());
square.drawShape();
System.out.println(square.draw());
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
triangle.drawShape();
System.out.println(triangle.draw());
}
}

View File

@ -1,5 +1,5 @@
package com.baeldung.designpatterns.bridge;
public interface Color {
public void fillColor();
String fill();
}

View File

@ -1,12 +1,10 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Red implements Color {
@Override
public void fillColor() {
LOG.info("Color : Red");
public String fill() {
return "Color is Red";
}
}

View File

@ -7,5 +7,5 @@ public abstract class Shape {
this.color = color;
}
abstract public void drawShape();
abstract public String draw();
}

View File

@ -1,7 +1,5 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Square extends Shape {
public Square(Color color) {
@ -9,8 +7,7 @@ public class Square extends Shape {
}
@Override
public void drawShape() {
LOG.info("Square drawn. ");
color.fillColor();
public String draw() {
return "Square drawn. " + color.fill();
}
}

View File

@ -1,7 +1,5 @@
package com.baeldung.designpatterns.bridge;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Triangle extends Shape {
public Triangle(Color color) {
@ -9,8 +7,7 @@ public class Triangle extends Shape {
}
@Override
public void drawShape() {
LOG.info("Triangle drawn. ");
color.fillColor();
public String draw() {
return "Triangle drawn. "+ color.fill();
}
}

View File

@ -1,5 +1,5 @@
package com.baeldung.designpatterns.decorator;
public interface ChristmasTree {
public String decorate();
}
String decorate();
}

View File

@ -1,5 +1,5 @@
package com.baeldung.designpatterns.proxy;
public interface ExpensiveObject {
public void process();
void process();
}

View File

@ -1,131 +1,67 @@
package com.baeldung.numberofdigits;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Benchmarking {;
private static final int LOWER_BOUND = 1;
private static final int UPPER_BOUND = 999999999;
public static void main(String[] args) {
LOG.info("Testing all methods...");
long length = test_stringBasedSolution();
LOG.info("String Based Solution : " + length);
length = test_logarithmicApproach();
LOG.info("Logarithmic Approach : " + length);
length = test_repeatedMultiplication();
LOG.info("Repeated Multiplication : " + length);
length = test_shiftOperators();
LOG.info("Shift Operators : " + length);
length = test_dividingWithPowersOf2();
LOG.info("Dividing with Powers of 2 : " + length);
length = test_divideAndConquer();
LOG.info("Divide And Conquer : " + length);
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.RunnerException;
public class Benchmarking {
public static void main(String[] args) throws RunnerException, IOException {
org.openjdk.jmh.Main.main(args);
}
private static long test_stringBasedSolution() {
long startTime, stopTime, elapsedTime;
startTime = System.currentTimeMillis();
int total = 0;
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
total += NumberOfDigits.stringBasedSolution(i);
}
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
return elapsedTime;
}
private static long test_logarithmicApproach() {
long startTime, stopTime, elapsedTime;
startTime = System.currentTimeMillis();
int total = 0;
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
total += NumberOfDigits.logarithmicApproach(i);
}
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
return elapsedTime;
}
private static long test_repeatedMultiplication() {
long startTime, stopTime, elapsedTime;
startTime = System.currentTimeMillis();
int total = 0;
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
total += NumberOfDigits.repeatedMultiplication(i);
}
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
return elapsedTime;
}
private static long test_shiftOperators() {
long startTime, stopTime, elapsedTime;
startTime = System.currentTimeMillis();
int total = 0;
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
total += NumberOfDigits.shiftOperators(i);
}
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
return elapsedTime;
}
private static long test_dividingWithPowersOf2() {
long startTime, stopTime, elapsedTime;
startTime = System.currentTimeMillis();
int total = 0;
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
total += NumberOfDigits.dividingWithPowersOf2(i);
}
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
return elapsedTime;
}
private static long test_divideAndConquer() {
long startTime, stopTime, elapsedTime;
startTime = System.currentTimeMillis();
int total = 0;
for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) {
total += NumberOfDigits.divideAndConquer(i);
}
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
return elapsedTime;
@State(Scope.Thread)
public static class ExecutionPlan {
public int number = Integer.MAX_VALUE;
public int length = 0;
public NumberOfDigits numberOfDigits= new NumberOfDigits();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void stringBasedSolution(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void logarithmicApproach(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void repeatedMultiplication(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void shiftOperators(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void dividingWithPowersOf2(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void divideAndConquer(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
}
}

View File

@ -1,17 +1,17 @@
package com.baeldung.numberofdigits;
public class NumberOfDigits {
public static int stringBasedSolution(int number) {
public int stringBasedSolution(int number) {
int length = String.valueOf(number).length();
return length;
}
public static int logarithmicApproach(int number) {
public int logarithmicApproach(int number) {
int length = (int) Math.log10(number) + 1;
return length;
}
public static int repeatedMultiplication(int number) {
public int repeatedMultiplication(int number) {
int length = 0;
long temp = 1;
while(temp <= number) {
@ -21,7 +21,7 @@ public class NumberOfDigits {
return length;
}
public static int shiftOperators(int number) {
public int shiftOperators(int number) {
int length = 0;
long temp = 1;
while(temp <= number) {
@ -31,7 +31,7 @@ public class NumberOfDigits {
return length;
}
public static int dividingWithPowersOf2(int number) {
public int dividingWithPowersOf2(int number) {
int length = 1;
if (number >= 100000000) {
length += 8;
@ -51,7 +51,7 @@ public class NumberOfDigits {
return length;
}
public static int divideAndConquer(int number) {
public int divideAndConquer(int number) {
if (number < 100000){
// 5 digits or less
if (number < 100){

View File

@ -1,27 +1,33 @@
package com.baeldung.numberofdigits;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class NumberOfDigitsDriver {
public static void main(String[] args) {
LOG.info("Testing all methods...");
long length = NumberOfDigits.stringBasedSolution(602);
LOG.info("String Based Solution : " + length);
length = NumberOfDigits.logarithmicApproach(602);
LOG.info("Logarithmic Approach : " + length);
length = NumberOfDigits.repeatedMultiplication(602);
LOG.info("Repeated Multiplication : " + length);
length = NumberOfDigits.shiftOperators(602);
LOG.info("Shift Operators : " + length);
length = NumberOfDigits.dividingWithPowersOf2(602);
LOG.info("Dividing with Powers of 2 : " + length);
length = NumberOfDigits.divideAndConquer(602);
LOG.info("Divide And Conquer : " + length);
}
}
package com.baeldung.numberofdigits;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class NumberOfDigitsDriver {
private static NumberOfDigits numberOfDigits;
static {
numberOfDigits = new NumberOfDigits();
}
public static void main(String[] args) {
LOG.info("Testing all methods...");
long length = numberOfDigits.stringBasedSolution(602);
LOG.info("String Based Solution : " + length);
length = numberOfDigits.logarithmicApproach(602);
LOG.info("Logarithmic Approach : " + length);
length = numberOfDigits.repeatedMultiplication(602);
LOG.info("Repeated Multiplication : " + length);
length = numberOfDigits.shiftOperators(602);
LOG.info("Shift Operators : " + length);
length = numberOfDigits.dividingWithPowersOf2(602);
LOG.info("Dividing with Powers of 2 : " + length);
length = numberOfDigits.divideAndConquer(602);
LOG.info("Divide And Conquer : " + length);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.sneakythrows;
import lombok.SneakyThrows;
public class SneakyRunnable implements Runnable {
@SneakyThrows
public void run() {
try {
throw new InterruptedException();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
new SneakyRunnable().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.sneakythrows;
import java.io.IOException;
public class SneakyThrows {
public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
throw (E) e;
}
public static void throwsSneakyIOException() {
sneakyThrow(new IOException("sneaky"));
}
public static void main(String[] args) {
try {
throwsSneakyIOException();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import io.vavr.collection.Stream;
import one.util.streamex.EntryStream;
public class StreamIndices {
public static List<String> getEvenIndexedStrings(String[] names) {
List<String> evenIndexedNames = IntStream.range(0, names.length)
.filter(i -> i % 2 == 0)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
return evenIndexedNames;
}
public List<String> getEvenIndexedStringsVersionTwo(List<String> names) {
List<String> evenIndexedNames = EntryStream.of(names)
.filterKeyValue((index, name) -> index % 2 == 0)
.values()
.toList();
return evenIndexedNames;
}
public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) {
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
.filter(i -> i.getIndex() % 2 == 0)
.collect(Collectors.toList());
return list;
}
public static List<Indexed<String>> getOddIndexedStrings(List<String> names) {
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
.filter(i -> i.getIndex() % 2 == 1)
.collect(Collectors.toList());
return list;
}
public static List<String> getOddIndexedStrings(String[] names) {
List<String> oddIndexedNames = IntStream.range(0, names.length)
.filter(i -> i % 2 == 1)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
return oddIndexedNames;
}
public static List<String> getOddIndexedStringsVersionTwo(String[] names) {
List<String> oddIndexedNames = Stream.of(names)
.zipWithIndex()
.filter(tuple -> tuple._2 % 2 == 1)
.map(tuple -> tuple._1)
.toJavaList();
return oddIndexedNames;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.string;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class StringBufferStringBuilder {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(StringBufferStringBuilder.class.getSimpleName())
.build();
new Runner(opt).run();
}
@State(Scope.Benchmark)
public static class MyState {
int iterations = 1000;
String initial = "abc";
String suffix = "def";
}
@Benchmark
public StringBuffer benchmarkStringBuffer(MyState state) {
StringBuffer stringBuffer = new StringBuffer(state.initial);
for (int i = 0; i < state.iterations; i++) {
stringBuffer.append(state.suffix);
}
return stringBuffer;
}
@Benchmark
public StringBuilder benchmarkStringBuilder(MyState state) {
StringBuilder stringBuilder = new StringBuilder(state.initial);
for (int i = 0; i < state.iterations; i++) {
stringBuilder.append(state.suffix);
}
return stringBuilder;
}
}

View File

@ -1,20 +1,30 @@
package com.baeldung.designpatterns;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter;
import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl;
import com.baeldung.designpatterns.adapter.AstonMartin;
import com.baeldung.designpatterns.adapter.BugattiVeyron;
import com.baeldung.designpatterns.adapter.McLaren;
import com.baeldung.designpatterns.adapter.Movable;
import com.baeldung.designpatterns.adapter.MovableAdapter;
import com.baeldung.designpatterns.adapter.MovableAdapterImpl;
public class AdapterPatternIntegrationTest {
@Test
public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001);
assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001);
assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001);
public void givenMovableAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
Movable bugattiVeyron = new BugattiVeyron();
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001);
Movable mcLaren = new McLaren();
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
assertEquals(mcLarenAdapter.getSpeed(), 387.85094, 0.00001);
Movable astonMartin = new AstonMartin();
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
assertEquals(astonMartinAdapter.getSpeed(), 354.0548, 0.00001);
}
}

View File

@ -1,14 +1,7 @@
package com.baeldung.designpatterns;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.*;
import java.util.List;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.designpatterns.bridge.Blue;
@ -18,35 +11,16 @@ import com.baeldung.designpatterns.bridge.Square;
import com.baeldung.designpatterns.bridge.Triangle;
public class BridgePatternIntegrationTest {
public static TestAppenderDP appender;
@Before
public void setUp() {
appender = new TestAppenderDP();
LOG.addAppender(appender);
}
@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {
//a square with red color
Shape square = new Square(new Red());
square.drawShape();
assertEquals(square.draw(), "Square drawn. Color is Red");
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
triangle.drawShape();
final List<LoggingEvent> log = appender.getLog();
assertThat((String) log.get(0).getMessage(), is("Square drawn. "));
assertThat((String) log.get(1).getMessage(), is("Color : Red"));
assertThat((String) log.get(2).getMessage(), is("Triangle drawn. "));
assertThat((String) log.get(3).getMessage(), is("Color : Blue"));
}
@After
public void tearDown() {
LOG.removeAppender(appender);
assertEquals(triangle.draw(), "Triangle drawn. Color is Blue");
}
}

View File

@ -10,19 +10,16 @@ import com.baeldung.designpatterns.decorator.ChristmasTreeImpl;
import com.baeldung.designpatterns.decorator.Garland;
public class DecoratorPatternIntegrationTest {
private ChristmasTree tree;
@Test
public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() {
//christmas tree with just one Garland
tree = new Garland(new ChristmasTreeImpl());
assertEquals(tree.decorate(), "Christmas tree with Garland");
//christmas tree with two Garlands and one Bubble lights
tree = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights");
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
assertEquals(tree1.decorate(),
"Christmas tree with Garland");
ChristmasTree tree2 = new BubbleLights(
new Garland(new Garland(new ChristmasTreeImpl())));
assertEquals(tree2.decorate(),
"Christmas tree with Garland with Garland with Bubble Lights");
}
}

View File

@ -1,20 +1,23 @@
package com.baeldung.encoderdecoder;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.is;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.*;
import org.springframework.web.util.UriUtils;
public class EncoderDecoderUnitTest {
@ -76,19 +79,20 @@ public class EncoderDecoderUnitTest {
private String encodePath(String path) {
try {
path = new URI(null, null, path, null).getPath();
} catch (URISyntaxException e) {
path = UriUtils.encodePath(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return path;
}
@Test
public void givenPath_thenEncodeDecodePath() throws URISyntaxException {
URI uri = new URI(null, null, "/Path 1/Path+2", null);
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException {
String pathSegment = "/Path 1/Path+2";
String encodedPathSegment = encodePath(pathSegment);
String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8");
Assert.assertEquals("/Path%201/Path+2", encodedPathSegment);
Assert.assertEquals("/Path 1/Path+2", decodedPathSegment);
}
@Test

View File

@ -8,10 +8,10 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NioEchoIntegrationTest {
public class NioEchoLiveTest {
Process server;
EchoClient client;
private Process server;
private EchoClient client;
@Before
public void setup() throws IOException, InterruptedException {

View File

@ -21,9 +21,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JdbcIntegrationTest {
public class JdbcLiveTest {
private static final Logger LOG = Logger.getLogger(JdbcIntegrationTest.class);
private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class);
private Connection con;

View File

@ -15,56 +15,56 @@ public class RoundTest {
private double expected = 2.03d;
@Test
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
places = 3;
expected = 2.035d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 1000.0d;
places = 17;
expected = 1000.0d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 256.025d;
places = 2;
expected = 256.03d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
value = 260.775d;
value = 260.775d;
places = 2;
expected = 260.78d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
value = 90080070060.1d;
places = 9;
expected = 90080070060.1d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !

View File

@ -9,7 +9,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class UDPIntegrationTest {
public class UDPLiveTest {
private EchoClient client;
@Before

View File

@ -7,7 +7,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class BroadcastIntegrationTest {
public class BroadcastLiveTest {
private BroadcastingClient client;
@Test

View File

@ -7,7 +7,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class MulticastIntegrationTest {
public class MulticastLiveTest {
private MulticastingClient client;
@Test

View File

@ -9,7 +9,13 @@ import org.junit.runner.RunWith;
@RunWith(Theories.class)
public class NumberOfDigitsIntegrationTest {
private static NumberOfDigits numberOfDigits;
static {
numberOfDigits = new NumberOfDigits();
}
@DataPoints
public static int[][] lowestIntegers()
{
@ -64,37 +70,37 @@ public class NumberOfDigitsIntegrationTest {
@Theory
public void givenDataPoints_whenStringBasedSolutionInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], NumberOfDigits.stringBasedSolution(entry[1]));
Assert.assertEquals(entry[0], numberOfDigits.stringBasedSolution(entry[1]));
}
@Theory
public void givenDataPoints_whenLogarithmicApproachInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], NumberOfDigits.logarithmicApproach(entry[1]));
Assert.assertEquals(entry[0], numberOfDigits.logarithmicApproach(entry[1]));
}
@Theory
public void givenDataPoints_whenRepeatedMultiplicationInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], NumberOfDigits.repeatedMultiplication(entry[1]));
Assert.assertEquals(entry[0], numberOfDigits.repeatedMultiplication(entry[1]));
}
@Theory
public void givenDataPoints_whenShiftOperatorsInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], NumberOfDigits.shiftOperators(entry[1]));
Assert.assertEquals(entry[0], numberOfDigits.shiftOperators(entry[1]));
}
@Theory
public void givenDataPoints_whenDividingWithPowersOf2Invoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], NumberOfDigits.dividingWithPowersOf2(entry[1]));
Assert.assertEquals(entry[0], numberOfDigits.dividingWithPowersOf2(entry[1]));
}
@Theory
public void givenDataPoints_whenDivideAndConquerInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], NumberOfDigits.divideAndConquer(entry[1]));
Assert.assertEquals(entry[0], numberOfDigits.divideAndConquer(entry[1]));
}
}

View File

@ -7,7 +7,7 @@ import java.io.File;
import static org.junit.Assert.assertTrue;
public class ScreenshotIntegrationTest {
public class ScreenshotLiveTest {
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
private File file = new File("Screenshot.jpg");

View File

@ -0,0 +1,17 @@
package com.baeldung.sneakythrows;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class SneakyRunnableTest {
@Test
public void whenCallSneakyRunnableMethod_thenThrowException() {
try {
new SneakyRunnable().run();
} catch (Exception e) {
assertEquals(InterruptedException.class, e.getStackTrace());
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.sneakythrows;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class SneakyThrowsTest {
@Test
public void whenCallSneakyMethod_thenThrowSneakyException() {
try {
SneakyThrows.throwsSneakyIOException();
} catch (Exception ex) {
assertEquals("sneaky", ex.getMessage().toString());
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.stream;
import com.codepoetics.protonpack.Indexed;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class StreamIndicesTest {
@Test
public void whenCalled_thenReturnListOfEvenIndexedStrings() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void whenCalled_thenReturnListOfEvenIndexedStringsVersionTwo() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void whenCalled_thenReturnListOfOddStrings() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
List<String> actualResult = StreamIndices.getOddIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void givenList_whenCalled_thenReturnListOfEvenIndexedStrings() {
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
List<Indexed<String>> expectedResult = Arrays
.asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed
.index(4, "Durim"));
List<Indexed<String>> actualResult = StreamIndices.getEvenIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void givenList_whenCalled_thenReturnListOfOddIndexedStrings() {
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
List<Indexed<String>> expectedResult = Arrays
.asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed
.index(5, "Shpetim"));
List<Indexed<String>> actualResult = StreamIndices.getOddIndexedStrings(names);
assertEquals(expectedResult, actualResult);
}
@Test
public void whenCalled_thenReturnListOfOddStringsVersionTwo() {
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
List<String> actualResult = StreamIndices.getOddIndexedStringsVersionTwo(names);
assertEquals(expectedResult, actualResult);
}
}

View File

@ -0,0 +1,5 @@
package org.baeldung.java.diamond;
public class Car<T extends Engine> implements Vehicle<T> {
}

View File

@ -0,0 +1,13 @@
package org.baeldung.java.diamond;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DiamondOperatorUnitTest {
@Test
public void whenCreateCarUsingDiamondOperator_thenSuccess() {
Car<Diesel> myCar = new Car<>();
assertNotNull(myCar);
}
}

View File

@ -0,0 +1,10 @@
package org.baeldung.java.diamond;
public class Diesel implements Engine {
@Override
public void start() {
System.out.println("Started Diesel...");
}
}

View File

@ -0,0 +1,6 @@
package org.baeldung.java.diamond;
public interface Engine {
void start();
}

View File

@ -0,0 +1,5 @@
package org.baeldung.java.diamond;
public interface Vehicle<T extends Engine> {
}

View File

@ -0,0 +1,17 @@
package org.baeldung.java.rawtypes;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class RawTypesTest {
@Test
public void shouldCreateListUsingRawTypes() {
@SuppressWarnings("rawtypes")
List myList = new ArrayList();
myList.add(new Object());
myList.add("2");
myList.add(new Integer(1));
}
}

6
couchbase/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
# Created by .ignore support plugin (hsz.mobi)
# IntelliJ project files
.idea
*.iml
/target/

0
couchbase-sdk/mvnw → couchbase/mvnw vendored Executable file → Normal file
View File

View File

@ -6,7 +6,7 @@
<artifactId>couchbase-sdk</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>couchbase-sdk</name>
<name>couchbase</name>
<description>Couchbase SDK Tutorials</description>
<parent>
@ -23,6 +23,12 @@
<version>${couchbase.client.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- Spring Context for Dependency Injection -->
<dependency>
<groupId>org.springframework</groupId>
@ -67,9 +73,10 @@
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.4.0</couchbase.client.version>
<couchbase.client.version>2.5.0</couchbase.client.version>
<spring-framework.version>4.3.5.RELEASE</spring-framework.version>
<commons-lang3.version>3.5</commons-lang3.version>
<jackson-version>2.9.1</jackson-version>
</properties>
</project>

Some files were not shown because too many files have changed in this diff Show More