Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
49d4e0f9f2
3
.gitignore
vendored
3
.gitignore
vendored
@ -41,4 +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
|
||||
/vertx-and-rxjava/.vertx/
|
||||
*.springBeans
|
||||
|
||||
|
@ -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/)**
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -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.");
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
|
@ -201,6 +201,21 @@
|
||||
<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>
|
||||
@ -229,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>
|
||||
@ -362,6 +378,8 @@
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
@ -396,6 +414,31 @@
|
||||
</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>
|
||||
|
158
core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java
Normal file → Executable file
158
core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java
Normal file → Executable 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);
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public int number = Integer.MAX_VALUE;
|
||||
public int length = 0;
|
||||
public NumberOfDigits numberOfDigits= new NumberOfDigits();
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void stringBasedSolution(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
|
||||
}
|
||||
|
||||
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);
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void logarithmicApproach(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void repeatedMultiplication(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
|
||||
}
|
||||
|
||||
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);
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void shiftOperators(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
|
||||
}
|
||||
|
||||
stopTime = System.currentTimeMillis();
|
||||
elapsedTime = stopTime - startTime;
|
||||
|
||||
return elapsedTime;
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void dividingWithPowersOf2(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
|
||||
}
|
||||
|
||||
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);
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void divideAndConquer(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
12
core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java
Normal file → Executable file
12
core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java
Normal file → Executable 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){
|
||||
|
18
core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java
Normal file → Executable file
18
core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java
Normal file → Executable file
@ -3,25 +3,31 @@ 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);
|
||||
long length = numberOfDigits.stringBasedSolution(602);
|
||||
LOG.info("String Based Solution : " + length);
|
||||
|
||||
length = NumberOfDigits.logarithmicApproach(602);
|
||||
length = numberOfDigits.logarithmicApproach(602);
|
||||
LOG.info("Logarithmic Approach : " + length);
|
||||
|
||||
length = NumberOfDigits.repeatedMultiplication(602);
|
||||
length = numberOfDigits.repeatedMultiplication(602);
|
||||
LOG.info("Repeated Multiplication : " + length);
|
||||
|
||||
length = NumberOfDigits.shiftOperators(602);
|
||||
length = numberOfDigits.shiftOperators(602);
|
||||
LOG.info("Shift Operators : " + length);
|
||||
|
||||
length = NumberOfDigits.dividingWithPowersOf2(602);
|
||||
length = numberOfDigits.dividingWithPowersOf2(602);
|
||||
LOG.info("Dividing with Powers of 2 : " + length);
|
||||
|
||||
length = NumberOfDigits.divideAndConquer(602);
|
||||
length = numberOfDigits.divideAndConquer(602);
|
||||
LOG.info("Divide And Conquer : " + length);
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
0
core-java/src/main/resources/META-INF/BenchmarkList
Executable file
0
core-java/src/main/resources/META-INF/BenchmarkList
Executable 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
|
||||
|
@ -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 {
|
@ -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;
|
||||
|
@ -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
|
@ -7,7 +7,7 @@ import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BroadcastIntegrationTest {
|
||||
public class BroadcastLiveTest {
|
||||
private BroadcastingClient client;
|
||||
|
||||
@Test
|
@ -7,7 +7,7 @@ import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MulticastIntegrationTest {
|
||||
public class MulticastLiveTest {
|
||||
private MulticastingClient client;
|
||||
|
||||
@Test
|
@ -10,6 +10,12 @@ 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]));
|
||||
}
|
||||
|
||||
}
|
@ -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");
|
@ -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());
|
||||
}
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,18 +1,17 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamIndicesTest {
|
||||
|
||||
@Test
|
||||
public void givenArray_whenGetIndexedStrings_thenReturnListOfEvenIndexedStrings() {
|
||||
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);
|
||||
@ -21,7 +20,7 @@ public class StreamIndicesTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenGetIndexedStrings_thenReturnListOfEvenIndexedStringsVersionTwo() {
|
||||
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);
|
||||
@ -30,7 +29,7 @@ public class StreamIndicesTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenGetIndexedStrings_thenReturnListOfOddStrings() {
|
||||
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);
|
||||
@ -39,30 +38,33 @@ public class StreamIndicesTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetIndexedStrings_thenReturnListOfEvenIndexedStrings() {
|
||||
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>> 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_whenGetIndexedStrings_thenReturnListOfOddIndexedStrings() {
|
||||
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>> 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 givenArray_whenGetIndexedStrings_thenReturnListOfOddStringsVersionTwo() {
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package org.baeldung.java.diamond;
|
||||
|
||||
public class Car<T extends Engine> implements Vehicle<T> {
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package org.baeldung.java.diamond;
|
||||
|
||||
public class Diesel implements Engine {
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
System.out.println("Started Diesel...");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package org.baeldung.java.diamond;
|
||||
|
||||
public interface Engine {
|
||||
|
||||
void start();
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package org.baeldung.java.diamond;
|
||||
|
||||
public interface Vehicle<T extends Engine> {
|
||||
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
74
geotools/pom.xml
Normal file
74
geotools/pom.xml
Normal file
@ -0,0 +1,74 @@
|
||||
<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>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>geotools</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>geotools</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-shapefile</artifactId>
|
||||
<version>${geotools-shapefile.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-epsg-hsql</artifactId>
|
||||
<version>${geotools.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-swing</artifactId>
|
||||
<version>${geotools-swing.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>maven2-repository.dev.java.net</id>
|
||||
<name>Java.net repository</name>
|
||||
<url>http://download.java.net/maven/2</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>osgeo</id>
|
||||
<name>Open Source Geospatial Foundation Repository</name>
|
||||
<url>http://download.osgeo.org/webdav/geotools/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
<id>opengeo</id>
|
||||
<name>OpenGeo Maven Repository</name>
|
||||
<url>http://repo.opengeo.org</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<inherited>true</inherited>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<geotools.version>15.2</geotools.version>
|
||||
<geotools-swing.version>15.2</geotools-swing.version>
|
||||
<geotools-shapefile.version>15.2</geotools-shapefile.version>
|
||||
</properties>
|
||||
</project>
|
@ -1,12 +1,8 @@
|
||||
package com.baeldung.geotools;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.vividsolutions.jts.geom.Coordinate;
|
||||
import com.vividsolutions.jts.geom.GeometryFactory;
|
||||
import com.vividsolutions.jts.geom.Point;
|
||||
import org.geotools.data.DataUtilities;
|
||||
import org.geotools.data.DefaultTransaction;
|
||||
import org.geotools.data.Transaction;
|
||||
@ -23,9 +19,13 @@ import org.geotools.swing.data.JFileDataStoreChooser;
|
||||
import org.opengis.feature.simple.SimpleFeature;
|
||||
import org.opengis.feature.simple.SimpleFeatureType;
|
||||
|
||||
import com.vividsolutions.jts.geom.Coordinate;
|
||||
import com.vividsolutions.jts.geom.GeometryFactory;
|
||||
import com.vividsolutions.jts.geom.Point;
|
||||
import java.io.File;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ShapeFile {
|
||||
|
||||
@ -41,15 +41,105 @@ public class ShapeFile {
|
||||
|
||||
SimpleFeatureType CITY = createFeatureType();
|
||||
|
||||
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
|
||||
|
||||
addLocations(featureBuilder, collection);
|
||||
addLocations(CITY, collection);
|
||||
|
||||
File shapeFile = getNewShapeFile();
|
||||
|
||||
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
|
||||
|
||||
Map<String, Serializable> params = new HashMap<String, Serializable>();
|
||||
|
||||
ShapefileDataStore dataStore = setDataStoreParams(dataStoreFactory, params, shapeFile, CITY);
|
||||
|
||||
writeToFile(dataStore, collection);
|
||||
}
|
||||
|
||||
static SimpleFeatureType createFeatureType() {
|
||||
|
||||
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
|
||||
builder.setName("Location");
|
||||
builder.setCRS(DefaultGeographicCRS.WGS84);
|
||||
|
||||
builder.add("Location", Point.class);
|
||||
builder.length(15)
|
||||
.add("Name", String.class);
|
||||
|
||||
return builder.buildFeatureType();
|
||||
}
|
||||
|
||||
static void addLocations(SimpleFeatureType CITY, DefaultFeatureCollection collection) {
|
||||
|
||||
Map<String, List<Double>> locations = new HashMap<>();
|
||||
|
||||
double lat = 13.752222;
|
||||
double lng = 100.493889;
|
||||
addToLocationMap("Bangkok", lat, lng, locations);
|
||||
|
||||
lat = 53.083333;
|
||||
lng = -0.15;
|
||||
addToLocationMap("New York", lat, lng, locations);
|
||||
|
||||
lat = -33.925278;
|
||||
lng = 18.423889;
|
||||
addToLocationMap("Cape Town", lat, lng, locations);
|
||||
|
||||
lat = -33.859972;
|
||||
lng = 151.211111;
|
||||
addToLocationMap("Sydney", lat, lng, locations);
|
||||
|
||||
lat = 45.420833;
|
||||
lng = -75.69;
|
||||
addToLocationMap("Ottawa", lat, lng, locations);
|
||||
|
||||
lat = 30.07708;
|
||||
lng = 31.285909;
|
||||
addToLocationMap("Cairo", lat, lng, locations);
|
||||
|
||||
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
|
||||
|
||||
locations.entrySet().stream()
|
||||
.map(toFeature(CITY, geometryFactory))
|
||||
.forEach(collection::add);
|
||||
}
|
||||
|
||||
private static Function<Map.Entry<String, List<Double>>, SimpleFeature> toFeature(SimpleFeatureType CITY, GeometryFactory geometryFactory) {
|
||||
return location -> {
|
||||
Point point = geometryFactory.createPoint(
|
||||
new Coordinate(location.getValue()
|
||||
.get(0), location.getValue().get(1)));
|
||||
|
||||
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
|
||||
featureBuilder.add(point);
|
||||
featureBuilder.add(location.getKey());
|
||||
return featureBuilder.buildFeature(null);
|
||||
};
|
||||
}
|
||||
|
||||
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
|
||||
List<Double> coordinates = new ArrayList<>();
|
||||
|
||||
coordinates.add(lat);
|
||||
coordinates.add(lng);
|
||||
locations.put(name, coordinates);
|
||||
}
|
||||
|
||||
private static File getNewShapeFile() {
|
||||
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
|
||||
|
||||
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
|
||||
chooser.setDialogTitle("Save shapefile");
|
||||
chooser.setSelectedFile(new File(filePath));
|
||||
|
||||
int returnVal = chooser.showSaveDialog(null);
|
||||
|
||||
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
return chooser.getSelectedFile();
|
||||
}
|
||||
|
||||
private static ShapefileDataStore setDataStoreParams(ShapefileDataStoreFactory dataStoreFactory, Map<String, Serializable> params, File shapeFile, SimpleFeatureType CITY) throws Exception {
|
||||
params.put("url", shapeFile.toURI()
|
||||
.toURL());
|
||||
params.put("create spatial index", Boolean.TRUE);
|
||||
@ -57,6 +147,11 @@ public class ShapeFile {
|
||||
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
|
||||
dataStore.createSchema(CITY);
|
||||
|
||||
return dataStore;
|
||||
}
|
||||
|
||||
private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception {
|
||||
|
||||
// If you decide to use the TYPE type and create a Data Store with it,
|
||||
// You will need to uncomment this line to set the Coordinate Reference System
|
||||
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
|
||||
@ -73,11 +168,9 @@ public class ShapeFile {
|
||||
try {
|
||||
featureStore.addFeatures(collection);
|
||||
transaction.commit();
|
||||
|
||||
} catch (Exception problem) {
|
||||
problem.printStackTrace();
|
||||
transaction.rollback();
|
||||
|
||||
} finally {
|
||||
transaction.close();
|
||||
}
|
||||
@ -86,102 +179,5 @@ public class ShapeFile {
|
||||
System.out.println(typeName + " does not support read/write access");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static SimpleFeatureType createFeatureType() {
|
||||
|
||||
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
|
||||
builder.setName("Location");
|
||||
builder.setCRS(DefaultGeographicCRS.WGS84);
|
||||
|
||||
builder.add("Location", Point.class);
|
||||
builder.length(15)
|
||||
.add("Name", String.class);
|
||||
|
||||
SimpleFeatureType CITY = builder.buildFeatureType();
|
||||
|
||||
return CITY;
|
||||
}
|
||||
|
||||
public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) {
|
||||
|
||||
Map<String, List<Double>> locations = new HashMap<>();
|
||||
|
||||
double lat = 13.752222;
|
||||
double lng = 100.493889;
|
||||
String name = "Bangkok";
|
||||
addToLocationMap(name, lat, lng, locations);
|
||||
|
||||
lat = 53.083333;
|
||||
lng = -0.15;
|
||||
name = "New York";
|
||||
addToLocationMap(name, lat, lng, locations);
|
||||
|
||||
lat = -33.925278;
|
||||
lng = 18.423889;
|
||||
name = "Cape Town";
|
||||
addToLocationMap(name, lat, lng, locations);
|
||||
|
||||
lat = -33.859972;
|
||||
lng = 151.211111;
|
||||
name = "Sydney";
|
||||
addToLocationMap(name, lat, lng, locations);
|
||||
|
||||
lat = 45.420833;
|
||||
lng = -75.69;
|
||||
name = "Ottawa";
|
||||
addToLocationMap(name, lat, lng, locations);
|
||||
|
||||
lat = 30.07708;
|
||||
lng = 31.285909;
|
||||
name = "Cairo";
|
||||
addToLocationMap(name, lat, lng, locations);
|
||||
|
||||
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
|
||||
|
||||
for (Map.Entry<String, List<Double>> location : locations.entrySet()) {
|
||||
Point point = geometryFactory.createPoint(new Coordinate(location.getValue()
|
||||
.get(0),
|
||||
location.getValue()
|
||||
.get(1)));
|
||||
featureBuilder.add(point);
|
||||
featureBuilder.add(name);
|
||||
SimpleFeature feature = featureBuilder.buildFeature(null);
|
||||
collection.add(feature);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
|
||||
List<Double> coordinates = new ArrayList<>();
|
||||
|
||||
coordinates.add(lat);
|
||||
coordinates.add(lng);
|
||||
locations.put(name, coordinates);
|
||||
}
|
||||
|
||||
private static File getNewShapeFile() {
|
||||
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
|
||||
|
||||
|
||||
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
|
||||
chooser.setDialogTitle("Save shapefile");
|
||||
chooser.setSelectedFile(new File(filePath));
|
||||
|
||||
int returnVal = chooser.showSaveDialog(null);
|
||||
|
||||
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
File shapeFile = chooser.getSelectedFile();
|
||||
if (shapeFile.equals(filePath)) {
|
||||
System.out.println("Error: cannot replace " + filePath);
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
return shapeFile;
|
||||
}
|
||||
|
||||
}
|
@ -7,21 +7,16 @@ import org.geotools.feature.simple.SimpleFeatureBuilder;
|
||||
import org.junit.Test;
|
||||
import org.opengis.feature.simple.SimpleFeatureType;
|
||||
|
||||
public class GeoToolsUnitTestTest {
|
||||
public class GeoToolsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFeatureType_whenAddLocations_returnFeatureCollection() {
|
||||
|
||||
DefaultFeatureCollection collection = new DefaultFeatureCollection();
|
||||
|
||||
SimpleFeatureType CITY = ShapeFile.createFeatureType();
|
||||
|
||||
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
|
||||
|
||||
ShapeFile.addLocations(featureBuilder, collection);
|
||||
ShapeFile.addLocations(CITY, collection);
|
||||
|
||||
assertNotNull(collection);
|
||||
|
||||
}
|
||||
|
||||
}
|
42
javaxval/bean-validation/pom.xml
Normal file
42
javaxval/bean-validation/pom.xml
Normal file
@ -0,0 +1,42 @@
|
||||
<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>
|
||||
|
||||
<groupId>com.baeldung.beanvalidation</groupId>
|
||||
<artifactId>beanvalidation</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>beanvalidation</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>2.0.0.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>6.0.2.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.web</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>2.2.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.beanvalidation.application;
|
||||
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import com.baeldung.beanvalidation.model.User;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main( String[] args ) {
|
||||
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
User user = new User();
|
||||
user.setName("Mary");
|
||||
user.setEmail("no-email");
|
||||
user.setAge(36);
|
||||
validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage()));
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.beanvalidation.container;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.validation.constraints.Positive;
|
||||
|
||||
public class IntegerContainer {
|
||||
|
||||
private Optional<@Positive(message = "Value must be a positive integer") Integer> container = Optional.empty();
|
||||
|
||||
public void addElement(int element) {
|
||||
container = Optional.of(element);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.beanvalidation.container;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class StringContainer {
|
||||
|
||||
private List<@NotNull String> container = new ArrayList<>();
|
||||
|
||||
public void addElement(String element) {
|
||||
container.add(element);
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.beanvalidation.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import org.hibernate.validator.constraints.Email;
|
||||
|
||||
public class User implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@NotNull(message = "Name cannot be null")
|
||||
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters")
|
||||
private String name;
|
||||
|
||||
@Email(message = "Email must be a well-formed email address")
|
||||
private String email;
|
||||
|
||||
@Min(value = 1, message = "Age must not be lesser than 1")
|
||||
@Max(value = 99, message = "Age must not be greater than 99")
|
||||
private int age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
public interface EntityService {
|
||||
|
||||
public String toString();
|
||||
|
||||
public void processEntity();
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
import java.io.Serializable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import com.baeldung.beanvalidation.model.User;
|
||||
|
||||
public class UserService implements EntityService, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Valid
|
||||
private User user;
|
||||
|
||||
@NotNull(message = "FileName cannot be null")
|
||||
@Size(min = 5, max = 10, message = "FileName must be between 5 and 10 characters")
|
||||
private String fileName;
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public void setFileName(String fileName) {
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processEntity() {
|
||||
// process the user here
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserService [user=" + user + ", fileName=" + fileName + "]";
|
||||
}
|
||||
}
|
@ -0,0 +1,134 @@
|
||||
package com.baeldung.beanvalidation;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import com.baeldung.beanvalidation.container.IntegerContainer;
|
||||
import com.baeldung.beanvalidation.container.StringContainer;
|
||||
import com.baeldung.beanvalidation.model.User;
|
||||
import com.baeldung.beanvalidation.service.UserService;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ValidationTest {
|
||||
|
||||
private static Validator validator;
|
||||
private static User user;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpHibernateValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpUserInstance() {
|
||||
user = new User();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownHibernateValidatorInstance() {
|
||||
validator = null;
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownUserInstance() {
|
||||
user = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullName_whenValidated_thenMessageDescriptorForName() {
|
||||
user.setName(null);
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
assertEquals("Name cannot be null", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidEmail_whenValidated_thenMessageDescriptorforEmail() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("no-email");
|
||||
user.setAge(36);
|
||||
assertEquals("Email must be a well-formed email address", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAgeLesserThanLowerBound_whenValidated_thenMessageDescriptorforAge() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(0);
|
||||
assertEquals("Age must not be lesser than 1", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAgeGreaterThanUpperBound_whenValidated_thenMessageDescriptorforAge() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(100);
|
||||
assertEquals("Age must not be greater than 99", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullFileName_whenValidated_thenMessageDescriptorforFileName() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName(null);
|
||||
userService.setUser(user);
|
||||
assertEquals("FileName cannot be null", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameShortherThanLowerBound_whenValidated_thenMessageDescriptorforFileName() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName("");
|
||||
userService.setUser(user);
|
||||
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameLongerThanUpperBound_whenValidated_thenMessageDescriptorforFileName() {
|
||||
user.setName("Mary");
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName("waytoolongfilename");
|
||||
userService.setUser(user);
|
||||
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullUserAndNullFileName_whenValidated_thenTwoConstraintViolations() {
|
||||
user.setName(null);
|
||||
user.setEmail("mary@domain.com");
|
||||
user.setAge(36);
|
||||
UserService userService = new UserService();
|
||||
userService.setFileName(null);
|
||||
userService.setUser(user);
|
||||
Set<ConstraintViolation<UserService>> constraintViolations = validator.validate(userService);
|
||||
assertEquals(2, constraintViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullElement_whenValidated_thenOneConstraintViolation() {
|
||||
StringContainer container = new StringContainer();
|
||||
container.addElement(null);
|
||||
Set<ConstraintViolation<StringContainer>> constraintViolations = validator.validate(container);
|
||||
assertEquals(1, constraintViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNegativeInteger_whenValidated_thenOneConstraintViolation() {
|
||||
IntegerContainer container = new IntegerContainer();
|
||||
container.addElement(-1);
|
||||
Set<ConstraintViolation<IntegerContainer>> constraintViolations = validator.validate(container);
|
||||
assertEquals(1, constraintViolations.size());
|
||||
}
|
||||
}
|
@ -22,7 +22,7 @@ import com.baeldung.arquillian.Component;
|
||||
import com.baeldung.arquillian.ConvertToLowerCase;
|
||||
|
||||
@RunWith(Arquillian.class)
|
||||
public class ArquillianTest {
|
||||
public class ArquillianLiveTest {
|
||||
|
||||
@Deployment
|
||||
public static JavaArchive createDeployment() {
|
12
kotlin/src/main/kotlin/com/baeldung/kotlin/JvmSample.kt
Normal file
12
kotlin/src/main/kotlin/com/baeldung/kotlin/JvmSample.kt
Normal file
@ -0,0 +1,12 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
class JvmSample(text:String) {
|
||||
@JvmField
|
||||
val sampleText:String = text
|
||||
}
|
||||
|
||||
class CompanionSample {
|
||||
companion object {
|
||||
@JvmField val MAX_LIMIT = 20
|
||||
}
|
||||
}
|
26
kotlin/src/test/kotlin/com/baeldung/kotlin/JvmSampleTest.kt
Normal file
26
kotlin/src/test/kotlin/com/baeldung/kotlin/JvmSampleTest.kt
Normal file
@ -0,0 +1,26 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class JvmSampleTest {
|
||||
|
||||
var sample = ""
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
sample = JvmSample("Hello!").sampleText
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenField_whenCheckValue_thenMatchesValue() {
|
||||
assertTrue(sample == "Hello!")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStaticVariable_whenCheckValue_thenMatchesValue() {
|
||||
// Sample when is treated as a static variable
|
||||
assertTrue(CompanionSample.MAX_LIMIT == 20)
|
||||
}
|
||||
}
|
@ -27,11 +27,12 @@
|
||||
- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils)
|
||||
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
|
||||
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
|
||||
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
|
||||
- [Introduction to Neuroph](http://www.baeldung.com/neuroph)
|
||||
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
|
||||
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
|
||||
- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception)
|
||||
|
||||
- [Introduction to NoException](http://www.baeldung.com/no-exception)
|
||||
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
|
||||
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
|
||||
|
||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||
|
||||
|
@ -105,7 +105,6 @@
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- /Neuroph -->
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
@ -136,6 +135,11 @@
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tec.units</groupId>
|
||||
<artifactId>unit-ri</artifactId>
|
||||
<version>1.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
@ -483,20 +487,27 @@
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Retrofit -->
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-shapefile</artifactId>
|
||||
<version>${geotools.version}</version>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>retrofit</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-epsg-hsql</artifactId>
|
||||
<version>${geotools.version}</version>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>converter-gson</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.geotools</groupId>
|
||||
<artifactId>gt-swing</artifactId>
|
||||
<version>${geotools.version}</version>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>adapter-rxjava</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
<version>3.9.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
@ -519,6 +530,36 @@
|
||||
<artifactId>yarg</artifactId>
|
||||
<version>2.0.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.engio</groupId>
|
||||
<artifactId>mbassador</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jdeferred</groupId>
|
||||
<artifactId>jdeferred-core</artifactId>
|
||||
<version>1.2.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.functionaljava</groupId>
|
||||
<artifactId>functionaljava</artifactId>
|
||||
<version>4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.cache</groupId>
|
||||
<artifactId>cache-api</artifactId>
|
||||
<version>${cache.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.hazelcast</groupId>
|
||||
<artifactId>hazelcast</artifactId>
|
||||
<version>${hazelcast.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
@ -526,19 +567,6 @@
|
||||
<name>Java.net repository</name>
|
||||
<url>http://download.java.net/maven/2</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>osgeo</id>
|
||||
<name>Open Source Geospatial Foundation Repository</name>
|
||||
<url>http://download.osgeo.org/webdav/geotools/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
<id>opengeo</id>
|
||||
<name>OpenGeo Maven Repository</name>
|
||||
<url>http://repo.opengeo.org</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
@ -592,8 +620,14 @@
|
||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<geotools.version>15.2</geotools.version>
|
||||
<joda-time.version>2.9.9</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<retrofit.version>2.3.0</retrofit.version>
|
||||
<joda-time.version>2.9.9</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<protonpack.version>1.14</protonpack.version>
|
||||
<unit-ri.version>1.0.3</unit-ri.version>
|
||||
<cache.version>1.0.0</cache.version>
|
||||
<hazelcast.version>3.8.4</hazelcast.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,43 @@
|
||||
package com.baeldung.commons.io;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.monitor.FileAlterationListener;
|
||||
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class FileMonitor {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
File folder = FileUtils.getTempDirectory();
|
||||
startFileMonitor(folder);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param folder
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void startFileMonitor(File folder) throws Exception {
|
||||
FileAlterationObserver observer = new FileAlterationObserver(folder);
|
||||
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
|
||||
|
||||
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
|
||||
|
||||
@Override
|
||||
public void onFileCreate(File file) {
|
||||
// on create action
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileDelete(File file) {
|
||||
// on delete action
|
||||
}
|
||||
};
|
||||
|
||||
observer.addListener(fal);
|
||||
monitor.addObserver(observer);
|
||||
monitor.start();
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.baeldung.fj;
|
||||
|
||||
import fj.F;
|
||||
import fj.F1Functions;
|
||||
import fj.Unit;
|
||||
import fj.data.IO;
|
||||
import fj.data.IOFunctions;
|
||||
|
||||
public class FunctionalJavaIOMain {
|
||||
|
||||
public static IO<Unit> printLetters(final String s) {
|
||||
return () -> {
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
System.out.println(s.charAt(i));
|
||||
}
|
||||
return Unit.unit();
|
||||
};
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
F<String, IO<Unit>> printLetters = i -> printLetters(i);
|
||||
|
||||
IO<Unit> lowerCase = IOFunctions
|
||||
.stdoutPrintln("What's your first Name ?");
|
||||
|
||||
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
|
||||
|
||||
IO<Unit> userInput = IOFunctions.append(lowerCase, input);
|
||||
|
||||
IO<String> readInput = IOFunctions.stdinReadLine();
|
||||
|
||||
F<String, String> toUpperCase = i -> i.toUpperCase();
|
||||
|
||||
F<String, IO<Unit>> transformInput = F1Functions
|
||||
.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
|
||||
|
||||
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput,
|
||||
transformInput);
|
||||
|
||||
IO<Unit> program = IOFunctions.bind(userInput,
|
||||
nothing -> readAndPrintResult);
|
||||
|
||||
IOFunctions.toSafe(program).run();
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.fj;
|
||||
|
||||
import fj.F;
|
||||
import fj.Show;
|
||||
import fj.data.Array;
|
||||
import fj.data.List;
|
||||
import fj.data.Option;
|
||||
import fj.function.Characters;
|
||||
import fj.function.Integers;
|
||||
|
||||
public class FunctionalJavaMain {
|
||||
|
||||
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Integer> fList = List.list(3, 4, 5, 6);
|
||||
List<Boolean> evenList = fList.map(isEven);
|
||||
Show.listShow(Show.booleanShow).println(evenList);
|
||||
|
||||
fList = fList.map(i -> i + 1);
|
||||
Show.listShow(Show.intShow).println(fList);
|
||||
|
||||
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
|
||||
Array<Integer> b = a.filter(Integers.even);
|
||||
Show.arrayShow(Show.intShow).println(b);
|
||||
|
||||
Array<String> array = Array.array("Welcome", "To", "baeldung");
|
||||
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
|
||||
System.out.println(isExist);
|
||||
|
||||
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
|
||||
int sum = intArray.foldLeft(Integers.add, 0);
|
||||
System.out.println(sum);
|
||||
|
||||
Option<Integer> n1 = Option.some(1);
|
||||
Option<Integer> n2 = Option.some(2);
|
||||
|
||||
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
|
||||
|
||||
Option<Integer> result1 = n1.bind(f1);
|
||||
Option<Integer> result2 = n2.bind(f1);
|
||||
|
||||
Show.optionShow(Show.intShow).println(result1);
|
||||
Show.optionShow(Show.intShow).println(result2);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.cache.event.CacheEntryCreatedListener;
|
||||
import javax.cache.event.CacheEntryEvent;
|
||||
import javax.cache.event.CacheEntryListenerException;
|
||||
import javax.cache.event.CacheEntryUpdatedListener;
|
||||
|
||||
public class SimpleCacheEntryListener implements CacheEntryCreatedListener<String, String>, CacheEntryUpdatedListener<String, String>, Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -712657810462878763L;
|
||||
private boolean updated;
|
||||
private boolean created;
|
||||
|
||||
public boolean getUpdated() {
|
||||
return this.updated;
|
||||
}
|
||||
|
||||
public boolean getCreated() {
|
||||
return this.created;
|
||||
}
|
||||
|
||||
public void onUpdated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
|
||||
this.updated = true;
|
||||
}
|
||||
|
||||
public void onCreated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
|
||||
this.created = true;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.cache.integration.CacheLoader;
|
||||
import javax.cache.integration.CacheLoaderException;
|
||||
|
||||
public class SimpleCacheLoader implements CacheLoader<Integer, String> {
|
||||
|
||||
@Override
|
||||
public String load(Integer key) throws CacheLoaderException {
|
||||
return "fromCache" + key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Integer, String> loadAll(Iterable<? extends Integer> keys) throws CacheLoaderException {
|
||||
Map<Integer, String> data = new HashMap<>();
|
||||
for (int key : keys) {
|
||||
data.put(key, load(key));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.cache.processor.EntryProcessor;
|
||||
import javax.cache.processor.EntryProcessorException;
|
||||
import javax.cache.processor.MutableEntry;
|
||||
|
||||
public class SimpleEntryProcessor implements EntryProcessor<String, String, String>, Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -5616476363722945132L;
|
||||
|
||||
public String process(MutableEntry<String, String> entry, Object... args) throws EntryProcessorException {
|
||||
|
||||
if (entry.exists()) {
|
||||
String current = entry.getValue();
|
||||
entry.setValue(current + " - modified");
|
||||
return current;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.jdeffered;
|
||||
|
||||
import org.jdeferred.Deferred;
|
||||
import org.jdeferred.Promise;
|
||||
import org.jdeferred.impl.DeferredObject;
|
||||
|
||||
class FilterDemo {
|
||||
|
||||
private static String modifiedMsg;
|
||||
|
||||
static String filter(String msg) {
|
||||
|
||||
Deferred<String, ?, ?> d = new DeferredObject<>();
|
||||
Promise<String, ?, ?> p = d.promise();
|
||||
Promise<String, ?, ?> filtered = p.then((result) -> {
|
||||
modifiedMsg = "Hello " + result;
|
||||
});
|
||||
|
||||
filtered.done(r -> System.out.println("filtering done"));
|
||||
|
||||
d.resolve(msg);
|
||||
return modifiedMsg;
|
||||
}
|
||||
}
|
35
libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java
Normal file
35
libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java
Normal file
@ -0,0 +1,35 @@
|
||||
package com.baeldung.jdeffered;
|
||||
|
||||
import org.jdeferred.Deferred;
|
||||
import org.jdeferred.DonePipe;
|
||||
import org.jdeferred.Promise;
|
||||
import org.jdeferred.impl.DeferredObject;
|
||||
|
||||
class PipeDemo {
|
||||
|
||||
public enum Result {
|
||||
SUCCESS, FAILURE
|
||||
};
|
||||
|
||||
private static Result status;
|
||||
|
||||
static Result validate(int num) {
|
||||
Deferred<Integer, ?, ?> d = new DeferredObject<>();
|
||||
Promise<Integer, ?, ?> p = d.promise();
|
||||
|
||||
p.then((DonePipe<Integer, Integer, Exception, Void>) result -> {
|
||||
if (result < 90) {
|
||||
return new DeferredObject<Integer, Exception, Void>()
|
||||
.resolve(result);
|
||||
} else {
|
||||
return new DeferredObject<Integer, Exception, Void>()
|
||||
.reject(new Exception("Unacceptable value"));
|
||||
}
|
||||
}).done(r -> status = Result.SUCCESS)
|
||||
.fail(r -> status = Result.FAILURE);
|
||||
|
||||
d.resolve(num);
|
||||
|
||||
return status;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.jdeffered;
|
||||
|
||||
import org.jdeferred.Deferred;
|
||||
import org.jdeferred.Promise;
|
||||
import org.jdeferred.impl.DeferredObject;
|
||||
|
||||
class PromiseDemo {
|
||||
|
||||
static void startJob(String jobName) {
|
||||
|
||||
Deferred<String, String, String> deferred = new DeferredObject<>();
|
||||
Promise<String, String, String> promise = deferred.promise();
|
||||
|
||||
promise.done(result -> System.out.println("Job done"))
|
||||
.fail(rejection -> System.out.println("Job fail"))
|
||||
.progress(progress -> System.out.println("Job is in progress"))
|
||||
.always((state, result, rejection) -> System.out.println("Job execution started"));
|
||||
|
||||
deferred.resolve(jobName);
|
||||
// deferred.notify("");
|
||||
// deferred.reject("oops");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package com.baeldung.jdeffered;
|
||||
|
||||
import org.jdeferred.Deferred;
|
||||
import org.jdeferred.DeferredManager;
|
||||
import org.jdeferred.Promise;
|
||||
import org.jdeferred.impl.DefaultDeferredManager;
|
||||
import org.jdeferred.impl.DeferredObject;
|
||||
|
||||
public class ThreadSafeDemo {
|
||||
|
||||
public static void task() {
|
||||
DeferredManager dm = new DefaultDeferredManager();
|
||||
Deferred<String, String, String> deferred = new DeferredObject<>();
|
||||
Promise<String, String, String> p1 = deferred.promise();
|
||||
Promise<String, String, String> p = dm.when(p1)
|
||||
.done(r -> System.out.println("done"))
|
||||
.fail(r -> System.out.println("fail"));
|
||||
|
||||
synchronized (p) {
|
||||
while (p.isPending()) {
|
||||
try {
|
||||
p.wait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
p.waitSafely();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
deferred.resolve("Hello Baeldung");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.jdeffered.manager;
|
||||
|
||||
import org.jdeferred.Deferred;
|
||||
import org.jdeferred.DeferredManager;
|
||||
import org.jdeferred.Promise;
|
||||
import org.jdeferred.impl.DefaultDeferredManager;
|
||||
import org.jdeferred.impl.DeferredObject;
|
||||
|
||||
class DeferredManagerDemo {
|
||||
|
||||
public static void initiate() {
|
||||
Deferred<String, String, String> deferred = new DeferredObject<>();
|
||||
DeferredManager dm = new DefaultDeferredManager();
|
||||
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
|
||||
dm.when(p1, p2, p3).done((result) -> {
|
||||
System.out.println("done");
|
||||
}).fail((result) -> {
|
||||
System.out.println("fail");
|
||||
});
|
||||
deferred.resolve("Hello Baeldung");
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.jdeffered.manager;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.jdeferred.Deferred;
|
||||
import org.jdeferred.DeferredManager;
|
||||
import org.jdeferred.Promise;
|
||||
import org.jdeferred.impl.DefaultDeferredManager;
|
||||
import org.jdeferred.impl.DeferredObject;
|
||||
|
||||
class DeferredManagerWithExecutorDemo {
|
||||
|
||||
public static void initiate() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
Deferred<String, String, String> deferred = new DeferredObject<>();
|
||||
DeferredManager dm = new DefaultDeferredManager(executor);
|
||||
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
|
||||
dm.when(p1, p2, p3)
|
||||
.done(r -> System.out.println("done"))
|
||||
.fail(r -> System.out.println("fail"));
|
||||
deferred.resolve("done");
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.jdeffered.manager;
|
||||
|
||||
import org.jdeferred.DeferredManager;
|
||||
import org.jdeferred.impl.DefaultDeferredManager;
|
||||
|
||||
class SimpleDeferredManagerDemo {
|
||||
|
||||
public static void initiate() {
|
||||
DeferredManager dm = new DefaultDeferredManager();
|
||||
dm.when(() -> 1)
|
||||
.done(r -> System.out.println("done"))
|
||||
.fail(Throwable::printStackTrace);
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.mbassador;
|
||||
|
||||
public class AckMessage extends Message {
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.mbassador;
|
||||
|
||||
public class Message {
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.mbassador;
|
||||
|
||||
public class RejectMessage extends Message {
|
||||
|
||||
int code;
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.measurement;
|
||||
|
||||
import javax.measure.Quantity;
|
||||
import javax.measure.quantity.Volume;
|
||||
|
||||
public class WaterTank {
|
||||
|
||||
private Quantity<Volume> capacityMeasure;
|
||||
private double capacityDouble;
|
||||
|
||||
public void setCapacityMeasure(Quantity<Volume> capacityMeasure) {
|
||||
this.capacityMeasure = capacityMeasure;
|
||||
}
|
||||
|
||||
public void setCapacityDouble(double capacityDouble) {
|
||||
this.capacityDouble = capacityDouble;
|
||||
}
|
||||
|
||||
public Quantity<Volume> getCapacityMeasure() {
|
||||
return capacityMeasure;
|
||||
}
|
||||
|
||||
public double getCapacityDouble() {
|
||||
return capacityDouble;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.protonpack;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.codepoetics.protonpack.collectors.CollectorUtils.maxBy;
|
||||
import static com.codepoetics.protonpack.collectors.CollectorUtils.minBy;
|
||||
|
||||
public class CollectorUtilsExample {
|
||||
|
||||
public void minMaxProjectionCollector() {
|
||||
Stream<String> integerStream = Stream.of("a", "bb", "ccc", "1");
|
||||
|
||||
Optional<String> max = integerStream.collect(maxBy(String::length));
|
||||
Optional<String> min = integerStream.collect(minBy(String::length));
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
package com.baeldung.protonpack;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import com.codepoetics.protonpack.StreamUtils;
|
||||
import com.codepoetics.protonpack.selectors.Selectors;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
public class StreamUtilsExample {
|
||||
|
||||
public void createInfiniteIndex() {
|
||||
LongStream indices = StreamUtils.indices();
|
||||
}
|
||||
|
||||
public void zipAStreamWithIndex() {
|
||||
Stream<String> source = Stream.of("Foo", "Bar", "Baz");
|
||||
List<Indexed<String>> zipped = StreamUtils
|
||||
.zipWithIndex(source)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void zipAPairOfStreams() {
|
||||
Stream<String> streamA = Stream.of("A", "B", "C");
|
||||
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
|
||||
|
||||
List<String> zipped = StreamUtils
|
||||
.zip(streamA, streamB, (a, b) -> a + " is for " + b)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void zipThreeStreams() {
|
||||
Stream<String> streamA = Stream.of("A", "B", "C");
|
||||
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
|
||||
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
|
||||
|
||||
List<String> zipped = StreamUtils
|
||||
.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void mergeThreeStreams() {
|
||||
Stream<String> streamA = Stream.of("A", "B", "C");
|
||||
Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date");
|
||||
Stream<String> streamC = Stream.of("fritter", "split", "cake", "roll", "pastry");
|
||||
|
||||
Stream<List<String>> merged = StreamUtils.mergeToList(streamA, streamB, streamC);
|
||||
}
|
||||
|
||||
public void interleavingStreamsUsingRoundRobin() {
|
||||
Stream<String> streamA = Stream.of("Peter", "Paul", "Mary");
|
||||
Stream<String> streamB = Stream.of("A", "B", "C", "D", "E");
|
||||
Stream<String> streamC = Stream.of("foo", "bar", "baz", "xyzzy");
|
||||
|
||||
Stream<String> interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC);
|
||||
}
|
||||
|
||||
public void takeWhileAndTakeUntilStream() {
|
||||
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
|
||||
Stream<Integer> finiteIntsWhileLessThan10 = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
|
||||
Stream<Integer> finiteIntsUntilGreaterThan10 = StreamUtils.takeUntil(infiniteInts, i -> i > 10);
|
||||
}
|
||||
|
||||
public void skipWhileAndSkipUntilStream() {
|
||||
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
Stream<Integer> skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4);
|
||||
Stream<Integer> skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4);
|
||||
}
|
||||
|
||||
public void unfoldStream() {
|
||||
Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty());
|
||||
}
|
||||
|
||||
public void windowedStream() {
|
||||
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
List<List<Integer>> windows = StreamUtils
|
||||
.windowed(integerStream, 2)
|
||||
.collect(toList());
|
||||
List<List<Integer>> windowsWithSkipIndex = StreamUtils
|
||||
.windowed(integerStream, 3, 2)
|
||||
.collect(toList());
|
||||
List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils
|
||||
.windowed(integerStream, 2, 2, true)
|
||||
.collect(toList());
|
||||
|
||||
}
|
||||
|
||||
public void groupRunsStreams() {
|
||||
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
|
||||
|
||||
List<List<Integer>> runs = StreamUtils
|
||||
.groupRuns(integerStream)
|
||||
.collect(toList());
|
||||
}
|
||||
|
||||
public void aggreagateOnBiElementPredicate() {
|
||||
Stream<String> stream = Stream.of("a1", "b1", "b2", "c1");
|
||||
Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
|
||||
public interface GitHubBasicApi {
|
||||
|
||||
/**
|
||||
* List GitHub repositories of user
|
||||
* @param user GitHub Account
|
||||
* @return GitHub repositories
|
||||
*/
|
||||
@GET("users/{user}/repos")
|
||||
Call<List<Repository>> listRepos(@Path("user") String user);
|
||||
|
||||
/**
|
||||
* List Contributors of a GitHub Repository
|
||||
* @param user GitHub Account
|
||||
* @param repo GitHub Repository
|
||||
* @return GitHub Repository Contributors
|
||||
*/
|
||||
@GET("repos/{user}/{repo}/contributors")
|
||||
Call<List<Contributor>> listRepoContributors(
|
||||
@Path("user") String user,
|
||||
@Path("repo") String repo);
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
public class GitHubBasicApp {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
String userName = "eugenp";
|
||||
List<String> topContributors = new GitHubBasicService()
|
||||
.getTopContributors(userName);
|
||||
topContributors.forEach(System.out::println);
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
class GitHubBasicService {
|
||||
|
||||
private GitHubBasicApi gitHubApi;
|
||||
|
||||
GitHubBasicService() {
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://api.github.com/")
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
|
||||
gitHubApi = retrofit.create(GitHubBasicApi.class);
|
||||
}
|
||||
|
||||
List<String> getTopContributors(String userName) throws IOException {
|
||||
List<Repository> repos = gitHubApi
|
||||
.listRepos(userName)
|
||||
.execute()
|
||||
.body();
|
||||
|
||||
repos = repos != null ? repos : Collections.emptyList();
|
||||
|
||||
return repos.stream()
|
||||
.flatMap(repo -> getContributors(userName, repo))
|
||||
.sorted((a, b) -> b.getContributions() - a.getContributions())
|
||||
.map(Contributor::getName)
|
||||
.distinct()
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Stream<Contributor> getContributors(String userName, Repository repo) {
|
||||
List<Contributor> contributors = null;
|
||||
try {
|
||||
contributors = gitHubApi
|
||||
.listRepoContributors(userName, repo.getName())
|
||||
.execute()
|
||||
.body();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
contributors = contributors != null ? contributors : Collections.emptyList();
|
||||
|
||||
return contributors.stream()
|
||||
.filter(c -> c.getContributions() > 100);
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.retrofit.models;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
public class Contributor {
|
||||
|
||||
@SerializedName("login")
|
||||
private String name;
|
||||
|
||||
private Integer contributions;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public Integer getContributions() {
|
||||
return contributions;
|
||||
}
|
||||
public void setContributions(Integer contributions) {
|
||||
this.contributions = contributions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Contributer [name=" + name + ", contributions=" + contributions + "]";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.retrofit.models;
|
||||
|
||||
public class Repository {
|
||||
|
||||
private String name;
|
||||
|
||||
private String description;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Repository [name=" + name + ", description=" + description + "]";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
import rx.Observable;
|
||||
|
||||
public interface GitHubRxApi {
|
||||
|
||||
/**
|
||||
* List GitHub repositories of user
|
||||
* @param user GitHub Account
|
||||
* @return GitHub repositories
|
||||
*/
|
||||
@GET("users/{user}/repos")
|
||||
Observable<List<Repository>> listRepos(@Path("user") String user);
|
||||
|
||||
/**
|
||||
* List Contributors of a GitHub Repository
|
||||
* @param user GitHub Account
|
||||
* @param repo GitHub Repository
|
||||
* @return GitHub Repository Contributors
|
||||
*/
|
||||
@GET("repos/{user}/{repo}/contributors")
|
||||
Observable<List<Contributor>> listRepoContributors(
|
||||
@Path("user") String user,
|
||||
@Path("repo") String repo);
|
||||
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class GitHubRxApp {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
String userName = "eugenp";
|
||||
new GitHubRxService().getTopContributors(userName)
|
||||
.subscribe(System.out::println);
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
import rx.Observable;
|
||||
|
||||
class GitHubRxService {
|
||||
|
||||
private GitHubRxApi gitHubApi;
|
||||
|
||||
GitHubRxService() {
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://api.github.com/")
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
|
||||
.build();
|
||||
|
||||
gitHubApi = retrofit.create(GitHubRxApi.class);
|
||||
}
|
||||
|
||||
Observable<String> getTopContributors(String userName) {
|
||||
return gitHubApi.listRepos(userName)
|
||||
.flatMapIterable(x -> x)
|
||||
.flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName()))
|
||||
.flatMapIterable(x -> x)
|
||||
.filter(c -> c.getContributions() > 100)
|
||||
.sorted((a, b) -> b.getContributions() - a.getContributions())
|
||||
.map(Contributor::getName)
|
||||
.distinct();
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
import java.io.IOException;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.logging.HttpLoggingInterceptor;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class GitHubServiceGenerator {
|
||||
|
||||
private static final String BASE_URL = "https://api.github.com/";
|
||||
|
||||
private static Retrofit.Builder builder
|
||||
= new Retrofit.Builder()
|
||||
.baseUrl(BASE_URL)
|
||||
.addConverterFactory(GsonConverterFactory.create());
|
||||
|
||||
private static Retrofit retrofit = builder.build();
|
||||
|
||||
private static OkHttpClient.Builder httpClient
|
||||
= new OkHttpClient.Builder();
|
||||
|
||||
private static HttpLoggingInterceptor logging
|
||||
= new HttpLoggingInterceptor()
|
||||
.setLevel(HttpLoggingInterceptor.Level.BASIC);
|
||||
|
||||
public static <S> S createService(Class<S> serviceClass) {
|
||||
if (!httpClient.interceptors().contains(logging)) {
|
||||
httpClient.addInterceptor(logging);
|
||||
builder.client(httpClient.build());
|
||||
retrofit = builder.build();
|
||||
}
|
||||
return retrofit.create(serviceClass);
|
||||
}
|
||||
|
||||
public static <S> S createService(Class<S> serviceClass, final String token) {
|
||||
if (token != null) {
|
||||
httpClient.interceptors().clear();
|
||||
httpClient.addInterceptor(new Interceptor() {
|
||||
@Override
|
||||
public Response intercept(Interceptor.Chain chain) throws IOException {
|
||||
Request original = chain.request();
|
||||
Request.Builder builder = original.newBuilder()
|
||||
.header("Authorization", token);
|
||||
Request request = builder.build();
|
||||
return chain.proceed(request);
|
||||
}
|
||||
});
|
||||
builder.client(httpClient.build());
|
||||
retrofit = builder.build();
|
||||
}
|
||||
return retrofit.create(serviceClass);
|
||||
}
|
||||
|
||||
}
|
49
libraries/src/main/java/com/baeldung/retrofitguide/Main.java
Normal file
49
libraries/src/main/java/com/baeldung/retrofitguide/Main.java
Normal file
@ -0,0 +1,49 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
import java.io.IOException;
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
//Manual creation
|
||||
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://api.github.com/")
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.client(httpClient.build())
|
||||
.build();
|
||||
UserService service = retrofit.create(UserService.class);
|
||||
//Using GitHubServiceGenerator
|
||||
service = GitHubServiceGenerator.createService(UserService.class);
|
||||
Call<User> callSync = service.getUser("eugenp");
|
||||
Call<User> callAsync = service.getUser("eugenp");
|
||||
|
||||
try {
|
||||
Response<User> response = callSync.execute();
|
||||
User user = response.body();
|
||||
System.out.println(user);
|
||||
} catch (IOException ex) {
|
||||
}
|
||||
|
||||
// Execute the call asynchronously. Get a positive or negative callback.
|
||||
callAsync.enqueue(new Callback<User>() {
|
||||
@Override
|
||||
public void onResponse(Call<User> call, Response<User> response) {
|
||||
User user = response.body();
|
||||
System.out.println(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<User> call, Throwable throwable) {
|
||||
System.out.println(throwable);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
65
libraries/src/main/java/com/baeldung/retrofitguide/User.java
Normal file
65
libraries/src/main/java/com/baeldung/retrofitguide/User.java
Normal file
@ -0,0 +1,65 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
public class User {
|
||||
|
||||
private String login;
|
||||
private long id;
|
||||
private String url;
|
||||
private String company;
|
||||
private String blog;
|
||||
private String email;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = company;
|
||||
}
|
||||
|
||||
public String getBlog() {
|
||||
return blog;
|
||||
}
|
||||
|
||||
public void setBlog(String blog) {
|
||||
this.blog = blog;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
import java.util.List;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
import retrofit2.http.Query;
|
||||
|
||||
public interface UserService {
|
||||
|
||||
@GET("/users")
|
||||
public Call<List<User>> getUsers(@Query("per_page") int per_page, @Query("page") int page);
|
||||
|
||||
@GET("/users/{username}")
|
||||
public Call<User> getUser(@Path("username") String username);
|
||||
|
||||
}
|
@ -0,0 +1,151 @@
|
||||
package com.baeldung.commons.io;
|
||||
|
||||
import org.apache.commons.io.FileSystemUtils;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.io.IOCase;
|
||||
import org.apache.commons.io.comparator.PathFileComparator;
|
||||
import org.apache.commons.io.comparator.SizeFileComparator;
|
||||
import org.apache.commons.io.filefilter.AndFileFilter;
|
||||
import org.apache.commons.io.filefilter.NameFileFilter;
|
||||
import org.apache.commons.io.filefilter.SuffixFileFilter;
|
||||
import org.apache.commons.io.filefilter.WildcardFileFilter;
|
||||
import org.apache.commons.io.input.TeeInputStream;
|
||||
import org.apache.commons.io.output.TeeOutputStream;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
public class CommonsIOUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData()
|
||||
throws IOException {
|
||||
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
File file = FileUtils.getFile(getClass().getClassLoader()
|
||||
.getResource("fileTest.txt")
|
||||
.getPath());
|
||||
File tempDir = FileUtils.getTempDirectory();
|
||||
FileUtils.copyFileToDirectory(file, tempDir);
|
||||
File newTempFile = FileUtils.getFile(tempDir, file.getName());
|
||||
String data = FileUtils.readFileToString(newTempFile,
|
||||
Charset.defaultCharset());
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileNameUtils_thenshowdifferentFileOperations()
|
||||
throws IOException {
|
||||
|
||||
String path = getClass().getClassLoader()
|
||||
.getResource("fileTest.txt")
|
||||
.getPath();
|
||||
|
||||
String fullPath = FilenameUtils.getFullPath(path);
|
||||
String extension = FilenameUtils.getExtension(path);
|
||||
String baseName = FilenameUtils.getBaseName(path);
|
||||
|
||||
System.out.println("full path" + fullPath);
|
||||
System.out.println("Extension" + extension);
|
||||
System.out.println("Base name" + baseName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileSystemUtils_thenDriveFreeSpace()
|
||||
throws IOException {
|
||||
|
||||
long freeSpace = FileSystemUtils.freeSpaceKb("/");
|
||||
}
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
@Test
|
||||
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams()
|
||||
throws IOException {
|
||||
|
||||
final String str = "Hello World.";
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
|
||||
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
|
||||
|
||||
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2);
|
||||
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
|
||||
|
||||
Assert.assertEquals(str, String.valueOf(outputStream1));
|
||||
Assert.assertEquals(str, String.valueOf(outputStream2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt()
|
||||
throws IOException {
|
||||
|
||||
final String testFile = "fileTest.txt";
|
||||
|
||||
String path = getClass().getClassLoader()
|
||||
.getResource(testFile)
|
||||
.getPath();
|
||||
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
|
||||
|
||||
String[] possibleNames = { "NotThisOne", testFile };
|
||||
|
||||
Assert.assertEquals(testFile,
|
||||
dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt()
|
||||
throws IOException {
|
||||
|
||||
String path = getClass().getClassLoader()
|
||||
.getResource("fileTest.txt")
|
||||
.getPath();
|
||||
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
|
||||
|
||||
Assert.assertEquals("sample.txt",
|
||||
dir.list(new AndFileFilter(
|
||||
new WildcardFileFilter("*ple*", IOCase.INSENSITIVE),
|
||||
new SuffixFileFilter("txt")))[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt()
|
||||
throws IOException {
|
||||
|
||||
PathFileComparator pathFileComparator = new PathFileComparator(
|
||||
IOCase.INSENSITIVE);
|
||||
String path = FilenameUtils.getFullPath(getClass().getClassLoader()
|
||||
.getResource("fileTest.txt")
|
||||
.getPath());
|
||||
File dir = new File(path);
|
||||
File[] files = dir.listFiles();
|
||||
|
||||
pathFileComparator.sort(files);
|
||||
|
||||
Assert.assertEquals("aaa.txt", files[0].getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSizeFileComparator_thenLargerFile()
|
||||
throws IOException {
|
||||
|
||||
SizeFileComparator sizeFileComparator = new SizeFileComparator();
|
||||
File largerFile = FileUtils.getFile(getClass().getClassLoader()
|
||||
.getResource("fileTest.txt")
|
||||
.getPath());
|
||||
File smallerFile = FileUtils.getFile(getClass().getClassLoader()
|
||||
.getResource("sample.txt")
|
||||
.getPath());
|
||||
|
||||
int i = sizeFileComparator.compare(largerFile, smallerFile);
|
||||
|
||||
Assert.assertTrue(i > 0);
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
package com.baeldung.fj;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import fj.F;
|
||||
import fj.data.Array;
|
||||
import fj.data.List;
|
||||
import fj.data.Option;
|
||||
import fj.function.Characters;
|
||||
import fj.function.Integers;
|
||||
|
||||
public class FunctionalJavaTest {
|
||||
|
||||
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
|
||||
|
||||
@Test
|
||||
public void calculateEvenNumbers_givenIntList_returnTrue() {
|
||||
List<Integer> fList = List.list(3, 4, 5, 6);
|
||||
List<Boolean> evenList = fList.map(isEven);
|
||||
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
|
||||
List<Boolean> evenListFalseResult = List.list(true, false, false, true);
|
||||
assertEquals(evenList.equals(evenListTrueResult), true);
|
||||
assertEquals(evenList.equals(evenListFalseResult), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapList_givenIntList_returnResult() {
|
||||
List<Integer> fList = List.list(3, 4, 5, 6);
|
||||
fList = fList.map(i -> i + 100);
|
||||
List<Integer> resultList = List.list(103, 104, 105, 106);
|
||||
List<Integer> falseResultList = List.list(15, 504, 105, 106);
|
||||
assertEquals(fList.equals(resultList), true);
|
||||
assertEquals(fList.equals(falseResultList), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterList_givenIntList_returnResult() {
|
||||
Array<Integer> array = Array.array(3, 4, 5, 6);
|
||||
Array<Integer> filteredArray = array.filter(Integers.even);
|
||||
Array<Integer> result = Array.array(4, 6);
|
||||
Array<Integer> wrongResult = Array.array(3, 5);
|
||||
assertEquals(filteredArray.equals(result), true);
|
||||
assertEquals(filteredArray.equals(wrongResult), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkForLowerCase_givenStringArray_returnResult() {
|
||||
Array<String> array = Array.array("Welcome", "To", "baeldung");
|
||||
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
|
||||
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
|
||||
Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
|
||||
assertEquals(isExist, true);
|
||||
assertEquals(isExist2, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOptions_givenOptions_returnResult() {
|
||||
Option<Integer> n1 = Option.some(1);
|
||||
Option<Integer> n2 = Option.some(2);
|
||||
|
||||
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
|
||||
|
||||
Option<Integer> result1 = n1.bind(f1);
|
||||
Option<Integer> result2 = n2.bind(f1);
|
||||
|
||||
assertEquals(result1, Option.none());
|
||||
assertEquals(result2, Option.some(102));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void foldLeft_givenArray_returnResult() {
|
||||
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
|
||||
int sum = intArray.foldLeft(Integers.add, 0);
|
||||
assertEquals(sum, 260);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.FactoryBuilder;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CacheLoaderTest {
|
||||
|
||||
private static final String CACHE_NAME = "SimpleCache";
|
||||
|
||||
private Cache<Integer, String> cache;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true)
|
||||
.setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
|
||||
this.cache = cacheManager.createCache("SimpleCache", config);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider()
|
||||
.getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadingFromStorage_thenCorrect() {
|
||||
for (int i = 1; i < 4; i++) {
|
||||
String value = cache.get(i);
|
||||
assertEquals("fromCache" + i, value);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EntryProcessorTest {
|
||||
|
||||
private static final String CACHE_NAME = "MyCache";
|
||||
|
||||
private Cache<String, String> cache;
|
||||
|
||||
@Before
|
||||
public void instantiateCache() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<>();
|
||||
this.cache = cacheManager.createCache(CACHE_NAME, config);
|
||||
this.cache.put("key", "value");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider()
|
||||
.getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyValue_thenCorrect() {
|
||||
this.cache.invoke("key", new SimpleEntryProcessor());
|
||||
assertEquals("value - modified", cache.get("key"));
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.FactoryBuilder;
|
||||
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EventListenerTest {
|
||||
|
||||
private static final String CACHE_NAME = "MyCache";
|
||||
|
||||
private Cache<String, String> cache;
|
||||
private SimpleCacheEntryListener listener;
|
||||
private MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<String, String>();
|
||||
this.cache = cacheManager.createCache("MyCache", config);
|
||||
this.listener = new SimpleCacheEntryListener();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider()
|
||||
.getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRunEvent_thenCorrect() throws InterruptedException {
|
||||
this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder
|
||||
.factoryOf(this.listener), null, false, true);
|
||||
this.cache.registerCacheEntryListener(this.listenerConfiguration);
|
||||
|
||||
assertEquals(false, this.listener.getCreated());
|
||||
|
||||
this.cache.put("key", "value");
|
||||
assertEquals(true, this.listener.getCreated());
|
||||
assertEquals(false, this.listener.getUpdated());
|
||||
|
||||
this.cache.put("key", "newValue");
|
||||
assertEquals(true, this.listener.getUpdated());
|
||||
}
|
||||
|
||||
}
|
27
libraries/src/test/java/com/baeldung/jcache/JCacheTest.java
Normal file
27
libraries/src/test/java/com/baeldung/jcache/JCacheTest.java
Normal file
@ -0,0 +1,27 @@
|
||||
package com.baeldung.jcache;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
import javax.cache.Caching;
|
||||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JCacheTest {
|
||||
|
||||
@Test
|
||||
public void instantiateCache() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<>();
|
||||
Cache<String, String> cache = cacheManager.createCache("simpleCache", config);
|
||||
cache.put("key1", "value1");
|
||||
cache.put("key2", "value2");
|
||||
assertEquals("value1", cache.get("key1"));
|
||||
assertEquals("value2", cache.get("key2"));
|
||||
cacheManager.close();
|
||||
}
|
||||
}
|
26
libraries/src/test/java/com/baeldung/jdeffered/AppTest.java
Normal file
26
libraries/src/test/java/com/baeldung/jdeffered/AppTest.java
Normal file
@ -0,0 +1,26 @@
|
||||
package com.baeldung.jdeffered;
|
||||
|
||||
import com.baeldung.jdeffered.PipeDemo.Result;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AppTest {
|
||||
|
||||
@Test
|
||||
public void givenJob_expectPromise() {
|
||||
PromiseDemo.startJob("Baeldung Job");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMsg_expectModifiedMsg() {
|
||||
String msg = FilterDemo.filter("Baeldung");
|
||||
assertEquals("Hello Baeldung", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNum_validateNum_expectStatus() {
|
||||
Result result = PipeDemo.validate(80);
|
||||
assertEquals(result, Result.SUCCESS);
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.mbassador;
|
||||
|
||||
import net.engio.mbassy.bus.MBassador;
|
||||
import net.engio.mbassy.listener.Handler;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class MBassadorAsyncDispatchTest {
|
||||
|
||||
private MBassador dispatcher = new MBassador<String>();
|
||||
private String testString;
|
||||
private AtomicBoolean ready = new AtomicBoolean(false);
|
||||
|
||||
@Before
|
||||
public void prepareTests() {
|
||||
dispatcher.subscribe(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsyncDispatched_thenMessageReceived() {
|
||||
dispatcher.post("foobar").asynchronously();
|
||||
await().untilAtomic(ready, equalTo(true));
|
||||
assertNotNull(testString);
|
||||
}
|
||||
|
||||
@Handler
|
||||
public void handleStringMessage(String message) {
|
||||
this.testString = message;
|
||||
ready.set(true);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user