Merge branch 'master' into bael-7667-update-readme

This commit is contained in:
Maiklins 2024-04-02 21:47:23 +02:00 committed by GitHub
commit e7d5768bc8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1318 changed files with 13954 additions and 4095 deletions

View File

@ -4,8 +4,8 @@
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>akka-modules</artifactId>
<name>akka-modules</name>
<packaging>pom</packaging>
<name>akka-modules</name>
<parent>
<artifactId>parent-modules</artifactId>

View File

@ -19,11 +19,6 @@
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>

View File

@ -5,6 +5,18 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>algorithms-miscellaneous-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
<name>algorithms-miscellaneous-5</name>
<parent>
@ -29,11 +41,7 @@
<artifactId>tradukisto</artifactId>
<version>${tradukisto.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>

View File

@ -1,15 +1,12 @@
package com.baeldung.algorithms.conversion;
import java.math.BigInteger;
import com.google.common.io.BaseEncoding;
import jakarta.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding;
import jakarta.xml.bind.DatatypeConverter;
import java.math.BigInteger;
import java.util.HexFormat;
public class HexStringConverter {
@ -109,4 +106,14 @@ public class HexStringConverter {
return BaseEncoding.base16()
.decode(hexString.toUpperCase());
}
public String encodeUsingHexFormat(byte[] bytes) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.formatHex(bytes);
}
public byte[] decodeUsingHexFormat(String hexString) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.parseHex(hexString);
}
}

View File

@ -1,15 +1,13 @@
package com.baeldung.algorithms.conversion;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.commons.codec.DecoderException;
import org.hamcrest.text.IsEqualIgnoringCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.conversion.HexStringConverter;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ByteArrayConverterUnitTest {
@ -24,7 +22,7 @@ class ByteArrayConverterUnitTest {
void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
if(hexString.charAt(0) == '0') {
if (hexString.charAt(0) == '0') {
hexString = hexString.substring(1);
}
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
@ -46,7 +44,7 @@ class ByteArrayConverterUnitTest {
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
assertArrayEquals(bytes, output);
}
@Test
void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
@ -62,7 +60,7 @@ class ByteArrayConverterUnitTest {
byte[] output = hexStringConverter.decodeHexString(hexString);
assertArrayEquals(bytes, output);
}
@Test
void shouldDecodeHexToByteWithInvalidHexCharacter() {
assertThrows(IllegalArgumentException.class, () -> {
@ -118,12 +116,28 @@ class ByteArrayConverterUnitTest {
assertArrayEquals(bytes, output);
}
@Test
void shouldEncodeByteArrayToHexStringUsingHexFormat() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingHexFormat(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
void shouldDecodeHexStringToByteArrayUsingHexFormat() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingHexFormat(hexString);
assertArrayEquals(bytes, output);
}
private String getSampleHexString() {
return "0af50c0e2d10";
}
private byte[] getSampleBytes() {
return new byte[] { 10, -11, 12, 14, 45, 16 };
return new byte[]{10, -11, 12, 14, 45, 16};
}
}

View File

@ -8,4 +8,10 @@
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
- [Check if Two Strings Are Rotations of Each Other](https://www.baeldung.com/java-string-check-strings-rotations)
- [Find the Largest Prime Under the Given Number in Java](https://www.baeldung.com/java-largest-prime-lower-threshold)
- [Count the Number of Unique Digits in an Integer using Java](https://www.baeldung.com/java-int-count-unique-digits)
- [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence)
- [Finding the Parent of a Node in a Binary Search Tree with Java](https://www.baeldung.com/java-find-parent-node-binary-search-tree)
- [Check if a Number Is a Happy Number in Java](https://www.baeldung.com/java-happy-sad-number-test)
- [Find the Largest Number Possible After Removing k Digits of a Number](https://www.baeldung.com/java-find-largest-number-remove-k-digits)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)

View File

@ -0,0 +1,57 @@
package com.baeldung.algorithms.largestNumberRemovingK;
import java.util.*;
public class LargestNumberRemoveKDigits {
public static int findLargestNumberUsingArithmetic(int num, int k) {
for (int j = 0; j < k; j++) {
int result = 0;
int i = 1;
while (num / i > 0) {
int temp = (num / (i * 10))
* i
+ (num % i);
i *= 10;
result = Math.max(result, temp);
}
num = result;
}
return num;
}
public static int findLargestNumberUsingStack(int num, int k) {
String numStr = Integer.toString(num);
int length = numStr.length();
if (k == length) return 0;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < length; i++) {
char digit = numStr.charAt(i);
while (k > 0 && !stack.isEmpty() && stack.peek() < digit) {
stack.pop();
k--;
}
stack.push(digit);
}
while (k > 0) {
stack.pop();
k--;
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return Integer.parseInt(result.toString());
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.algorithms.happynumber;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HappyNumberDecider {
public static boolean isHappyNumber(int n) {
Set<Integer> checkedNumbers = new HashSet<>();
while (true) {
n = sumDigitsSquare(n);
if (n == 1) {
return true;
}
if (checkedNumbers.contains(n)) {
return false;
}
checkedNumbers.add(n);
}
}
public static boolean isHappyNumberFloyd(int n) {
int slow = n;
int fast = n;
do {
slow = sumDigitsSquare(slow);
fast = sumDigitsSquare(sumDigitsSquare(fast));
} while (slow != fast);
return slow == 1;
}
private static int sumDigitsSquare(int n) {
int squareSum = 0;
while (n != 0) {
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}
}
public class HappyNumberUnitTest {
@Test
void whenUsingIsHappyNumber_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumber(7));
assertTrue(HappyNumberDecider.isHappyNumber(10));
assertTrue(HappyNumberDecider.isHappyNumber(13));
assertTrue(HappyNumberDecider.isHappyNumber(19));
assertTrue(HappyNumberDecider.isHappyNumber(23));
assertFalse(HappyNumberDecider.isHappyNumber(4));
assertFalse(HappyNumberDecider.isHappyNumber(6));
assertFalse(HappyNumberDecider.isHappyNumber(11));
assertFalse(HappyNumberDecider.isHappyNumber(15));
assertFalse(HappyNumberDecider.isHappyNumber(20));
}
@Test
void whenUsingIsHappyNumber2_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumberFloyd(7));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(10));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(13));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(19));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(23));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(4));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(6));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(11));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(15));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(20));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.algorithms.largestNumberRemovingK;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LargestNumberRemoveKDigitsUnitTest {
@Test
public void givenNumber_UsingArithmeticRemoveKDigits_thenReturnLargestNumber(){
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(9461, 1), 961);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(463, 2), 6);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98625410, 6), 98);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(20, 2), 0);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98989, 4), 9);
}
@Test
public void givenNumber_UsingStackRemoveKDigits_thenReturnLargestNumber(){
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(9461, 1), 961);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(463, 2), 6);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98625410, 6), 98);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(20, 2), 0);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98989, 4), 9);
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Vigenère Cipher in Java](https://www.baeldung.com/java-vigenere-cipher)

View File

@ -3,19 +3,14 @@
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>docker-caching</artifactId>
<name>docker-caching</name>
<packaging>pom</packaging>
<artifactId>algorithms-miscellaneous-8</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-8</name>
<parent>
<artifactId>docker-modules</artifactId>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>single-module-caching</module>
<module>multi-module-caching</module>
</modules>
</project>
</project>

View File

@ -0,0 +1,37 @@
package com.baeldung.algorithms.mergeintervals;
import java.util.Objects;
public class Interval {
int start;
int end;
Interval(int start, int end) {
this.start = start;
this.end = end;
}
public void setEnd(int end) {
this.end = end;
}
@Override
public String toString() {
return "Interval{" + "start=" + start + ", end=" + end + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Interval interval = (Interval) o;
return start == interval.start && end == interval.end;
}
@Override
public int hashCode() {
return Objects.hash(start, end);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.mergeintervals;
import java.util.ArrayList;
import java.util.List;
public class MergeOverlappingIntervals {
public List<Interval> doMerge(List<Interval> intervals) {
// Sort the intervals based on start time
intervals.sort((one, two) -> one.start - two.start);
// Create somewhere to put the merged list, start it off with the earliest starting interval
ArrayList<Interval> merged = new ArrayList<>();
merged.add(intervals.get(0));
// Loop over each interval and merge if start time is before the end time of the
// previous interval
intervals.forEach(interval -> {
if (merged.get(merged.size() - 1).end > interval.start) {
merged.get(merged.size() - 1).setEnd(interval.end);
} else {
merged.add(interval);
}
});
return merged;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.algorithms.skiplist;
class Node {
int value;
Node[] forward; // array to hold references to different levels
public Node(int value, int level) {
this.value = value;
this.forward = new Node[level + 1]; // level + 1 because level is 0-based
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.algorithms.skiplist;
import java.util.Random;
public class SkipList {
private Node head;
private int maxLevel;
private int level;
private Random random;
public SkipList() {
maxLevel = 16; // maximum number of levels
level = 0; // current level of SkipList
head = new Node(Integer.MIN_VALUE, maxLevel);
random = new Random();
}
public void insert(int value) {
Node[] update = new Node[maxLevel + 1];
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current == null || current.value != value) {
int lvl = randomLevel();
if (lvl > level) {
for (int i = level + 1; i <= lvl; i++) {
update[i] = head;
}
level = lvl;
}
Node newNode = new Node(value, lvl);
for (int i = 0; i <= lvl; i++) {
newNode.forward[i] = update[i].forward[i];
update[i].forward[i] = newNode;
}
}
}
public boolean search(int value) {
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
}
current = current.forward[0];
return current != null && current.value == value;
}
public void delete(int value) {
Node[] update = new Node[maxLevel + 1];
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current != null && current.value == value) {
for (int i = 0; i <= level; i++) {
if (update[i].forward[i] != current) break;
update[i].forward[i] = current.forward[i];
}
while (level > 0 && head.forward[level] == null) {
level--;
}
}
}
private int randomLevel() {
int lvl = 0;
while (lvl < maxLevel && random.nextDouble() < 0.5) {
lvl++;
}
return lvl;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.mergeintervals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class MergeIntervalsUnitTest {
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
new Interval(2, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(1, 3)
));
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
new Interval(1, 5),
new Interval(11, 20)
));
@Test
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.skiplist;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SkipListUnitTest {
@Test
public void givenSkipList_WhenInsert_ThenSearchFound() {
SkipList skipList = new SkipList();
skipList.insert(3);
assertTrue(skipList.search(3), "Should find 3");
assertFalse(skipList.search(99), "Should not find 99");
}
@Test
public void givenSkipList_WhenDeleteElement_ThenRemoveFromList() {
SkipList skipList = new SkipList();
skipList.insert(3);
skipList.insert(7);
skipList.delete(3);
assertFalse(skipList.search(3), "3 should have been deleted");
skipList.delete(99);
assertTrue(skipList.search(7), "7 should still exist");
}
}

View File

@ -24,17 +24,17 @@ public class VigenereCipherUnitTest {
@Test
void encodeArticleTitle() {
VigenereCipher cipher = new VigenereCipher();
String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG");
String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG");
Assertions.assertEquals("XFLQRZFL EJUTIM WU LBAM", output);
Assertions.assertEquals("XJLQRZFL EJUTIM WU LBAM", output);
}
@Test
void encodeArticleTitleMoreCharacters() {
VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG");
String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG");
Assertions.assertEquals("XFLQRZELBDNALZEGKOEVEPO", output);
Assertions.assertEquals("XJLQRZELBDNALZEGKOEVEPO", output);
}
@Test
@ -56,8 +56,21 @@ public class VigenereCipherUnitTest {
@Test
void decodeArticleTitleMoreCharacters() {
VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
String output = cipher.decode("XFLQRZELBDNALZEGKOEVEPO", "BAELDUNG");
String output = cipher.decode("XJLQRZELBDNALZEGKOEVEPO", "BAELDUNG");
Assertions.assertEquals("VEGENERE CIPHER IN JAVA", output);
Assertions.assertEquals("VIGENERE CIPHER IN JAVA", output);
}
@Test
void encodeDecodeBaeldung() {
VigenereCipher cipher = new VigenereCipher();
String input = "BAELDUNG";
String key = "HELLO";
String encoded = cipher.encode(input, key);
String decoded = cipher.decode(encoded, key);
Assertions.assertEquals(input, decoded);
}
}

View File

@ -22,6 +22,7 @@
<module>algorithms-miscellaneous-5</module>
<module>algorithms-miscellaneous-6</module>
<module>algorithms-miscellaneous-7</module>
<module>algorithms-miscellaneous-8</module>
<module>algorithms-searching</module>
<module>algorithms-sorting</module>
<module>algorithms-sorting-2</module>
@ -34,4 +35,4 @@
<tradukisto.version>1.0.1</tradukisto.version>
</properties>
</project>
</project>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cxf-spring</artifactId>
<name>cxf-spring</name>
<packaging>war</packaging>
<name>cxf-spring</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,9 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-cxf-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-cxf-modules</name>
<packaging>pom</packaging>
<name>apache-cxf-modules</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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>sse-jaxrs</artifactId>
<name>sse-jaxrs</name>
<packaging>pom</packaging>
<name>sse-jaxrs</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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>sse-jaxrs-server</artifactId>
<name>sse-jaxrs-server</name>
<packaging>war</packaging>
<name>sse-jaxrs-server</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-httpclient4</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-httpclient4</name>
<packaging>war</packaging>
<name>apache-httpclient4</name>
<parent>
<groupId>com.baeldung</groupId>
@ -82,7 +82,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
<version>${spring-oxm.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
@ -176,12 +176,6 @@
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
@ -199,7 +193,6 @@
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
@ -233,6 +226,7 @@
</profiles>
<properties>
<spring-oxm.version>6.1.4</spring-oxm.version>
<!-- util -->
<commons-codec.version>1.16.0</commons-codec.version>
<httpasyncclient.version>4.1.5</httpasyncclient.version>

View File

@ -16,3 +16,4 @@ You can build the project from the command line using: *mvn clean install*, or i
- [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka)
- [Ensuring Message Ordering in Kafka: Strategies and Configurations](https://www.baeldung.com/kafka-message-ordering)
- [Read Multiple Messages with Apache Kafka](https://www.baeldung.com/kafka-read-multiple-messages)
- [Creating a Kafka Listener Using the Consumer API](https://www.baeldung.com/kafka-create-listener-consumer-api)

10
apache-kafka-3/README.md Normal file
View File

@ -0,0 +1,10 @@
## Apache Kafka
This module contains articles about Apache Kafka.
##### Building the project
You can build the project from the command line using: *mvn clean install*, or in an IDE.
### Relevant Articles:
- [Commit Offsets in Kafka](https://www.baeldung.com/kafka-commit-offsets)

48
apache-kafka-3/pom.xml Normal file
View File

@ -0,0 +1,48 @@
<?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>apache-kafka-3</artifactId>
<name>apache-kafka-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${kafka.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
</dependency>
</dependencies>
<properties>
<kafka.version>3.6.1</kafka.version>
<jackson.databind.version>2.15.2</jackson.databind.version>
</properties>
<profiles>
<profile>
<id>integration-jdk9-and-above</id>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,23 @@
package com.baeldung.kafka.commitoffset;
import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties;
import java.time.Duration;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
public class AsyncCommit {
public static void main(String[] args) {
KafkaConsumer<Long, String> consumer = new KafkaConsumer<>(KafkaConfigProperties.getProperties());
consumer.subscribe(KafkaConfigProperties.getTopic());
ConsumerRecords<Long, String> messages = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord<Long, String> message : messages) {
// processed message
consumer.commitAsync();
}
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.kafka.commitoffset;
import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties;
import java.time.Duration;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
public class AutomaticCommit {
public static void main(String[] args) {
Properties properties = KafkaConfigProperties.getProperties();
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
KafkaConsumer<Long, String> consumer = new KafkaConsumer<>(properties);
consumer.subscribe(KafkaConfigProperties.getTopic());
ConsumerRecords<Long, String> messages = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord<Long, String> message : messages) {
// processed message
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.kafka.commitoffset;
import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
public class SpecificOffsetCommit {
public static void main(String[] args) {
KafkaConsumer<Long, String> consumer = new KafkaConsumer<>(KafkaConfigProperties.getProperties());
consumer.subscribe(KafkaConfigProperties.getTopic());
Map<TopicPartition, OffsetAndMetadata> currentOffsets = new HashMap<>();
int messageProcessed = 0;
while (true) {
ConsumerRecords<Long, String> messages = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord<Long, String> message : messages) {
// processed message
messageProcessed++;
currentOffsets.put(new TopicPartition(message.topic(), message.partition()), new OffsetAndMetadata(message.offset() + 1));
if (messageProcessed % 50 == 0) {
consumer.commitSync(currentOffsets);
}
}
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.kafka.commitoffset;
import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties;
import java.time.Duration;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
public class SyncCommit {
public static void main(String[] args) {
KafkaConsumer<Long, String> consumer = new KafkaConsumer<>(KafkaConfigProperties.getProperties());
consumer.subscribe(KafkaConfigProperties.getTopic());
ConsumerRecords<Long, String> messages = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord<Long, String> message : messages) {
// processed message
consumer.commitSync();
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.kafka.commitoffset.config;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
/**
* @author amitkumar
*/
public class KafkaConfigProperties {
public static final String MY_TOPIC = "my-topic";
public static Properties getProperties() {
Properties props = new Properties();
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "MyFirstConsumer");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
return props;
}
public static ArrayList<String> getTopic() {
ArrayList<String> topics = new ArrayList<>();
topics.add(MY_TOPIC);
return topics;
}
}

View File

@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -71,11 +71,6 @@
<version>${flink.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@ -2,3 +2,5 @@
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
- [Logging in Apache Camel](https://www.baeldung.com/java-apache-camel-logging)
- More articles: [[<-- prev]](../apache-libraries)

View File

@ -0,0 +1 @@
Welcome to Baeldung

View File

@ -0,0 +1,4 @@
{
"name" : "phillip",
"age" : 5
}

View File

@ -0,0 +1 @@
WELCOME TO BAELDUNG

View File

@ -0,0 +1 @@
{"name":"phillip","age":5,"transformedName":"PHILLIP","transformedAge":15}

View File

@ -24,24 +24,27 @@
<artifactId>camel-core</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-junit5</artifactId>
<version>${camel.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-main</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>
</dependencies>
<properties>
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
<camel.version>4.3.0</camel.version>
<camel.version>4.4.1</camel.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.main.Main;
public class CamelLoggingMainApp {
public static void main(String[] args) throws Exception {
Main main = new Main();
main.configure()
.addRoutesBuilder(new FileCopierCamelRoute());
main.run(args);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileCopierCamelRoute extends RouteBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(FileCopierCamelRoute.class);
public void configure() {
from("file:data/inbox?noop=true").log("We got an incoming file ${file:name} containing: ${body}")
.to("log:com.baeldung.apachecamellogging?level=INFO")
.process(process -> {
LOGGER.info("We are passing the message to a FileProcesor bean to capitalize the message body");
})
.bean(FileProcessor.class)
.to("file:data/outbox")
.to("log:com.baeldung.apachecamellogging?showBodyType=false&maxChars=20")
.log(LoggingLevel.DEBUG, "Output Process", "The Process ${id}")
.log("Successfully transfer file: ${file:name}");
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileCopierTracerCamelRoute extends RouteBuilder {
Logger logger = LoggerFactory.getLogger(FileCopierTracerCamelRoute.class);
public void configure() {
getContext().setTracing(true);
from("file:data/json?noop=true").to("log:input?level=INFO")
.unmarshal()
.json(JsonLibrary.Jackson)
.bean(FileProcessor.class, "transform")
.marshal()
.json(JsonLibrary.Jackson)
.to("file:data/output");
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.Body;
import java.util.Map;
public class FileProcessor {
public String process(@Body String fileContent) {
String processedContent = fileContent.toUpperCase();
return processedContent;
}
public Map<String, Object> transform(Map<String, Object> input) {
String name = (String) input.get("name");
int age = (int) input.get("age");
input.put("transformedName", name.toUpperCase());
input.put("transformedAge", age + 10);
return input;
}
}

View File

@ -1,4 +1,4 @@
package dynamicrouter;
package com.baeldung.dynamicrouter;
import com.baeldung.dynamicrouter.DynamicRouterRoute;
import org.apache.camel.RoutesBuilder;

View File

@ -13,3 +13,5 @@ This module contains articles about various Apache libraries and utilities
- [Introduction to Apache Curator](https://www.baeldung.com/apache-curator)
- [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)
- [Guide To Solr in Java With Apache SolrJ](https://www.baeldung.com/apache-solrj)
- More articles: [[next -->]](../apache-libraries-2)

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<name>apache-spark</name>
<packaging>jar</packaging>
<name>apache-spark</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-thrift</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-thrift</name>
<packaging>pom</packaging>
<name>apache-thrift</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-velocity</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-velocity</name>
<packaging>war</packaging>
<name>apache-velocity</name>
<parent>
<groupId>com.baeldung</groupId>
@ -28,7 +28,7 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${org.apache.httpcomponents.version}</version>
<version>${httpclient.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
@ -60,7 +60,7 @@
</build>
<properties>
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
<httpclient.version>4.5.2</httpclient.version>
<velocity-version>1.7</velocity-version>
<velocity-tools-version>2.0</velocity-tools-version>
</properties>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-dynamodb</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-dynamodb</name>
<packaging>jar</packaging>
<name>aws-dynamodb</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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>lambda-function</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>lambda-function</name>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>

View File

@ -4,8 +4,8 @@
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>aws-lambda-modules</artifactId>
<name>aws-lambda-modules</name>
<packaging>pom</packaging>
<name>aws-lambda-modules</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -3,8 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>ShippingFunction</artifactId>
<version>1.0</version>
<name>ShippingFunction</name>
<version>1.0</version>
<packaging>jar</packaging>
<parent>

View File

@ -4,8 +4,8 @@
<modelVersion>4.0.0</modelVersion>
<groupId>helloworld</groupId>
<artifactId>ToDoFunction</artifactId>
<version>1.0</version>
<name>ToDoFunction</name>
<version>1.0</version>
<packaging>jar</packaging>
<parent>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-miscellaneous</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-miscellaneous</name>
<packaging>jar</packaging>
<name>aws-miscellaneous</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -87,6 +87,7 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.version}</version>
</plugin>
</plugins>
</build>

View File

@ -12,3 +12,4 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object)
- [How To Rename Files and Folders in Amazon S3](https://www.baeldung.com/java-amazon-s3-rename-files-folders)
- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object)
- [How to Mock Amazon S3 for Integration Test](https://www.baeldung.com/java-amazon-simple-storage-service-mock-testing)

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-s3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-s3</name>
<packaging>jar</packaging>
<name>aws-s3</name>
<parent>
<groupId>com.baeldung</groupId>
@ -26,7 +26,6 @@
<version>${aws.java.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@ -56,7 +55,6 @@
<version>${com.adobe.testing.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>

View File

@ -4,6 +4,7 @@
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>aws-modules</artifactId>
<packaging>pom</packaging>
<name>aws-modules</name>
<parent>
@ -12,16 +13,6 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.12.523</version>
<scope>compile</scope>
</dependency>
</dependencies>
<packaging>pom</packaging>
<modules>
<module>aws-app-sync</module>
<module>aws-dynamodb</module>
@ -31,6 +22,15 @@
<module>aws-s3</module>
</modules>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.12.523</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
<aws-java-sdk-v2.version>2.24.9</aws-java-sdk-v2.version>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>azure</artifactId>
<version>0.1</version>
<name>azure</name>
<packaging>war</packaging>
<name>azure</name>
<description>Demo project for Spring Boot on Azure</description>
<parent>

View File

@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>checker-framework</artifactId>
<version>1.0-SNAPSHOT</version>
<name>checker-framework</name>
<packaging>jar</packaging>
<name>checker-framework</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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-10</artifactId>
<name>core-java-10</name>
<packaging>jar</packaging>
<name>core-java-10</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-11-2</artifactId>
<name>core-java-11-2</name>
<packaging>jar</packaging>
<name>core-java-11-2</name>
<parent>
<groupId>com.baeldung</groupId>
@ -15,11 +15,6 @@
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-junit-jupiter</artifactId>

View File

@ -4,8 +4,8 @@
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-11-3</artifactId>
<name>core-java-11-3</name>
<packaging>jar</packaging>
<name>core-java-11-3</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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-11</artifactId>
<name>core-java-11</name>
<packaging>jar</packaging>
<name>core-java-11</name>
<parent>
<groupId>com.baeldung</groupId>
@ -15,11 +15,6 @@
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>

View File

@ -4,8 +4,8 @@
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-12</artifactId>
<name>core-java-12</name>
<packaging>jar</packaging>
<name>core-java-12</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-13</artifactId>
<name>core-java-13</name>
<packaging>jar</packaging>
<name>core-java-13</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-14</artifactId>
<name>core-java-14</name>
<packaging>jar</packaging>
<name>core-java-14</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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-15</artifactId>
<name>core-java-15</name>
<packaging>jar</packaging>
<name>core-java-15</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
@ -13,7 +13,6 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>

View File

@ -4,8 +4,8 @@
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-16</artifactId>
<name>core-java-16</name>
<packaging>jar</packaging>
<name>core-java-16</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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-17</artifactId>
<name>core-java-17</name>
<packaging>jar</packaging>
<name>core-java-17</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,8 +4,8 @@
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-18</artifactId>
<name>core-java-18</name>
<packaging>jar</packaging>
<name>core-java-18</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -0,0 +1,44 @@
package com.baeldung.inetspi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.stream.Stream;
import com.baeldung.inetspi.providers.CustomAddressResolverImpl;
public class InetAddressSPI {
public String usingGetByName(String host) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(host);
return inetAddress.getHostAddress();
}
public String[] usingGetAllByName(String host) throws UnknownHostException {
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
return Arrays.stream(inetAddresses).map(InetAddress::getHostAddress).toArray(String[]::new);
}
public String usingGetByIp(byte[] ip) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByAddress(ip);
return inetAddress.getHostName();
}
public String usingGetByIpAndReturnsCannonName(byte[] ip) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByAddress(ip);
return inetAddress.getCanonicalHostName();
}
public String getHostUsingCustomImpl(byte[] ip) throws UnknownHostException {
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
return imp.get(null).lookupByAddress(ip);
}
public Stream<InetAddress> getIpUsingCustomImpl(String host) throws UnknownHostException {
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
return imp.get(null).lookupByName(host, null);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.inetspi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.stream.Stream;
public class Registry {
private final Map<String, List<byte[]>> registry;
private static final Logger LOGGER = Logger.getLogger(Registry.class.getName());
public Registry() {
registry = loadMapWithData();
}
public Stream<InetAddress> getAddressesfromHost(String host) throws UnknownHostException {
LOGGER.info("Performing Forward Lookup for HOST : " + host);
if (!registry.containsKey(host)) {
throw new UnknownHostException("Missing Host information in Resolver");
}
return registry.get(host)
.stream()
.map(add -> constructInetAddress(host, add))
.filter(Objects::nonNull);
}
public String getHostFromAddress(byte[] arr) throws UnknownHostException {
LOGGER.info("Performing Reverse Lookup for Address : " + Arrays.toString(arr));
for (Map.Entry<String, List<byte[]>> entry : registry.entrySet()) {
if (entry.getValue()
.stream()
.anyMatch(ba -> Arrays.equals(ba, arr))) {
return entry.getKey();
}
}
throw new UnknownHostException("Address Not Found");
}
private Map<String, List<byte[]>> loadMapWithData() {
return Map.of("baeldung-local.org", List.of(new byte[] { 1, 2, 3, 4 }));
}
private static InetAddress constructInetAddress(String host, byte[] address) {
try {
return InetAddress.getByAddress(host, address);
} catch (UnknownHostException unknownHostException) {
return null;
}
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.inetspi.providers;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.spi.InetAddressResolver;
import java.net.spi.InetAddressResolverProvider;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Stream;
import com.baeldung.inetspi.Registry;
public class CustomAddressResolverImpl extends InetAddressResolverProvider {
private static Logger LOGGER = Logger.getLogger(CustomAddressResolverImpl.class.getName());
private static Registry registry = new Registry();
@Override
public InetAddressResolver get(Configuration configuration) {
LOGGER.info("Using Custom Address Resolver :: " + this.name());
LOGGER.info("Registry initialised");
return new InetAddressResolver() {
@Override
public Stream<InetAddress> lookupByName(String host, LookupPolicy lookupPolicy) throws UnknownHostException {
return registry.getAddressesfromHost(host);
}
@Override
public String lookupByAddress(byte[] addr) throws UnknownHostException {
return registry.getHostFromAddress(addr);
}
};
}
@Override
public String name() {
return "CustomInternetAddressResolverImpl";
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.inetspi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
public class InetAddressSPIUnitTest {
@Test
public void givenInetAddress_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
InetAddressSPI spi = new InetAddressSPI();
Assert.assertNotNull(spi.usingGetByName("www.google.com"));
Assert.assertTrue(spi.usingGetAllByName("www.google.com").length > 1);
Assert.assertNotNull(spi.usingGetByIp(InetAddress.getByName("www.google.com")
.getAddress()));
Assert.assertNotNull(spi.usingGetByIpAndReturnsCannonName(InetAddress.getByName("www.google.com")
.getAddress()));
}
@Test
public void givenCustomInetAddressImplementation_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
InetAddressSPI spi = new InetAddressSPI();
Assert.assertEquals("baeldung-local.org", spi.getHostUsingCustomImpl(new byte[] { 1, 2, 3, 4 }));
Stream<InetAddress> response = spi.getIpUsingCustomImpl("baeldung-local.org");
Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4 }, response.findFirst()
.get()
.getAddress());
}
}

View File

@ -13,4 +13,5 @@
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
- [Check if a Given Time Lies Between Two Times Regardless of Date](https://www.baeldung.com/java-check-between-two-times)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)

View File

@ -4,8 +4,8 @@
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-8-datetime-2</artifactId>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
<name>core-java-8-datetime-2</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -0,0 +1,45 @@
package com.baeldung.checkiftimebetweentwotimes;
import org.junit.Test;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertTrue;
public class CheckIfTimeBetweenTwoTimesUnitTest {
private LocalTime startTime = LocalTime.parse("09:00:00");
private LocalTime endTime = LocalTime.parse("17:00:00");
private LocalTime targetTime = LocalTime.parse("12:30:00");
@Test
public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() {
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime));
}
@Test
public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() {
assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0);
}
@Test
public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(Calendar.HOUR_OF_DAY, 9);
startCalendar.set(Calendar.MINUTE, 0);
Date startTime = startCalendar.getTime();
Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.HOUR_OF_DAY, 17);
endCalendar.set(Calendar.MINUTE, 0);
Date endTime = endCalendar.getTime();
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(Calendar.HOUR_OF_DAY, 12);
targetCalendar.set(Calendar.MINUTE, 30);
Date targetTime = targetCalendar.getTime();
assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime));
}
}

View File

@ -4,8 +4,8 @@
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-8-datetime</artifactId>
<name>core-java-8-datetime</name>
<packaging>jar</packaging>
<name>core-java-8-datetime</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -5,7 +5,7 @@ This module contains articles about Project Jigsaw and the Java Platform Module
### Relevant Articles:
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [A Guide to Java Modularity](https://www.baeldung.com/java-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
- [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing)

View File

@ -3,20 +3,14 @@
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>library-core</artifactId>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-9-jigsaw</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>library-core</artifactId>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -52,4 +46,11 @@
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -4,8 +4,9 @@
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-9-jigsaw</artifactId>
<name>core-java-9-jigsaw</name>
<packaging>pom</packaging>
<name>core-java-9-jigsaw</name>
<modules>
<module>library-core</module>
</modules>

View File

@ -4,8 +4,8 @@
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-9-streams</artifactId>
<name>core-java-9-streams</name>
<packaging>jar</packaging>
<name>core-java-9-streams</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-annotations</artifactId>
<name>core-java-annotations</name>
<packaging>jar</packaging>
<name>core-java-annotations</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-convert</artifactId>
<name>core-java-arrays-convert</name>
<packaging>jar</packaging>
<name>core-java-arrays-convert</name>
<parent>
<artifactId>core-java-modules</artifactId>
@ -20,4 +20,5 @@
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -4,8 +4,8 @@
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-guides</artifactId>
<name>core-java-arrays-guides</name>
<packaging>jar</packaging>
<name>core-java-arrays-guides</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -4,8 +4,8 @@
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-multidimensional</artifactId>
<name>core-java-arrays-multidimensional</name>
<packaging>jar</packaging>
<name>core-java-arrays-multidimensional</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -2,3 +2,4 @@
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
- [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element)

View File

@ -4,8 +4,8 @@
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-operations-advanced-2</artifactId>
<name>core-java-arrays-operations-advanced-2</name>
<packaging>jar</packaging>
<name>core-java-arrays-operations-advanced-2</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -0,0 +1,95 @@
package com.baeldung.majorityelement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class FindMajorityElement {
public static Integer findMajorityElementUsingForLoop(int[] nums) {
int majorityThreshold = nums.length / 2;
Integer majorityElement = null;
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[i] == nums[j]) {
count++;
}
}
if (count > majorityThreshold) {
return majorityElement = nums[i];
}
}
return majorityElement;
}
public static Integer findMajorityElementUsingSorting(int[] nums) {
Arrays.sort(nums);
int majorityThreshold = nums.length / 2;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == nums[majorityThreshold]) {
count++;
}
if (count > majorityThreshold) {
return nums[majorityThreshold];
}
}
return null;
}
public static Integer findMajorityElementUsingHashMap(int[] nums) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int majorityThreshold = nums.length / 2;
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() > majorityThreshold) {
return entry.getKey();
}
}
return null;
}
public static Integer findMajorityElementUsingMooreVoting(int[] nums) {
int majorityThreshold = nums.length / 2;
int candidate = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
candidate = nums[i];
count = 1;
} else if (candidate == nums[i]) {
count++;
} else {
count--;
}
System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]");
}
count = 0;
for (int num : nums) {
if (num == candidate) {
count++;
}
}
return count > majorityThreshold ? candidate : null;
}
public static void main(String[] args) {
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
Integer majorityElement = findMajorityElementUsingMooreVoting(nums);
if (majorityElement != null) {
System.out.println("Majority element with maximum occurrences: " + majorityElement);
} else {
System.out.println("No majority element found");
}
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.majorityelement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class FindMajorityElementUnitTest {
@Test
void givenArrayWithMajorityElement_WhenUsingForLoop_ThenReturnFound() {
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
Integer result = FindMajorityElement.findMajorityElementUsingForLoop(nums);
assertEquals(2, result);
}
@Test
void givenArrayWithoutMajorityElement_WhenUsingForLoop_ThenNotFound() {
int[] nums = { 2, 2, 3, 3 };
Integer result = FindMajorityElement.findMajorityElementUsingForLoop(nums);
assertEquals(null, result);
}
@Test
public void givenArrayWithMajorityElement_WhenUsingSorting_ThenReturnFound() {
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
Integer result = FindMajorityElement.findMajorityElementUsingSorting(nums);
assertEquals(2, result);
}
@Test
public void givenArrayWithoutMajorityElement_WhenUsingSorting_ThenNotFound() {
int[] nums = { 2, 2, 3, 3 };
Integer result = FindMajorityElement.findMajorityElementUsingSorting(nums);
assertEquals(null, result);
}
@Test
void givenArrayWithMajorityElement_WhenUsingHashMap_ThenReturnFound() {
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
Integer result = FindMajorityElement.findMajorityElementUsingHashMap(nums);
assertEquals(2, result);
}
@Test
void givenArrayWithoutMajorityElement_WhenUsingHashMap_ThenNotFound() {
int[] nums = { 2, 2, 3, 3 };
Integer result = FindMajorityElement.findMajorityElementUsingHashMap(nums);
assertEquals(null, result);
}
@Test
void givenArrayWithMajorityElement_WhenUsingMooreVoting_ThenReturnFound() {
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
Integer result = FindMajorityElement.findMajorityElementUsingMooreVoting(nums);
assertEquals(2, result);
}
@Test
void givenArrayWithoutMajorityElement_WhenUsingMooreVoting_ThenNotFound() {
int[] nums = { 2, 2, 3, 3 };
Integer result = FindMajorityElement.findMajorityElementUsingMooreVoting(nums);
assertEquals(null, result);
}
}

View File

@ -4,8 +4,8 @@
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-operations-advanced</artifactId>
<name>core-java-arrays-operations-advanced</name>
<packaging>jar</packaging>
<name>core-java-arrays-operations-advanced</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -4,8 +4,8 @@
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-operations-basic-2</artifactId>
<name>core-java-arrays-operations-basic-2</name>
<packaging>jar</packaging>
<name>core-java-arrays-operations-basic-2</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -4,8 +4,8 @@
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-operations-basic</artifactId>
<name>core-java-arrays-operations-basic</name>
<packaging>jar</packaging>
<name>core-java-arrays-operations-basic</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -4,8 +4,8 @@
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-sorting</artifactId>
<name>core-java-arrays-sorting</name>
<packaging>jar</packaging>
<name>core-java-arrays-sorting</name>
<parent>
<artifactId>core-java-modules</artifactId>

View File

@ -4,8 +4,8 @@
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-booleans</artifactId>
<name>core-java-booleans</name>
<packaging>jar</packaging>
<name>core-java-booleans</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-char</artifactId>
<name>core-java-char</name>
<packaging>jar</packaging>
<name>core-java-char</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -4,8 +4,8 @@
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-collections-2</artifactId>
<name>core-java-collections-2</name>
<packaging>jar</packaging>
<name>core-java-collections-2</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

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