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
1318 changed files with 13954 additions and 4095 deletions
+1 -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>akka-modules</artifactId>
<name>akka-modules</name>
<packaging>pom</packaging>
<name>akka-modules</name>
<parent>
<artifactId>parent-modules</artifactId>
@@ -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>
@@ -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>
@@ -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);
}
}
@@ -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};
}
}
@@ -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)
@@ -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());
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -0,0 +1,2 @@
### Relevant Articles:
- [Vigenère Cipher in Java](https://www.baeldung.com/java-vigenere-cipher)
@@ -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>
@@ -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);
}
}
@@ -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;
}
}
@@ -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
}
}
@@ -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;
}
}
@@ -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());
}
}
@@ -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");
}
}
@@ -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);
}
}
+2 -1
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>
+1 -1
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>
+2 -1
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>
+1 -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>sse-jaxrs</artifactId>
<name>sse-jaxrs</name>
<packaging>pom</packaging>
<name>sse-jaxrs</name>
<parent>
<groupId>com.baeldung</groupId>
@@ -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>
+3 -9
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>
+1
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
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
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>
@@ -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();
}
}
}
@@ -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
}
}
}

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