This commit is contained in:
chirag d 2020-02-15 21:45:37 +05:30
commit 1016af812a
261 changed files with 26055 additions and 450 deletions

1
.gitignore vendored
View File

@ -65,6 +65,7 @@ core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv
ninja/devDb.mv.db
**/node_modules/
**/dist

View File

@ -13,4 +13,11 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)

View File

@ -0,0 +1,141 @@
package com.baeldung.algorithms.balancedbinarytree;
public class AVLTree {
public class Node {
int key;
int height;
Node left;
Node right;
Node(int key) {
this.key = key;
}
}
private Node root;
public Node find(int key) {
Node current = root;
while (current != null) {
if (current.key == key) {
break;
}
current = current.key < key ? current.right : current.left;
}
return current;
}
public void insert(int key) {
root = insert(root, key);
}
public void delete(int key) {
root = delete(root, key);
}
public Node getRoot() {
return root;
}
public int height() {
return root == null ? -1 : root.height;
}
private Node insert(Node node, int key) {
if (node == null) {
return new Node(key);
} else if (node.key > key) {
node.left = insert(node.left, key);
} else if (node.key < key) {
node.right = insert(node.right, key);
} else {
throw new RuntimeException("duplicate Key!");
}
return rebalance(node);
}
private Node delete(Node node, int key) {
if (node == null) {
return node;
} else if (node.key > key) {
node.left = delete(node.left, key);
} else if (node.key < key) {
node.right = delete(node.right, key);
} else {
if (node.left == null || node.right == null) {
node = (node.left == null) ? node.right : node.left;
} else {
Node mostLeftChild = mostLeftChild(node.right);
node.key = mostLeftChild.key;
node.right = delete(node.right, node.key);
}
}
if (node != null) {
node = rebalance(node);
}
return node;
}
private Node mostLeftChild(Node node) {
Node current = node;
/* loop down to find the leftmost leaf */
while (current.left != null) {
current = current.left;
}
return current;
}
private Node rebalance(Node z) {
updateHeight(z);
int balance = getBalance(z);
if (balance > 1) {
if (height(z.right.right) > height(z.right.left)) {
z = rotateLeft(z);
} else {
z.right = rotateRight(z.right);
z = rotateLeft(z);
}
} else if (balance < -1) {
if (height(z.left.left) > height(z.left.right)) {
z = rotateRight(z);
} else {
z.left = rotateLeft(z.left);
z = rotateRight(z);
}
}
return z;
}
private Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x);
return x;
}
private Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
return x;
}
private void updateHeight(Node n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private int height(Node n) {
return n == null ? -1 : n.height;
}
public int getBalance(Node n) {
return (n == null) ? 0 : height(n.right) - height(n.left);
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.algorithms.balancedbinarytree;
import org.junit.Assert;
import org.junit.Test;
public class AVLTreeUnitTest {
@Test
public void givenEmptyTree_whenHeightCalled_shouldReturnMinus1() {
AVLTree tree = new AVLTree();
Assert.assertEquals(-1, tree.height());
}
@Test
public void givenEmptyTree_whenInsertCalled_heightShouldBeZero() {
AVLTree tree = new AVLTree();
tree.insert(1);
Assert.assertEquals(0, tree.height());
}
@Test
public void givenEmptyTree_whenInsertCalled_treeShouldBeAvl() {
AVLTree tree = new AVLTree();
tree.insert(1);
Assert.assertTrue(isAVL(tree));
}
@Test
public void givenSampleTree_whenInsertCalled_treeShouldBeAvl() {
AVLTree tree = getSampleAVLTree();
int newKey = 11;
tree.insert(newKey);
Assert.assertTrue(isAVL(tree));
}
@Test
public void givenSampleTree_whenFindExistingKeyCalled_shouldReturnMatchedNode() {
AVLTree tree = getSampleAVLTree();
int existingKey = 2;
AVLTree.Node result = tree.find(existingKey);
Assert.assertEquals(result.key, existingKey);
}
@Test
public void givenSampleTree_whenFindNotExistingKeyCalled_shouldReturnNull() {
AVLTree tree = getSampleAVLTree();
int notExistingKey = 11;
AVLTree.Node result = tree.find(notExistingKey);
Assert.assertNull(result);
}
@Test
public void givenEmptyTree_whenDeleteCalled_treeShouldBeAvl() {
AVLTree tree = new AVLTree();
tree.delete(1);
Assert.assertTrue(isAVL(tree));
}
@Test
public void givenSampleTree_whenDeleteCalled_treeShouldBeAvl() {
AVLTree tree = getSampleAVLTree();
tree.delete(1);
Assert.assertTrue(isAVL(tree, tree.getRoot()));
}
private boolean isAVL(AVLTree tree) {
return isAVL(tree, tree.getRoot());
}
private boolean isAVL(AVLTree tree, AVLTree.Node node) {
if ( node == null )
return true;
int balance = tree.getBalance(node);
return (balance <= 1 && balance >= -1) && isAVL(tree, node.left) && isAVL(tree, node.right);
}
private AVLTree getSampleAVLTree() {
AVLTree avlTree = new AVLTree();
for (int i = 0; i < 10; i++)
avlTree.insert(i);
return avlTree;
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)

View File

@ -6,3 +6,6 @@ This module contains articles about Apache POI
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://github.com/eugenp/tutorials/tree/master/apache-poi)

View File

@ -1,4 +1,4 @@
package com.baeldung.poi.excel;
package com.baeldung.poi.excel.merge;
import static org.junit.Assert.assertEquals;

View File

@ -3,3 +3,5 @@
This module contains articles about Apache RocketMQ
### Relevant Articles:
- [Apache RocketMQ with Spring Boot](https://www.baeldung.com/apache-rocketmq-spring-boot)

3
aws-reactive/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [AWS S3 with Java Reactive Support](https://www.baeldung.com/java-aws-s3-reactive)

View File

@ -13,3 +13,4 @@ This module contains articles about Java 11 core features
- [Guide to jlink](https://www.baeldung.com/jlink)
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections)
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)

View File

@ -1,3 +1,4 @@
### Relevant articles:
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [New Java 13 Features](https://www.baeldung.com/java-13-new-features)

View File

@ -13,4 +13,5 @@ This module contains articles about Java arrays
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list)
- [Arrays.sort vs Arrays.parallelSort](https://www.baeldung.com/java-arrays-sort-vs-parallelsort)
- [[<-- Prev]](/core-java-modules/core-java-arrays)

View File

@ -69,7 +69,7 @@ public class SortComparisonUnitTest {
}
@Test
public void givenArrayOfIntegers_whenUsingArraysSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
public void givenArrayOfIntegers_whenUsingArraysSortWithRange_thenSortRangeOfArrayAsc() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };
@ -89,7 +89,7 @@ public class SortComparisonUnitTest {
}
@Test
public void givenArrayOfIntegers_whenUsingArraysParallelSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
public void givenArrayOfIntegers_whenUsingArraysParallelSortWithRange_thenSortRangeOfArrayAsc() {
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };

View File

@ -8,4 +8,6 @@ This module contains articles about advanced topics about multithreading with co
- [Common Concurrency Pitfalls in Java](https://www.baeldung.com/java-common-concurrency-pitfalls)
- [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler)
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
- [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing)
- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -4,7 +4,7 @@ package com.baeldung.concurrent.volatilekeyword;
public class SharedObject {
private volatile int count=0;
void increamentCount(){
void incrementCount(){
count++;
}
public int getCount(){

View File

@ -10,7 +10,7 @@ public class SharedObjectManualTest {
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writer = new Thread(() -> sharedObject.increamentCount());
Thread writer = new Thread(() -> sharedObject.incrementCount());
writer.start();
Thread.sleep(100);
@ -31,11 +31,11 @@ public class SharedObjectManualTest {
@Test
public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writerOne = new Thread(() -> sharedObject.increamentCount());
Thread writerOne = new Thread(() -> sharedObject.incrementCount());
writerOne.start();
Thread.sleep(100);
Thread writerTwo = new Thread(() -> sharedObject.increamentCount());
Thread writerTwo = new Thread(() -> sharedObject.incrementCount());
writerTwo.start();
Thread.sleep(100);

View File

@ -6,4 +6,5 @@ This module contains articles about date operations in Java.
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)

View File

@ -5,3 +5,5 @@ This module contains articles about core java exceptions
### Relevant Articles:
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
- [Wrapping vs Rethrowing Exceptions in Java](https://www.baeldung.com/java-wrapping-vs-rethrowing-exceptions)
- [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception)

View File

@ -0,0 +1,32 @@
package com.baeldung.socketexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
return in.readLine();
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.socketexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg = in.readLine();
if (msg.contains("hi"))
out.println("hi");
else
out.println("didn't understand");
close();
stop();
} catch (IOException e) {
}
}
private void close() throws IOException {
in.close();
out.close();
}
private void stop() throws IOException {
clientSocket.close();
serverSocket.close();
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.socketexception;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.Executors;
import org.junit.BeforeClass;
import org.junit.Test;
public class SocketExceptionHandlingUnitTest {
@BeforeClass
public static void runServer() throws IOException, InterruptedException {
Executors.newSingleThreadExecutor()
.submit(() -> new SocketServer().start(6699));
Thread.sleep(100);
}
@Test
public void givenRunningServer_whenConnectToClosedSocket_thenHandleException() throws IOException {
SocketClient client = new SocketClient();
client.startConnection("127.0.0.1", 6699);
try {
client.sendMessage("hi");
client.sendMessage("hi again");
} catch (SocketException e) {
client.stopConnection();
}
}
}

View File

@ -6,4 +6,7 @@ This module contains articles about core features in the Java language
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments)
- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class)
- [Java Default Parameters Using Method Overloading](https://www.baeldung.com/java-default-parameters-method-overloading)
- [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values)
- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword)
- [[<-- Prev]](/core-java-modules/core-java-lang)

View File

@ -0,0 +1,27 @@
package com.baeldung.headlessmode;
import java.awt.GraphicsEnvironment;
import javax.swing.JOptionPane;
public class FlexibleApp {
public static final int HEADLESS = 0;
public static final int HEADED = 1;
public FlexibleApp() {
if (GraphicsEnvironment.isHeadless()) {
System.out.println("Hello World");
} else {
JOptionPane.showMessageDialog(null, "Hello World");
}
}
public static int iAmFlexible() {
if (GraphicsEnvironment.isHeadless()) {
return HEADLESS;
} else {
return HEADED;
}
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.headlessmode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.awt.Canvas;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
public class HeadlessModeUnitTest {
private static final String IN_FILE = "/product.png";
private static final String OUT_FILE = System.getProperty("java.io.tmpdir") + "/product.jpg";
private static final String FORMAT = "jpg";
@Before
public void setUpHeadlessMode() {
System.setProperty("java.awt.headless", "true");
}
@Test
public void whenJavaAwtHeadlessSetToTrue_thenIsHeadlessReturnsTrue() {
assertThat(GraphicsEnvironment.isHeadless()).isTrue();
}
@Test
public void whenHeadlessMode_thenFontsWork() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String fonts[] = ge.getAvailableFontFamilyNames();
assertThat(fonts).isNotEmpty();
Font font = new Font(fonts[0], Font.BOLD, 14);
FontMetrics fm = (new Canvas()).getFontMetrics(font);
assertThat(fm.getHeight()).isGreaterThan(0);
assertThat(fm.getAscent()).isGreaterThan(0);
assertThat(fm.getDescent()).isGreaterThan(0);
}
@Test
public void whenHeadlessMode_thenImagesWork() throws IOException {
boolean result = false;
try (InputStream inStream = HeadlessModeUnitTest.class.getResourceAsStream(IN_FILE); FileOutputStream outStream = new FileOutputStream(OUT_FILE)) {
BufferedImage inputImage = ImageIO.read(inStream);
result = ImageIO.write(inputImage, FORMAT, outStream);
}
assertThat(result).isTrue();
}
@Test
public void whenHeadlessmode_thenFrameThrowsHeadlessException() {
assertThatExceptionOfType(HeadlessException.class).isThrownBy(() -> {
Frame frame = new Frame();
frame.setVisible(true);
frame.setSize(120, 120);
});
}
@Test
public void whenHeadless_thenFlexibleAppAdjustsItsBehavior() {
assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADLESS);
}
@Test
public void whenHeaded_thenFlexibleAppAdjustsItsBehavior() {
Assume.assumeFalse(GraphicsEnvironment.isHeadless());
assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADED);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -9,3 +9,4 @@
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set)

View File

@ -13,4 +13,5 @@ This module contains articles about Object-oriented programming (OOP) in Java
- [The “final” Keyword in Java](https://www.baeldung.com/java-final)
- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure)
- [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding)
- [Object-Oriented-Programming Concepts in Java](https://www.baeldung.com/java-oop)
- [[More -->]](/core-java-modules/core-java-lang-oop-2)

View File

@ -12,4 +12,5 @@ This module contains articles about Java syntax
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
- [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax)
- [Java protected Access Modifier](https://www.baeldung.com/java-protected-access-modifier)
- [Using the Not Operator in If Conditions in Java](https://www.baeldung.com/java-using-not-in-if-conditions)
- [[<-- Prev]](/core-java-modules/core-java-lang-syntax)

View File

@ -13,4 +13,7 @@ This module contains articles about Java syntax
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop)
- [Java Do-While Loop](https://www.baeldung.com/java-do-while-loop)
- [Java While Loop](https://www.baeldung.com/java-while-loop)
- [Java For Loop](https://www.baeldung.com/java-for-loop)
- [[More -->]](/core-java-modules/core-java-lang-syntax-2)

View File

@ -6,4 +6,5 @@
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)

View File

@ -0,0 +1,10 @@
=========
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)
- [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches)

View File

@ -2,9 +2,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-text</artifactId>
<artifactId>core-java-regex</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-text</name>
<name>core-java-regex</name>
<packaging>jar</packaging>
<parent>
@ -28,7 +28,7 @@
</dependencies>
<build>
<finalName>core-java-text</finalName>
<finalName>core-java-regex</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>

View File

@ -1,4 +1,4 @@
package com.baeldung.java.regex;
package com.baeldung.regex;
import static org.junit.Assert.*;

View File

@ -1,6 +0,0 @@
=========
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)

View File

@ -2,7 +2,6 @@
### Relevant Articles:
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
@ -11,7 +10,6 @@
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)

View File

@ -113,7 +113,7 @@
<module>core-java-strings</module>
<module>core-java-sun</module>
<module>core-java-text</module>
<module>core-java-regex</module>
<!-- <module>core-java-time-measurements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>multimodulemavenproject</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->

View File

@ -4,5 +4,5 @@ This module contains articles about Kotlin core features.
### Relevant articles:
- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates)
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-conditional-operator)
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator)
- [[<-- Prev]](/core-kotlin-modules/core-kotlin)

View File

@ -3,7 +3,7 @@
This module contains articles about Kotlin core features.
### Relevant articles:
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin)
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro)
- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability)
- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number)
- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project)

View File

@ -7,3 +7,5 @@ This module contains articles about data structures in Java
- [The Trie Data Structure in Java](https://www.baeldung.com/trie-java)
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
- [Circular Linked List Java Implementation](https://www.baeldung.com/java-circular-linked-list)
- [How to Print a Binary Tree Diagram](https://www.baeldung.com/java-print-binary-tree-diagram)
- [Introduction to Big Queue](https://www.baeldung.com/java-big-queue)

View File

@ -7,3 +7,4 @@ This module contains articles about Domain-driven Design (DDD)
- [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates)
- [Double Dispatch in DDD](https://www.baeldung.com/ddd-double-dispatch)
- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd)
- [Organizing Layers Using Hexagonal Architecture, DDD, and Spring](https://www.baeldung.com/hexagonal-architecture-ddd-spring)

View File

@ -1 +1,5 @@
# Dropwizard
# Dropwizard
### Relevant Articles:
- [Introduction to Dropwizard](https://www.baeldung.com/java-dropwizard)

View File

@ -35,6 +35,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>3.4.2-0</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-core</artifactId>

View File

@ -0,0 +1,87 @@
package com.baeldung.imageprocessing.opencv;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import nu.pattern.OpenCV;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import org.opencv.videoio.VideoCapture;
import java.io.ByteArrayInputStream;
public class CameraStream extends Application {
private VideoCapture capture;
public void start(Stage stage) throws Exception {
OpenCV.loadShared();
capture= new VideoCapture(0); // The number is the ID of the camera
ImageView imageView = new ImageView();
HBox hbox = new HBox(imageView);
Scene scene = new Scene(hbox);
stage.setScene(scene);
stage.show();
new AnimationTimer(){
@Override
public void handle(long l) {
imageView.setImage(getCapture());
}
}.start();
}
public Image getCapture() {
Mat mat = new Mat();
capture.read(mat);
return mat2Img(mat);
}
public Image getCaptureWithFaceDetection() {
Mat mat = new Mat();
capture.read(mat);
Mat haarClassifiedImg = detectFace(mat);
return mat2Img(haarClassifiedImg);
}
public Image mat2Img(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode("img", mat, bytes);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray());
Image img = new Image(inputStream); return img;
}
public static void main(String[] args) {
Application.launch(args);
}
public static Mat detectFace(Mat inputImage) {
MatOfRect facesDetected = new MatOfRect();
CascadeClassifier cascadeClassifier = new CascadeClassifier();
int minFaceSize = Math.round(inputImage.rows() * 0.1f);
cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
cascadeClassifier.detectMultiScale(inputImage,
facesDetected,
1.1,
3,
Objdetect.CASCADE_SCALE_IMAGE,
new Size(minFaceSize, minFaceSize),
new Size()
);
Rect[] facesArray = facesDetected.toArray();
for(Rect face : facesArray) {
Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
}
return inputImage;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.imageprocessing.opencv;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import javafx.scene.image.Image;
import java.io.ByteArrayInputStream;
public class FaceDetection {
public static Mat loadImage(String imagePath) {
Imgcodecs imageCodecs = new Imgcodecs();
return imageCodecs.imread(imagePath);
}
public static void saveImage(Mat imageMatrix, String targetPath) {
Imgcodecs imgcodecs = new Imgcodecs();
imgcodecs.imwrite(targetPath, imageMatrix);
}
public static void detectFace(String sourceImagePath, String targetImagePath) {
Mat loadedImage = loadImage(sourceImagePath);
MatOfRect facesDetected = new MatOfRect();
CascadeClassifier cascadeClassifier = new CascadeClassifier();
int minFaceSize = Math.round(loadedImage.rows() * 0.1f);
cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
cascadeClassifier.detectMultiScale(loadedImage,
facesDetected,
1.1,
3,
Objdetect.CASCADE_SCALE_IMAGE,
new Size(minFaceSize, minFaceSize),
new Size()
);
Rect[] facesArray = facesDetected.toArray();
for(Rect face : facesArray) {
Imgproc.rectangle(loadedImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
}
saveImage(loadedImage, targetImagePath);
}
public Image mat2Img(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode("img", mat, bytes);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray());
Image img = new Image(inputStream); return img;
}
}

File diff suppressed because it is too large Load Diff

4
java-numbers-3/README.md Normal file
View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers)
- [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long)

View File

@ -3,3 +3,4 @@
This module contains articles about JSON.
### Relevant Articles:
- [Introduction to Jsoniter](https://www.baeldung.com/java-jsoniter)

View File

@ -1,15 +1,14 @@
package com.baeldung.handlebars;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import org.junit.Test;
import java.io.IOException;
import org.junit.Ignore;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Showcases the built-in template helpers.
@ -20,7 +19,6 @@ public class BuiltinHelperUnitTest {
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
@Ignore
@Test
public void whenUsedWith_ThenContextChanges() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -30,10 +28,9 @@ public class BuiltinHelperUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>I live in World</h4>\n");
assertThat(templateString).contains("<h4>I live in World</h4>");
}
@Ignore
@Test
public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -43,10 +40,9 @@ public class BuiltinHelperUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>I live in World</h4>\n");
assertThat(templateString).contains("<h4>I live in World</h4>");
}
@Ignore
@Test
public void whenUsedEach_ThenIterates() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -59,11 +55,10 @@ public class BuiltinHelperUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<span>Java is my friend.</span>\n"
+ "\n<span>Spring is my friend.</span>\n");
assertThat(templateString)
.contains("<span>Java is my friend.</span>", "<span>Spring is my friend.</span>");
}
@Ignore
@Test
public void whenUsedEachMustacheStyle_ThenIterates() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -76,11 +71,10 @@ public class BuiltinHelperUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<span>Java is my friend.</span>\n"
+ "\n<span>Spring is my friend.</span>\n");
assertThat(templateString)
.contains("<span>Java is my friend.</span>", "<span>Spring is my friend.</span>");
}
@Ignore
@Test
public void whenUsedIf_ThenPutsCondition() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -90,10 +84,9 @@ public class BuiltinHelperUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>Baeldung is busy.</h4>\n");
assertThat(templateString).contains("<h4>Baeldung is busy.</h4>");
}
@Ignore
@Test
public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -103,7 +96,7 @@ public class BuiltinHelperUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<h4>Baeldung is busy.</h4>\n");
assertThat(templateString).contains("<h4>Baeldung is busy.</h4>");
}
private Person getPerson(String name) {

View File

@ -1,15 +1,14 @@
package com.baeldung.handlebars;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
import com.github.jknack.handlebars.io.TemplateLoader;
import org.junit.Test;
import java.io.IOException;
import org.junit.Ignore;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Showcases reusing the existing templates.
@ -20,7 +19,6 @@ public class ReusingTemplatesUnitTest {
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
@Ignore
@Test
public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -30,10 +28,10 @@ public class ReusingTemplatesUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("<h4>Hi Baeldung!</h4>\n<p>This is the page Baeldung</p>");
assertThat(templateString)
.contains("<h4>Hi Baeldung!</h4>", "<p>This is the page Baeldung</p>");
}
@Ignore
@Test
public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException {
Handlebars handlebars = new Handlebars(templateLoader);
@ -43,11 +41,11 @@ public class ReusingTemplatesUnitTest {
String templateString = template.apply(person);
assertThat(templateString).isEqualTo("\n<html>\n"
+ "<body>\n"
+ "\n This is the intro\n\n"
+ "\n Hi there!\n\n"
+ "</body>\n"
+ "</html>");
assertThat(templateString).contains("<html>",
"<body>",
"This is the intro",
"Hi there!",
"</body>",
"</html>");
}
}

View File

@ -9,3 +9,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
### Relevant Articles:
- [Parsing Command-Line Parameters with JCommander](https://www.baeldung.com/jcommander-parsing-command-line-parameters)
- [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos)
- [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline)

View File

@ -24,7 +24,6 @@
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

View File

@ -0,0 +1,90 @@
package com.baeldung.libraries.snakeyaml;
import org.junit.Before;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.InputStream;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class MultiLineStringsUnitTest {
private Yaml yaml;
@Before
public void setup() {
yaml = new Yaml();
}
@Test
public void whenLiteral_ThenLineBreaksArePresent() {
String key = parseYamlKey("literal.yaml", "key");
assertEquals("Line1\nLine2\nLine3", key);
}
@Test
public void whenLiteral_ThenEndingBreaksAreReducedToOne() {
String key = parseYamlKey("literal2.yaml", "key");
assertEquals("\n\nLine1\n\nLine2\n\nLine3\n", key);
}
@Test
public void whenFolded_ThenLineBreaksAreReplaced() {
String key = parseYamlKey("folded.yaml", "key");
assertEquals("Line1 Line2 Line3", key);
}
@Test
public void whenFolded_ThenEmptyLinesAreReducedToOne() {
String key = parseYamlKey("folded2.yaml", "key");
assertEquals("Line1 Line2\n\nLine3\n", key);
}
@Test
public void whenLiteralKeep_ThenLastEmptyLinesArePresent() {
String key = parseYamlKey("literal_keep.yaml", "key");
assertEquals("Line1\nLine2\nLine3\n\n", key);
}
@Test
public void whenLiteralStrip_ThenLastEmptyLinesAreRemoved() {
String key = parseYamlKey("literal_strip.yaml", "key");
assertEquals("Line1\nLine2\nLine3", key);
}
@Test
public void whenFoldedKeep_ThenLastEmptyLinesArePresent() {
String key = parseYamlKey("folded_keep.yaml", "key");
assertEquals("Line1 Line2 Line3\n\n\n", key);
}
@Test
public void whenFoldedStrip_ThenLastEmptyLinesAreRemoved() {
String key = parseYamlKey("folded_strip.yaml", "key");
assertEquals("Line1 Line2 Line3", key);
}
@Test
public void whenDoubleQuotes_ThenExplicitBreaksArePreserved() {
String key = parseYamlKey("plain_double_quotes.yaml", "key");
assertEquals("Line1\nLine2\nLine3", key);
}
@Test
public void whenSingleQuotes_ThenExplicitBreaksAreIgnored() {
String key = parseYamlKey("plain_single_quotes.yaml", "key");
assertEquals("Line1\\nLine2\nLine3", key);
}
String parseYamlKey(String fileName, String key) {
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml" + File.separator + "multiline" + File.separator + fileName);
Map<String, String> parsed = yaml.load(inputStream);
return parsed.get(key);
}
}

View File

@ -0,0 +1,4 @@
key: >
Line1
Line2
Line3

View File

@ -0,0 +1,8 @@
key: >
Line1
Line2
Line3

View File

@ -0,0 +1,6 @@
key: >+
Line1
Line2
Line3

View File

@ -0,0 +1,7 @@
key: >-
Line1
Line2
Line3

View File

@ -0,0 +1,4 @@
key: |
Line1
Line2
Line3

View File

@ -0,0 +1,10 @@
key: |
Line1
Line2
Line3

View File

@ -0,0 +1,5 @@
key: |+
Line1
Line2
Line3

View File

@ -0,0 +1,5 @@
key: |-
Line1
Line2
Line3

View File

@ -0,0 +1 @@
key: "Line1\nLine2\nLine3"

View File

@ -0,0 +1,3 @@
key: 'Line1\nLine2
Line3'

View File

@ -13,3 +13,4 @@ This module contains articles about HTTP libraries.
- [A Guide to Unirest](https://www.baeldung.com/unirest)
- [Creating REST Microservices with Javalin](https://www.baeldung.com/javalin-rest-microservices)
- [A Quick Guide to Timeouts in OkHttp](https://www.baeldung.com/okhttp-timeouts)
- [A Quick Guide to Post Requests with OkHttp](https://www.baeldung.com/okhttp-post)

View File

@ -2,3 +2,4 @@
- [Get Log Output in JSON](https://www.baeldung.com/java-log-json-output)
- [SLF4J Warning: Class Path Contains Multiple SLF4J Bindings](https://www.baeldung.com/slf4j-classpath-multiple-bindings)
- [Sending Emails with Logback](https://www.baeldung.com/logback-send-email)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Using Maven Behind a Proxy](https://www.baeldung.com/maven-behind-proxy)

3
ninja/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles
- [Introduction to Ninja Framework](https://www.baeldung.com/ninja-framework-intro)

View File

@ -1,3 +1,3 @@
### Relevant articles
- [HBase with Java](http://www.baeldung.com/hbase)
- [HBase with Java](https://www.baeldung.com/hbase)

View File

@ -1,4 +1,4 @@
package org.baeldung.hbase;
package com.baeldung.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;

View File

@ -1,4 +1,4 @@
package org.baeldung.hbase;
package com.baeldung.hbase;
import com.google.protobuf.ServiceException;

View File

@ -7,4 +7,5 @@ This module contains articles about Hibernate 5.
- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode)
- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context)
- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode)
- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels)
- [[<-- Prev]](/hibernate5)

View File

@ -1,111 +1,111 @@
package com.baeldung.aggregation;
import static com.mongodb.client.model.Aggregates.count;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.out;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Aggregates.sort;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
public class AggregationLiveTest {
private static final String DATABASE = "world";
private static final String COLLECTION = "countries";
private static final String DATASET_JSON = "/countrydata.json";
private static MongoClient mongoClient;
private static MongoDatabase database;
private static MongoCollection<Document> collection;
@BeforeClass
public static void setUpDB() throws IOException {
mongoClient = MongoClients.create();
database = mongoClient.getDatabase(DATABASE);
collection = database.getCollection(COLLECTION);
collection.drop();
InputStream is = AggregationLiveTest.class.getResourceAsStream(DATASET_JSON);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
reader.lines()
.forEach(line -> collection.insertOne(Document.parse(line)));
reader.close();
}
@Test
public void givenCountryCollection_whenNAFTACountriesCounted_thenThree() {
Document naftaCountries = collection.aggregate(Arrays.asList(match(Filters.eq("regionalBlocs.acronym", "NAFTA")), count()))
.first();
assertEquals(3, naftaCountries.get("count"));
}
@Test
public void givenCountryCollection_whenAreaSortedDescending_thenSuccess() {
collection.aggregate(Arrays.asList(sort(Sorts.descending("area")), limit(7), out("largest_seven")))
.toCollection();
MongoCollection<Document> largestSeven = database.getCollection("largest_seven");
assertEquals(7, largestSeven.countDocuments());
Document usa = largestSeven.find(Filters.eq("alpha3Code", "USA"))
.first();
assertNotNull(usa);
}
@Test
public void givenCountryCollection_whenCountedRegionWise_thenMaxInAfrica() {
Document maxCountriedRegion = collection.aggregate(Arrays.asList(group("$region", Accumulators.sum("tally", 1)), sort(Sorts.descending("tally"))))
.first();
assertTrue(maxCountriedRegion.containsValue("Africa"));
}
@Test
public void givenCountryCollection_whenNeighborsCalculated_thenMaxIsFifteenInChina() {
Bson borderingCountriesCollection = project(Projections.fields(Projections.excludeId(), Projections.include("name"), Projections.computed("borderingCountries", Projections.computed("$size", "$borders"))));
int maxValue = collection.aggregate(Arrays.asList(borderingCountriesCollection, group(null, Accumulators.max("max", "$borderingCountries"))))
.first()
.getInteger("max");
assertEquals(15, maxValue);
Document maxNeighboredCountry = collection.aggregate(Arrays.asList(borderingCountriesCollection, match(Filters.eq("borderingCountries", maxValue))))
.first();
assertTrue(maxNeighboredCountry.containsValue("China"));
}
@AfterClass
public static void cleanUp() {
mongoClient.close();
}
}
package com.baeldung.aggregation;
import static com.mongodb.client.model.Aggregates.count;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.out;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Aggregates.sort;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
public class AggregationLiveTest {
private static final String DATABASE = "world";
private static final String COLLECTION = "countries";
private static final String DATASET_JSON = "/countrydata.json";
private static MongoClient mongoClient;
private static MongoDatabase database;
private static MongoCollection<Document> collection;
@BeforeClass
public static void setUpDB() throws IOException {
mongoClient = MongoClients.create();
database = mongoClient.getDatabase(DATABASE);
collection = database.getCollection(COLLECTION);
collection.drop();
InputStream is = AggregationLiveTest.class.getResourceAsStream(DATASET_JSON);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
reader.lines()
.forEach(line -> collection.insertOne(Document.parse(line)));
reader.close();
}
@Test
public void givenCountryCollection_whenEnglishSpeakingCountriesCounted_thenNinetyOne() {
Document englishSpeakingCountries = collection.aggregate(Arrays.asList(match(Filters.eq("languages.name", "English")), count()))
.first();
assertEquals(91, englishSpeakingCountries.get("count"));
}
@Test
public void givenCountryCollection_whenAreaSortedDescending_thenSuccess() {
collection.aggregate(Arrays.asList(sort(Sorts.descending("area")), limit(7), out("largest_seven")))
.toCollection();
MongoCollection<Document> largestSeven = database.getCollection("largest_seven");
assertEquals(7, largestSeven.countDocuments());
Document usa = largestSeven.find(Filters.eq("alpha3Code", "USA"))
.first();
assertNotNull(usa);
}
@Test
public void givenCountryCollection_whenCountedRegionWise_thenMaxInAfrica() {
Document maxCountriedRegion = collection.aggregate(Arrays.asList(group("$region", Accumulators.sum("tally", 1)), sort(Sorts.descending("tally"))))
.first();
assertTrue(maxCountriedRegion.containsValue("Africa"));
}
@Test
public void givenCountryCollection_whenNeighborsCalculated_thenMaxIsFifteenInChina() {
Bson borderingCountriesCollection = project(Projections.fields(Projections.excludeId(), Projections.include("name"), Projections.computed("borderingCountries", Projections.computed("$size", "$borders"))));
int maxValue = collection.aggregate(Arrays.asList(borderingCountriesCollection, group(null, Accumulators.max("max", "$borderingCountries"))))
.first()
.getInteger("max");
assertEquals(15, maxValue);
Document maxNeighboredCountry = collection.aggregate(Arrays.asList(borderingCountriesCollection, match(Filters.eq("borderingCountries", maxValue))))
.first();
assertTrue(maxNeighboredCountry.containsValue("China"));
}
@AfterClass
public static void cleanUp() {
mongoClient.close();
}
}

View File

@ -1,3 +1,3 @@
### Relevant Articles:
- [Intro to Querydsl](http://www.baeldung.com/intro-to-querydsl)
- [A Guide to Querydsl with JPA](http://www.baeldung.com/querydsl-with-jpa-tutorial)
- [Intro to Querydsl](https://www.baeldung.com/intro-to-querydsl)
- [A Guide to Querydsl with JPA](https://www.baeldung.com/querydsl-with-jpa-tutorial)

View File

@ -1,9 +1,9 @@
package org.baeldung.dao;
package com.baeldung.dao;
import java.util.List;
import java.util.Map;
import org.baeldung.entity.Person;
import com.baeldung.entity.Person;
public interface PersonDao {

View File

@ -1,17 +1,15 @@
package org.baeldung.dao;
package com.baeldung.dao;
import java.util.List;
import java.util.Map;
import com.baeldung.entity.Person;
import com.baeldung.entity.QPerson;
import com.querydsl.core.group.GroupBy;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.baeldung.entity.Person;
import org.baeldung.entity.QPerson;
import org.springframework.stereotype.Repository;
import com.querydsl.core.group.GroupBy;
import com.querydsl.jpa.impl.JPAQuery;
import java.util.List;
import java.util.Map;
@Repository
public class PersonDaoImpl implements PersonDao {

View File

@ -1,4 +1,4 @@
package org.baeldung.entity;
package com.baeldung.entity;
import javax.persistence.Column;
import javax.persistence.Entity;

View File

@ -1,7 +1,7 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro.entities;
package com.baeldung.querydsl.intro.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

View File

@ -1,7 +1,7 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro.entities;
package com.baeldung.querydsl.intro.entities;
import java.util.HashSet;
import java.util.Set;

View File

@ -17,7 +17,7 @@
</persistence-unit>
<!-- PersistenceUnit for Intro to QueryDSL -->
<persistence-unit name="org.baeldung.querydsl.intro">
<persistence-unit name="com.baeldung.querydsl.intro">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>

View File

@ -1,8 +1,8 @@
package org.baeldung.dao;
package com.baeldung.dao;
import java.util.Map;
import org.baeldung.entity.Person;
import com.baeldung.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;

View File

@ -1,17 +1,17 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro;
package com.baeldung.querydsl.intro;
import com.baeldung.querydsl.intro.entities.BlogPost;
import com.baeldung.querydsl.intro.entities.QBlogPost;
import com.baeldung.querydsl.intro.entities.QUser;
import com.baeldung.querydsl.intro.entities.User;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.baeldung.querydsl.intro.entities.BlogPost;
import org.baeldung.querydsl.intro.entities.QBlogPost;
import org.baeldung.querydsl.intro.entities.QUser;
import org.baeldung.querydsl.intro.entities.User;
import org.junit.*;
import javax.persistence.EntityManager;
@ -31,7 +31,7 @@ public class QueryDSLIntegrationTest {
@BeforeClass
public static void populateDatabase() {
emf = Persistence.createEntityManagerFactory("org.baeldung.querydsl.intro");
emf = Persistence.createEntityManagerFactory("com.baeldung.querydsl.intro");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

View File

@ -13,7 +13,7 @@
>
<tx:annotation-driven />
<context:component-scan base-package="org.baeldung" />
<context:component-scan base-package="com.baeldung" />
<import resource="test-db.xml" />

View File

@ -3,7 +3,7 @@
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>org.baeldung.examples.r2dbc</groupId>
<groupId>com.baeldung.examples.r2dbc</groupId>
<artifactId>r2dbc-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>r2dbc-example</name>

View File

@ -1,4 +1,4 @@
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import java.math.BigDecimal;

View File

@ -1,12 +1,8 @@
/**
*
*/
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@ -15,8 +11,6 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

View File

@ -1,16 +1,14 @@
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import io.netty.util.internal.StringUtil;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.ConnectionFactoryOptions.Builder;
import io.r2dbc.spi.Option;
import reactor.core.publisher.Flux;
import static io.r2dbc.spi.ConnectionFactoryOptions.*;

View File

@ -1,4 +1,4 @@
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import javax.validation.constraints.NotEmpty;

View File

@ -1,4 +1,4 @@
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -1,9 +1,7 @@
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import java.math.BigDecimal;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import io.r2dbc.spi.Connection;

View File

@ -1,5 +1,5 @@
{"properties": [{
"name": "r2dbc",
"type": "org.baeldung.examples.r2dbc.R2DBCConfigurationProperties",
"type": "com.baeldung.examples.r2dbc.R2DBCConfigurationProperties",
"description": "R2DBC Connection properties"
}]}

View File

@ -1,19 +1,15 @@
package org.baeldung.examples.r2dbc;
package com.baeldung.examples.r2dbc;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.List;
import org.hamcrest.core.IsNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;

View File

@ -2,3 +2,4 @@
- [Intro to Jedis the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library)
- [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson)
- [Introduction to Lettuce the Java Redis Client](https://www.baeldung.com/java-redis-lettuce)
- [List All Available Redis Keys](https://www.baeldung.com/redis-list-available-keys)

View File

@ -145,5 +145,10 @@ public class RedisClient {
log.error("Exception caught in flushAll", ex);
}
}
public void destroyInstance() {
jedisPool = null;
instance = null;
}
}

View File

@ -25,13 +25,14 @@ public class NaiveApproachIntegrationTest {
s.close();
redisServer = new RedisServer(port);
redisServer.start();
}
@AfterClass
public static void destroy() {
if (redisServer.isActive())
if (redisServer.isActive()) {
redisServer.stop();
redisClient.destroyInstance();
}
}
@Before

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