Merge remote-tracking branch 'upstream/master'

This commit is contained in:
macroscopic64
2020-02-23 20:51:29 +05:30
787 changed files with 31520 additions and 1433 deletions
+1
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
+7
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)
- [Prim’s 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)
- [Kruskal’s 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)
@@ -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);
}
}
@@ -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;
}
}
+3
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)
+3
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)
@@ -1,4 +1,4 @@
package com.baeldung.poi.excel;
package com.baeldung.poi.excel.merge;
import static org.junit.Assert.assertEquals;
+2
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
View File
@@ -0,0 +1,3 @@
### Relevant Articles:
- [AWS S3 with Java – Reactive Support](https://www.baeldung.com/java-aws-s3-reactive)
+1 -1
View File
@@ -106,7 +106,7 @@
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>sample-blade-app.jar</argument>
<argument>blade.jar</argument>
</arguments>
</configuration>
</execution>
+1
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)
+1
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)
@@ -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)
@@ -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 };
@@ -0,0 +1,5 @@
## Core Java Arrays (Part 3)
This module contains articles about Java arrays
## Relevant Articles
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-arrays-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-arrays-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj.version>3.14.0</assertj.version>
</properties>
</project>
@@ -0,0 +1,96 @@
package com.baeldung.arrays.deepequals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Objects;
import org.junit.jupiter.api.Test;
public class ArraysDeepEqualsUnitTest {
class Person {
private int id;
private String name;
private int age;
Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Person))
return false;
Person person = (Person) obj;
return id == person.id && name.equals(person.name) && age == person.age;
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
}
@Test
void givenTwoUnidimensionalObjectTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnTrue() {
Object[] anArray = new Object[] { "string1", "string2", "string3" };
Object[] anotherArray = new Object[] { "string1", "string2", "string3" };
assertTrue(Arrays.equals(anArray, anotherArray));
assertTrue(Arrays.deepEquals(anArray, anotherArray));
}
@Test
void givenTwoUnidimensionalObjectTypeArraysWithNullElements_whenUsingEqualsAndDeepEquals_thenBothShouldReturnTrue() {
Object[] anArray = new Object[] { "string1", null, "string3" };
Object[] anotherArray = new Object[] { "string1", null, "string3" };
assertTrue(Arrays.equals(anArray, anotherArray));
assertTrue(Arrays.deepEquals(anArray, anotherArray));
}
@Test
void givenTwoUnidimensionalObjectTypeArraysWithNestedElements_whenUsingEqualsAndDeepEquals_thenShouldReturnDifferently() {
Object[] anArray = new Object[] { "string1", null, new String[] { "nestedString1", "nestedString2" } };
Object[] anotherArray = new Object[] { "string1", null, new String[] { "nestedString1", "nestedString2" } };
assertFalse(Arrays.equals(anArray, anotherArray));
assertTrue(Arrays.deepEquals(anArray, anotherArray));
}
@Test
void givenTwoMultidimensionalPrimitiveTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnDifferently() {
int[][] anArray = { { 1, 2, 3 }, { 4, 5, 6, 9 }, { 7 } };
int[][] anotherArray = { { 1, 2, 3 }, { 4, 5, 6, 9 }, { 7 } };
assertFalse(Arrays.equals(anArray, anotherArray));
assertTrue(Arrays.deepEquals(anArray, anotherArray));
}
@Test
void givenTwoMultidimensionalObjectTypeArrays_whenUsingEqualsAndDeepEquals_thenBothShouldReturnDifferently() {
Person personArray1[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
Person personArray2[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
assertFalse(Arrays.equals(personArray1, personArray2));
assertTrue(Arrays.deepEquals(personArray1, personArray2));
}
@Test
void givenTwoMultidimensionalObjectTypeArrays_whenUsingDeepEqualsFromObjectsAndArraysClasses_thenBothShouldReturnTrue() {
Person personArray1[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
Person personArray2[][] = { { new Person(1, "John", 22), new Person(2, "Mike", 23) }, { new Person(3, "Steve", 27), new Person(4, "Gary", 28) } };
assertTrue(Objects.deepEquals(personArray1, personArray2));
assertTrue(Arrays.deepEquals(personArray1, personArray2));
}
}
@@ -1,20 +0,0 @@
package com.baeldung.array;
public class Find2ndLargestInArray {
public static int find2ndLargestElement(int[] array) {
int maxElement = array[0];
int secondLargestElement = -1;
for (int index = 0; index < array.length; index++) {
if (maxElement <= array[index]) {
secondLargestElement = maxElement;
maxElement = array[index];
} else if (secondLargestElement < array[index]) {
secondLargestElement = array[index];
}
}
return secondLargestElement;
}
}
@@ -1,22 +0,0 @@
package com.baeldung.array;
import java.util.Arrays;
public class FindElementInArray {
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
boolean actualResult = false;
for (int index = 0; index < array.length; index++) {
if (element == array[index]) {
actualResult = true;
break;
}
}
return actualResult;
}
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
}
}
@@ -1,16 +0,0 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class Find2ndLargestInArrayUnitTest {
@Test
public void givenAnIntArray_thenFind2ndLargestElement() {
int[] array = { 1, 3, 24, 16, 87, 20 };
int expected2ndLargest = 24;
int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array);
Assert.assertEquals(expected2ndLargest, actualSecondLargestElement);
}
}
@@ -1,35 +0,0 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class FindElementInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int element = 19;
boolean expectedResult = true;
boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
element = 78;
expectedResult = false;
actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindAnElement() {
int[] array = { 15, 16, 12, 18 };
int element = 16;
boolean expectedResult = true;
boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
element = 20;
expectedResult = false;
actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
}
}
@@ -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)
@@ -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(){
@@ -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);
@@ -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)
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
@@ -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)
@@ -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();
}
}
@@ -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();
}
}
@@ -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();
}
}
}

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