Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima 2022-08-25 16:55:26 -03:00 committed by GitHub
commit 6bd4ff5165
1428 changed files with 7208 additions and 3423 deletions

View File

@ -11,4 +11,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
- [Permutations of a String in Java](https://www.baeldung.com/java-string-permutations)
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)

View File

@ -1,14 +1,20 @@
package com.baeldung.algorithms.stringpermutation;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayHelper {
public class Helper {
private ArrayHelper() {
private Helper() {
}
static List<Character> toCharacterList(final String string) {
return string.chars().mapToObj(s -> ((char) s)).collect(Collectors.toList());
}
static String toString(Collection<Character> collection) {
return collection.stream().map(Object::toString).collect(Collectors.joining());
}
}

View File

@ -1,20 +1,29 @@
package com.baeldung.algorithms.stringpermutation;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.iterators.PermutationIterator;
public class StringPermutationsApache {
public Collection<List<Character>> eagerPermutationWithRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return CollectionUtils.permutations(characters);
public List<String> eagerPermutationWithRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return CollectionUtils.permutations(characters)
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public PermutationIterator<Character> lazyPermutationWithoutRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return new PermutationIterator<>(characters);
public List<String> lazyPermutationWithoutRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
final PermutationIterator<Character> permutationIterator = new PermutationIterator<>(characters);
final List<String> result = new ArrayList<>();
while (permutationIterator.hasNext()) {
result.add(Helper.toString(permutationIterator.next()));
}
return result;
}
}

View File

@ -7,19 +7,21 @@ import org.paukov.combinatorics3.PermutationGenerator.TreatDuplicatesAs;
public class StringPermutationsCombinatoricsLib {
public List<List<Character>> permutationWithoutRepetitions(final String string) {
List<Character> chars = ArrayHelper.toCharacterList(string);
public List<String> permutationWithoutRepetitions(final String string) {
List<Character> chars = Helper.toCharacterList(string);
return Generator.permutation(chars)
.simple()
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public List<List<Character>> permutationWithRepetitions(final String string) {
List<Character> chars = ArrayHelper.toCharacterList(string);
public List<String> permutationWithRepetitions(final String string) {
List<Character> chars = Helper.toCharacterList(string);
return Generator.permutation(chars)
.simple(TreatDuplicatesAs.IDENTICAL)
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}

View File

@ -1,18 +1,22 @@
package com.baeldung.algorithms.stringpermutation;
import com.google.common.collect.Collections2;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class StringPermutationsGuava {
public Collection<List<Character>> permutationWithRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return Collections2.permutations(characters);
public List<String> permutationWithRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return Collections2.permutations(characters).stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public Collection<List<Character>> permutationWithoutRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return Collections2.orderedPermutations(characters);
public List<String> permutationWithoutRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return Collections2.orderedPermutations(characters).stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class HelperUnitTest {
@ParameterizedTest
@MethodSource("stringProvider")
void toListTest(String value, List<Character> expected) {
final List<Character> actual = Helper.toCharacterList(value);
assertThat(expected).isEqualTo(actual);
}
@ParameterizedTest
@MethodSource("stringProvider")
void toStringTest(String expected, List<Character> value) {
final String actual = Helper.toString(value);
assertThat(expected).isEqualTo(actual);
}
static Stream<Arguments> stringProvider() {
return Stream.of(
Arguments.of("hello", Arrays.asList('h', 'e', 'l', 'l', 'o')),
Arguments.of("abc", Arrays.asList('a','b','c')),
Arguments.of("12345", Arrays.asList('1', '2', '3', '4', '5'))
);
}
}

View File

@ -2,22 +2,19 @@ package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.List;
import org.apache.commons.collections4.iterators.PermutationIterator;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class StringPermutationsApacheUnitTest {
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 120",
"aaaaaa, 720"})
@DisplayName("Apache permutation for ")
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsApache permutationGenerator = new StringPermutationsApache();
final Collection<List<Character>> permutations = permutationGenerator.eagerPermutationWithRepetitions(string);
final List<String> permutations = permutationGenerator.eagerPermutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@ -30,12 +27,8 @@ class StringPermutationsApacheUnitTest {
"aaaaaa, 720"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsApache permutationGenerator = new StringPermutationsApache();
final PermutationIterator<Character> permutations = permutationGenerator.lazyPermutationWithoutRepetitions(string);
int size = 0;
while (permutations.hasNext()) {
permutations.next();
++size;
}
final List<String> permutations = permutationGenerator.lazyPermutationWithoutRepetitions(string);
int size = permutations.size();
assertThat(size)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.isEqualTo(numberOfPermutations);

View File

@ -14,7 +14,7 @@ class StringPermutationsCombinatoricsLibUnitTest {
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsCombinatoricsLib permutationGenerator = new StringPermutationsCombinatoricsLib();
final List<List<Character>> permutations = permutationGenerator.permutationWithRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@ -27,7 +27,7 @@ class StringPermutationsCombinatoricsLibUnitTest {
"aaaaaa, 1"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsCombinatoricsLib permutationGenerator = new StringPermutationsCombinatoricsLib();
final List<List<Character>> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)

View File

@ -2,7 +2,6 @@ package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@ -15,7 +14,7 @@ class StringPermutationsGuavaUnitTest {
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsGuava permutationGenerator = new StringPermutationsGuava();
final Collection<List<Character>> permutations = permutationGenerator.permutationWithRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@ -28,7 +27,7 @@ class StringPermutationsGuavaUnitTest {
"aaaaaa, 1"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsGuava permutationGenerator = new StringPermutationsGuava();
final Collection<List<Character>> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)

View File

@ -0,0 +1,16 @@
<?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>algorithms-miscellaneous-7</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-7</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,73 @@
package com.baeldung.algorithms.luhn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LuhnChecker {
private static final Logger LOGGER = LoggerFactory.getLogger(LuhnChecker.class);
/*
* Starting from the rightmost digit, we add all the digits together, performing
* a special step for every second digit.
*
* If the result is not divisible by 10, then the card number must not be valid.
*
* We can form a number that passes the Luhn Check by subtracting the result of
* the Luhn algorithm from 10.
*
* This is how the final digit of a credit card is calculated.
*/
public static boolean checkLuhn(String cardNumber) {
int sum = 0;
try {
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
if ((cardNumber.length() - i) % 2 == 0) {
digit = doubleAndSumDigits(digit);
}
sum += digit;
}
LOGGER.info("Luhn Algorithm sum of digits is " + sum);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException - Card number probably contained some non-numeric characters, returning false");
return false;
} catch (NullPointerException e) {
LOGGER.error("Null pointer - Card number was probably null, returning false");
return false;
}
boolean result = sum % 10 == 0;
LOGGER.info("Luhn check result (sum divisible by 10): " + result);
return result;
}
/*
* We apply this method to every second number from the right of the card
* number. First, we double the digit, then we sum the digits.
*
* Note: subtracting 9 is equivalent to doubling and summing digits (when
* starting with a single digit) 0-4 -> produce single digit when doubled
* 5*2 = 10 -> 1+0 = 1 = 10-9
* 6*2 = 12 -> 1+3 = 3 = 12-9
* 7*2 = 14 -> 1+5 = 5 = 14-9
* 8*2 = 16 -> 1+7 = 7 = 16-9
* 9*2 = 18 -> 1+9 = 9 = 18-9
*/
public static int doubleAndSumDigits(int digit) {
int ret = digit * 2;
if (ret > 9) {
ret -= 9;
}
return ret;
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.algorithms.luhn;
import org.junit.Assert;
import org.junit.Test;
public class LuhnCheckerUnitTest {
@Test
public void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() {
String cardNumber = "8649";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
}
@Test
public void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() {
String cardNumber = "8642";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
}
@Test
public void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "0505050505050505";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
}
@Test
public void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "75757575757575";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
}
@Test
public void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() {
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(0), 0);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(1), 2);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(2), 4);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(3), 6);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(4), 8);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(5), 1);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(6), 3);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(7), 5);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(8), 7);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(9), 9);
}
@Test
public void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() {
String cardNumber = "test";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
}
@Test
public void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() {
String cardNumber = null;
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
}
}

View File

@ -21,6 +21,7 @@
<module>algorithms-miscellaneous-4</module>
<module>algorithms-miscellaneous-5</module>
<module>algorithms-miscellaneous-6</module>
<module>algorithms-miscellaneous-7</module>
<module>algorithms-searching</module>
<module>algorithms-sorting</module>
<module>algorithms-sorting-2</module>

View File

@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-cxf-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-cxf</name>
<name>apache-cxf-modules</name>
<packaging>pom</packaging>
<parent>

9
apache-kafka-2/README.md Normal file
View File

@ -0,0 +1,9 @@
## 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:
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)

View File

@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout

68
apache-kafka-2/pom.xml Normal file
View File

@ -0,0 +1,68 @@
<?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-2</artifactId>
<name>apache-kafka-2</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.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>kafka</artifactId>
<version>${testcontainers-kafka.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<kafka.version>2.8.0</kafka.version>
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
</properties>
</project>

View File

@ -0,0 +1,35 @@
package com.baeldung.kafka;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.common.Node;
public class KafkaAdminClient {
private final AdminClient client;
public KafkaAdminClient(String bootstrap) {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrap);
props.put("request.timeout.ms", 3000);
props.put("connections.max.idle.ms", 5000);
this.client = AdminClient.create(props);
}
public boolean verifyConnection() throws ExecutionException, InterruptedException {
Collection<Node> nodes = this.client.describeCluster()
.nodes()
.get();
return nodes != null && nodes.size() > 0;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
String defaultBootStrapServer = "localhost:9092";
KafkaAdminClient kafkaAdminClient = new KafkaAdminClient(defaultBootStrapServer);
System.out.println(kafkaAdminClient.verifyConnection());
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.kafka;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import static org.assertj.core.api.Assertions.assertThat;
// This live test needs a running Docker instance so that a kafka container can be created
@Testcontainers
class KafkaConnectionLiveTest {
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"));
private KafkaAdminClient kafkaAdminClient;
@BeforeEach
void setup() {
KAFKA_CONTAINER.addExposedPort(9092);
this.kafkaAdminClient = new KafkaAdminClient(KAFKA_CONTAINER.getBootstrapServers());
}
@AfterEach
void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void givenKafkaIsRunning_whenCheckedForConnection_thenConnectionIsVerified() throws Exception {
boolean alive = kafkaAdminClient.verifyConnection();
assertThat(alive).isTrue();
}
}

View File

@ -173,7 +173,6 @@
<graphframes.version>0.8.1-spark3.0-s_2.12</graphframes.version>
<com.datastax.spark.spark-cassandra-connector.version>2.5.2</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.6.0-M1</com.datastax.spark.spark-cassandra-connector-java.version>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>

View File

@ -11,6 +11,9 @@ spring:
open-in-view: false
hibernate:
ddl-auto: update
properties:
hibernate:
globally_quoted_identifiers: true
sql:
init:

View File

@ -1,12 +1,10 @@
insert into car_maker(id,name) values (1,'Special Motors');
insert into car_maker(id,name) values (2,'BWM');
insert into car_maker(id,name) values (3,'Dolores');
insert into "car_maker"("id", "name") values (1,'Special Motors');
insert into "car_maker"("id", "name") values (2,'BWM');
insert into "car_maker"("id", "name") values (3,'Dolores');
insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018);
insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(1,1,'Muze','SM001',2018);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(2,1,'Empada','SM002',2008);
insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008);
insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009);
insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008);
alter sequence hibernate_sequence restart with 100;
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(4,2,'BWM-100','BWM100',2008);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(5,2,'BWM-200','BWM200',2009);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(6,2,'BWM-300','BWM300',2008);

View File

@ -8,4 +8,5 @@ This module contains articles about the Java List collection
- [Sort a List Alphabetically in Java](https://www.baeldung.com/java-sort-list-alphabetically)
- [Arrays.asList() vs Collections.singletonList()](https://www.baeldung.com/java-aslist-vs-singletonlist)
- [Replace Element at a Specific Index in a Java ArrayList](https://www.baeldung.com/java-arraylist-replace-at-index)
- [Difference Between Arrays.asList() and List.of()](https://www.baeldung.com/java-arrays-aslist-vs-list-of)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-3)

View File

@ -64,6 +64,23 @@
<colt.version>1.2.0</colt.version>
<apache-commons.version>3.0</apache-commons.version>
<assertj.version>3.22.0</assertj.version>
<maven.compiler.source.version>17</maven.compiler.source.version>
<maven.compiler.target.version>17</maven.compiler.target.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,56 @@
package com.baeldung.list.creation;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ArraysAsListUnitTest {
@Test
void givenAnArrayOfIntegersWhenCreatingAListUsingArraysAsListThenItWillHaveTheSameElementsInTheSameOrder() {
Integer[] array = new Integer[]{1, 2, 3, 4};
List<Integer> list = Arrays.asList(array);
assertThat(list).containsExactly(1, 2, 3, 4);
}
@Test
void givenAnListOfIntegersCreatedUsingArraysAsListWhenChangingTheOriginalArrayTheReturnListWillAlsoChange() {
Integer[] array = new Integer[]{1, 2, 3};
List<Integer> list = Arrays.asList(array);
array[0] = 1000;
assertThat(list.get(0)).isEqualTo(1000);
}
@Test
void givenAnListOfIntegersCreatedUsingArraysAsListWhenChangingTheReturnedListTheOriginalArrayWillAlsoChange() {
Integer[] array = new Integer[]{1, 2, 3};
List<Integer> list = Arrays.asList(array);
list.set(0, 1000);
assertThat(array[0]).isEqualTo(1000);
}
@Test
void givenAnArrayOfIntegersCreatedUsingArraysAsListWhenModifyingAnExistingElementThenModifyIt() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.set(1, 1000);
assertThat(list.get(1)).isEqualTo(1000);
}
@Test
void givenAnArrayCreatedWithArraysAsListWhenAddingANewElementThenUnsupportedOperationExceptionIsThrown() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
assertThrows(UnsupportedOperationException.class, () -> list.add(6));
}
@Test
void givenAnArrayCreatedWithArraysAsListWhenRemovingAnExistingElementThenUnsupportedOperationExceptionIsThrown() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
assertThrows(UnsupportedOperationException.class, () -> list.remove(1));
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.list.creation;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ListOfUnitTest {
@Test
void givenAnArrayOfStringWhenCreatingAListUsingItsValuesThenItWillHaveTheSameElementsInTheSameOrder() {
String[] array = new String[]{"one", "two", "three"};
List<String> list = List.of(array);
assertThat(list).containsExactly("one", "two", "three");
}
@Test
void givenAnListOfStringCreatedUsingListOfWhenChangingTheOriginalArrayTheReturnListWontChange() {
String[] array = new String[]{"one", "two", "three"};
List<String> list = List.of(array);
array[0] = "thousand";
assertThat(list.get(0)).isEqualTo("one");
}
@Test
void givenAnArrayCreatedWithListOfWhenAddingANewElementThenUnsupportedOperationExceptionIsThrown() {
List<String> list = List.of("one", "two", "three");
assertThrows(UnsupportedOperationException.class, () -> list.add("four"));
}
@Test
void givenAnArrayCreatedWithListOfWhenRemovingAnExistingElementThenUnsupportedOperationExceptionIsThrown() {
List<String> list = List.of("one", "two", "three");
assertThrows(UnsupportedOperationException.class, () -> list.remove("two"));
}
@Test
void givenAnArrayCreatedWithListOfWhenModifyingAnExistingElementThenUnsupportedOperationExceptionIsThrown() {
List<String> list = List.of("one", "two", "three");
assertThrows(UnsupportedOperationException.class, () -> list.set(1, "four"));
}
@Test
void givenAnArrayContainingNullElementWhenUsingItToCreateListThenNullPointerExceptionIsThrown() {
assertThrows(NullPointerException.class, () -> List.of("one", null, "two"));
}
}

View File

@ -4,7 +4,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CountdownLatchResetExampleUnitTest {
public class CountdownLatchResetExampleManualTest {
@Test
public void whenCountDownLatch_noReset() {

View File

@ -8,3 +8,4 @@
- [Acquire a Lock by a Key in Java](https://www.baeldung.com/java-acquire-lock-by-key)
- [Differences Between set() and lazySet() in Java Atomic Variables](https://www.baeldung.com/java-atomic-set-vs-lazyset)
- [Volatile vs. Atomic Variables in Java](https://www.baeldung.com/java-volatile-vs-atomic)
- [What Is “Locked Ownable Synchronizers” in Thread Dump?](https://www.baeldung.com/locked-ownable-synchronizers)

View File

@ -0,0 +1,45 @@
package com.baeldung.ownablesynchronizers;
import java.util.concurrent.locks.ReentrantLock;
public class Application {
public static Thread createThread(ReentrantLock mainLock, ReentrantLock otherLock, String threadName) {
return new Thread(() -> {
try {
mainLock.lock();
// synchronized block here allows us to wait for other thread to lock,
// in order to simulate a deadlock
synchronized (Application.class) {
Application.class.notify();
if (!otherLock.isLocked()) {
Application.class.wait();
}
}
// thread will hang here
otherLock.lock();
System.out.println(threadName + ": Finished");
mainLock.unlock();
otherLock.unlock();
} catch (InterruptedException e) {
System.out.println(threadName + ": " + e.getMessage());
}
});
}
public static void main(String[] args) throws Exception {
ReentrantLock firstLock = new ReentrantLock(true);
ReentrantLock secondLock = new ReentrantLock(true);
Thread first = createThread(firstLock, secondLock, "Thread-0");
Thread second = createThread(secondLock, firstLock, "Thread-1");
first.start();
second.start();
first.join();
second.join();
}
}

View File

@ -2,9 +2,9 @@
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>java-concurrency-simple</artifactId>
<artifactId>core-java-concurrency-simple</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-concurrency-simple</name>
<name>core-java-concurrency-simple</name>
<packaging>jar</packaging>
<parent>
@ -14,7 +14,7 @@
</parent>
<build>
<finalName>java-concurrency-simple</finalName>
<finalName>core-java-concurrency-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>

View File

@ -7,6 +7,6 @@ public class JarAppUnitTest {
@Test
public void findClassTest(){
Assert.assertTrue(JarApp.findObjectMapperClass().endsWith("jackson-databind-2.13.0.jar"));
Assert.assertTrue(JarApp.findObjectMapperClass().endsWith("jackson-databind-2.13.3.jar"));
}
}

View File

@ -6,3 +6,4 @@ This module contains articles about core features in the Java language
- [Difference Between == and equals() in Java](https://www.baeldung.com/java-equals-method-operator-difference)
- [Advantages and Disadvantages of Using Java Wildcard Imports](https://www.baeldung.com/java-wildcard-imports)
- [Toggle a Boolean Variable in Java](https://www.baeldung.com/java-toggle-boolean)

View File

@ -0,0 +1,10 @@
package com.baeldung.toggleboolean;
public class ToggleBoolean {
public static Boolean toggle(Boolean b) {
if (b == null) {
return b;
}
return !b;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.toggleboolean;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class ToggleBooleanUnitTest {
@Test
void givenPrimitiveBoolean_whenUsingNotOperator_shouldToggleTheBoolean() {
boolean b = true;
b = !b;
assertFalse(b);
b = !b;
assertTrue(b);
}
@Test
void givenNullBoxedBoolean_whenUsingNotOperator_shouldThrowNPE() {
assertThatThrownBy(() -> {
Boolean b = null;
b = !b;
}).isInstanceOf(NullPointerException.class);
}
@Test
void givenPrimitiveBoolean_whenUsingXorOperator_shouldToggleTheBoolean() {
boolean b = true;
b ^= true;
assertFalse(b);
b ^= true;
assertTrue(b);
}
@Test
void givenBooleanObj_whenToggle_shouldGetExpectedResult() {
//boxed Boolean
Boolean b = true;
b = ToggleBoolean.toggle(b);
assertFalse(b);
b = ToggleBoolean.toggle(b);
assertTrue(b);
b = null;
b = ToggleBoolean.toggle(b);
assertNull(b);
//primitive boolean
boolean bb = true;
bb = ToggleBoolean.toggle(bb);
assertFalse(bb);
bb = ToggleBoolean.toggle(bb);
assertTrue(bb);
}
}

View File

@ -33,7 +33,6 @@
</dependencies>
<properties>
<lombok.version>1.18.22</lombok.version>
<commons-lang.version>2.6</commons-lang.version>
<assertj-core.version>3.10.0</assertj-core.version>
<equalsverifier.version>3.0.3</equalsverifier.version>

View File

@ -90,7 +90,6 @@
<jgonian.commons-ip-math.version>1.32</jgonian.commons-ip-math.version>
<googlecode.ipv6.version>0.17</googlecode.ipv6.version>
<javax.mail.version>1.6.2</javax.mail.version>
<guava.version>31.0-jre</guava.version>
</properties>
</project>

View File

@ -1,3 +1,5 @@
### Relevant Articles:
- [Check if a Number Is Odd or Even](https://www.baeldung.com/java-check-number-parity)
- [How to Check Whether an Integer Exists in a Range with Java](https://www.baeldung.com/java-interval-contains-integer)
- [Check if a Number Is Positive or Negative in Java](https://www.baeldung.com/java-check-number-positive-negative)
- [Armstrong Numbers in Java](https://www.baeldung.com/java-armstrong-numbers)

View File

@ -0,0 +1,44 @@
package com.baeldung.armstrong;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArmstrongNumberUtil {
public static boolean isArmstrong(int n) {
if (n < 0) {
return false;
}
List<Integer> digitsList = digitsInList(n);
int len = digitsList.size();
int sum = digitsList.stream()
.mapToInt(d -> (int) Math.pow(d, len))
.sum();
// alternatively, we can use the reduce() method:
// int sum = digits.stream()
// .reduce(0, (subtotal, digit) -> subtotal + (int) Math.pow(digit, len));
return n == sum;
}
private static List<Integer> digitsInList(int n) {
List<Integer> list = new ArrayList<>();
while (n > 0) {
list.add(n % 10);
n = n / 10;
}
return list;
}
public static List<Integer> getA005188Sequence(int limit) {
if (limit < 0) {
throw new IllegalArgumentException("The limit cannot be a negative number.");
}
return IntStream.range(0, limit)
.boxed()
.filter(ArmstrongNumberUtil::isArmstrong)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.positivenegative;
public class PositiveOrNegative {
enum Result {
POSITIVE, NEGATIVE, ZERO
}
public static Result byOperator(Integer integer) {
if (integer > 0) {
return Result.POSITIVE;
} else if (integer < 0) {
return Result.NEGATIVE;
}
return Result.ZERO;
}
public static Result bySignum(Integer integer) {
int result = Integer.signum(integer);
if (result == 1) {
return Result.POSITIVE;
} else if (result == -1) {
return Result.NEGATIVE;
}
return Result.ZERO;
}
public static Result bySignum(Float floatNumber) {
float result = Math.signum(floatNumber);
if (result == 1.0f) {
return Result.POSITIVE;
} else if (result == -1.0f) {
return Result.NEGATIVE;
}
return Result.ZERO;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.armstrong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
class ArmstrongNumberUtilUnitTest {
// @formatter:off
private static final Map<Integer, Boolean> ARMSTRONG_MAP = ImmutableMap.of(
0, true,
1, true,
2, true,
153, true,
370, true,
407, true,
42, false,
777, false,
12345, false);
// @formatter:on
private static final List<Integer> A005188_SEQ_1K = ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407);
private static final List<Integer> A005188_SEQ_10K = ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474);
@Test
void givenIntegers_whenCheckArmstrong_shouldReturnExpectedResult() {
ARMSTRONG_MAP.forEach((number, result) -> assertEquals(result, ArmstrongNumberUtil.isArmstrong(number)));
}
@Test
void givenALimit_whenFindArmstrong_shouldReturnExpectedResult() {
assertEquals(A005188_SEQ_1K, ArmstrongNumberUtil.getA005188Sequence(1000));
assertEquals(A005188_SEQ_10K, ArmstrongNumberUtil.getA005188Sequence(10000));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.positivenegative;
import org.junit.jupiter.api.Test;
import static com.baeldung.positivenegative.PositiveOrNegative.Result.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PositiveOrNegativeUnitTest {
@Test
void givenIntegers_whenChkPositiveOrNegativeByOperator_thenReturnExpectedResult() {
assertEquals(POSITIVE, PositiveOrNegative.byOperator(42));
assertEquals(ZERO, PositiveOrNegative.byOperator(0));
assertEquals(NEGATIVE, PositiveOrNegative.byOperator(-700));
}
@Test
void givenIntegers_whenChkPositiveOrNegativeBySignum_thenReturnExpectedResult() {
assertEquals(POSITIVE, PositiveOrNegative.bySignum(42));
assertEquals(ZERO, PositiveOrNegative.bySignum(0));
assertEquals(NEGATIVE, PositiveOrNegative.bySignum(-700));
}
@Test
void givenFloats_whenChkPositiveOrNegativeBySignum_thenReturnExpectedResult() {
assertEquals(POSITIVE, PositiveOrNegative.bySignum(4.2f));
assertEquals(ZERO, PositiveOrNegative.bySignum(0f));
assertEquals(NEGATIVE, PositiveOrNegative.bySignum(-7.7f));
}
}

View File

@ -81,7 +81,6 @@
<maven.compiler.target>1.9</maven.compiler.target>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.18.22</lombok.version>
</properties>
</project>

View File

@ -66,8 +66,4 @@
</plugins>
</build>
<properties>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>

View File

@ -3,3 +3,4 @@
- [Count Occurrences Using Java groupingBy Collector](https://www.baeldung.com/java-groupingby-count)
- [How to Split a Stream into Multiple Streams](https://www.baeldung.com/java-split-stream)
- [Filter Java Stream to 1 and Only 1 Element](https://www.baeldung.com/java-filter-stream-unique-element)
- [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition)

View File

@ -53,6 +53,12 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,89 @@
package com.baeldung.streams.multiplefilters;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
public class MultipleFiltersVsComplexConditionFilterOrderUnitTest {
AtomicInteger numberOfOperations = new AtomicInteger();
@Before
public void beforeEach() {
numberOfOperations.set(0);
}
@Test
public void givenWrongFilterOrder_whenUsingMultipleFilters_shouldEvaluateManyConditions() {
long filteredStreamSize = IntStream.range(0, 100)
.boxed()
.filter(this::isEvenNumber)
.filter(this::isSmallerThanTwenty)
.count();
assertThat(filteredStreamSize).isEqualTo(10);
assertThat(numberOfOperations).hasValue(150);
}
@Test
public void givenWrongFilterOrder_whenUsingSingleFilters_shouldEvaluateManyConditions() {
long filteredStreamSize = IntStream.range(0, 100)
.boxed()
.filter(i -> isEvenNumber(i) && isSmallerThanTwenty(i))
.count();
assertThat(filteredStreamSize).isEqualTo(10);
assertThat(numberOfOperations).hasValue(150);
}
@Test
public void givenCorrectFilterOrder_whenUsingMultipleFilters_shouldEvaluateFewerConditions() {
long filteredStreamSize = IntStream.range(0, 100)
.boxed()
.filter(this::isSmallerThanTwenty)
.filter(this::isEvenNumber)
.count();
assertThat(filteredStreamSize).isEqualTo(10);
assertThat(numberOfOperations).hasValue(120);
}
@Test
public void givenCorrectFilterOrder_whenUsingHavingASlowCondition_shouldEvaluateFewerConditions() {
long filteredStreamSize = IntStream.range(0, 100)
.boxed()
.filter(this::isSmallerThanTwenty)
.filter(this::isEvenNumber)
.filter(this::verySlowFilter)
.count();
assertThat(filteredStreamSize).isEqualTo(10);
assertThat(numberOfOperations).hasValue(130);
}
private boolean isEvenNumber(int i) {
numberOfOperations.incrementAndGet();
return i % 2 == 0;
}
private boolean isSmallerThanTwenty(int i) {
numberOfOperations.incrementAndGet();
return i < 20;
}
private boolean verySlowFilter(int i) {
numberOfOperations.incrementAndGet();
// commented the Thread.sleep() not to slow down the pipeline.
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
return true;
}
}

View File

@ -0,0 +1,130 @@
package com.baeldung.streams.multiplefilters;
import java.text.MessageFormat;
import java.util.function.Function;
import java.util.stream.IntStream;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Test;
public class MultipleFiltersVsComplexConditionFilterPerformanceIntegrationTest {
// this test is slow, avoid running it on pipeline
@Test
public void measureProcessingTimeForEachSolution() {
averageMultipleMeasurements("Stream with Multiple Filters", this::measureTimeForMultipleFilters, 10_000);
averageMultipleMeasurements("Stream with Multiple Filters", this::measureTimeForMultipleFilters, 100_000);
averageMultipleMeasurements("Stream with Multiple Filters", this::measureTimeForMultipleFilters, 10_00_000);
averageMultipleMeasurements("Stream with Multiple Filters", this::measureTimeForMultipleFilters, 1_0000_000);
averageMultipleMeasurements("Stream with Complex Condition", this::measureTimeForComplexCondition, 10_000);
averageMultipleMeasurements("Stream with Complex Condition", this::measureTimeForComplexCondition, 100_000);
averageMultipleMeasurements("Stream with Complex Condition", this::measureTimeForComplexCondition, 10_00_000);
averageMultipleMeasurements("Stream with Complex Condition", this::measureTimeForComplexCondition, 1_0000_000);
averageMultipleMeasurements("Parallel Stream with Multiple Filters", this::measureTimeForParallelStreamWithMultipleFilters, 10_000);
averageMultipleMeasurements("Parallel Stream with Multiple Filters", this::measureTimeForParallelStreamWithMultipleFilters, 100_000);
averageMultipleMeasurements("Parallel Stream with Multiple Filters", this::measureTimeForParallelStreamWithMultipleFilters, 10_00_000);
averageMultipleMeasurements("Parallel Stream with Multiple Filters", this::measureTimeForParallelStreamWithMultipleFilters, 1_0000_000);
averageMultipleMeasurements("Parallel Stream with Complex Condition", this::measureTimeForParallelStreamWithComplexCondition, 10_000);
averageMultipleMeasurements("Parallel Stream with Complex Condition", this::measureTimeForParallelStreamWithComplexCondition, 100_000);
averageMultipleMeasurements("Parallel Stream with Complex Condition", this::measureTimeForParallelStreamWithComplexCondition, 10_00_000);
averageMultipleMeasurements("Parallel Stream with Complex Condition", this::measureTimeForParallelStreamWithComplexCondition, 1_0000_000);
averageMultipleMeasurements("Old For Loop with Complex Condition", this::measureTimeForOlfForLoopWithComplexCondition, 10_000);
averageMultipleMeasurements("Old For Loop with Complex Condition", this::measureTimeForOlfForLoopWithComplexCondition, 100_000);
averageMultipleMeasurements("Old For Loop with Complex Condition", this::measureTimeForOlfForLoopWithComplexCondition, 10_00_000);
averageMultipleMeasurements("Old For Loop with Complex Condition", this::measureTimeForOlfForLoopWithComplexCondition, 1_0000_000);
}
private void averageMultipleMeasurements(String measurementName, Function<Integer, Long> measurement, int range) {
double avgTime = IntStream.range(0, 100)
.mapToLong(i -> measurement.apply(range))
.average()
.orElseThrow();
System.out.println(MessageFormat.format("{0}; Stream size: {1}; Processing Time (ms): {2}", measurementName, range, avgTime));
}
public long measureTimeForMultipleFilters(int range) {
StopWatch watch = new StopWatch();
watch.start();
IntStream.range(0, range)
.boxed()
.filter(i -> i != 10)
.filter(i -> i != 20)
.filter(i -> i != 30)
.filter(i -> i != 40)
.filter(i -> i != 50)
.filter(i -> i != 60)
.count();
watch.stop();
return watch.getTime();
}
public long measureTimeForParallelStreamWithMultipleFilters(int range) {
StopWatch watch = new StopWatch();
watch.start();
IntStream.range(0, range)
.boxed()
.parallel()
.filter(i -> i != 10)
.filter(i -> i != 20)
.filter(i -> i != 30)
.filter(i -> i != 40)
.filter(i -> i != 50)
.filter(i -> i != 60)
.count();
watch.stop();
return watch.getTime();
}
public long measureTimeForComplexCondition(int range) {
StopWatch watch = new StopWatch();
watch.start();
IntStream.range(0, range)
.boxed()
.filter(i -> i != 10 && i != 20 && i != 30 && i != 40 && i != 50 && i != 60)
.count();
watch.stop();
return watch.getTime();
}
public long measureTimeForParallelStreamWithComplexCondition(int range) {
StopWatch watch = new StopWatch();
watch.start();
IntStream.range(0, range)
.boxed()
.parallel()
.filter(i -> i != 10 && i != 20 && i != 30 && i != 40 && i != 50 && i != 60)
.count();
watch.stop();
return watch.getTime();
}
public long measureTimeForOlfForLoopWithComplexCondition(int range) {
StopWatch watch = new StopWatch();
watch.start();
int count = 0;
for (int i = 0; i <= range; i++) {
if (i != 10 && i != 20 && i != 30 && i != 40 && i != 50 && i != 60) {
count++;
}
}
watch.stop();
return watch.getTime();
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.streams.multiplefilters;
import static java.util.function.Predicate.not;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class MultipleFiltersVsComplexConditionReadabilityUnitTest {
private List<Student> students;
private Student mathStudent;
@Before
public void beforeEach() {
this.mathStudent = new Student();
mathStudent.setName("John Doe");
mathStudent.setYear(3);
mathStudent.setProfile(Student.Profile.MATH);
mathStudent.setMarks(List.of(80, 90, 77, 95, 100));
Student csStudent = new Student();
csStudent.setName("Paul Atreides");
csStudent.setYear(2);
csStudent.setProfile(Student.Profile.COMPUTER_SCIENCE);
csStudent.setMarks(List.of(30, 40, 60));
this.students = List.of(mathStudent, csStudent);
}
@Test
public void whenUsingMultipleFilters_dataShouldBeFiltered() {
List<Student> filteredStream = students.stream()
.filter(s -> s.getMarksAverage() > 50)
.filter(s -> s.getMarks().size() > 3)
.filter(not(s -> s.getProfile() == Student.Profile.PHYSICS))
.collect(Collectors.toList());
assertThat(filteredStream).containsExactly(mathStudent);
}
@Test
public void whenUsingSingleComplexFilter_dataShouldBeFiltered() {
List<Student> filteredStream = students.stream()
.filter(s -> s.getMarksAverage() > 50
&& s.getMarks().size() > 3
&& s.getProfile() != Student.Profile.PHYSICS)
.collect(Collectors.toList());
assertThat(filteredStream).containsExactly(mathStudent);
}
@Test
public void whenUsingSingleComplexFilterExtracted_dataShouldBeFiltered() {
List<Student> filteredStream = students.stream()
.filter(Student::isEligibleForScholarship)
.collect(Collectors.toList());
assertThat(filteredStream).containsExactly(mathStudent);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.streams.multiplefilters;
import java.util.List;
import java.util.stream.Collectors;
public class Student {
private String name;
private int year;
private List<Integer> marks;
private Profile profile;
public enum Profile {
COMPUTER_SCIENCE,
MATH,
PHYSICS
}
public double getMarksAverage() {
return marks.stream().collect(Collectors.averagingInt(m -> m));
}
public boolean isEligibleForScholarship() {
return getMarksAverage() > 50
&& marks.size() > 3
&& profile != Profile.PHYSICS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public List<Integer> getMarks() {
return marks;
}
public void setMarks(List<Integer> marks) {
this.marks = marks;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}

View File

@ -12,4 +12,5 @@ This module contains articles about string conversions from/to another type.
- [Convert a ByteBuffer to String in Java](https://www.baeldung.com/java-bytebuffer-to-string)
- [Convert String to Float and Back in Java](https://www.baeldung.com/java-string-to-float)
- [Difference Between parseInt() and valueOf() in Java](https://www.baeldung.com/java-integer-parseint-vs-valueof)
- [Integer.toString() vs String.valueOf() in Java](https://www.baeldung.com/java-tostring-valueof)
- More articles: [[<-- prev]](/core-java-modules/core-java-string-conversions)

View File

@ -1,4 +1,4 @@
package com.baeldung.chararraytostring;
package com.baeldung.inttostring;
import static org.junit.Assert.assertEquals;
@ -23,7 +23,8 @@ public class IntToStringUnitTest {
@Test(expected = NullPointerException.class)
public void whenNullIntegerObjectIsPassed_thenShouldThrowException() {
Integer i = null;
System.out.println(String.valueOf(i)); // it prints "null"
System.out.println(i.toString());
// NOTE: primitive int can never be null, we are checking this example to check in what case the exception is thrown by these methods.
System.out.println(String.valueOf(i)); // prints "null" as the call goes to String.valueOf(Object obj) method
System.out.println(i.toString()); // throws NPE
}
}

View File

@ -9,3 +9,4 @@
- [Check if a Character is a Vowel in Java](https://www.baeldung.com/java-check-character-vowel)
- [How to Truncate a String in Java](https://www.baeldung.com/java-truncating-strings)
- [Remove Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-whitespace)
- [Named Placeholders in String Formatting](https://www.baeldung.com/java-string-formatting-named-placeholders)

View File

@ -76,7 +76,6 @@
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<joda.version>2.10</joda.version>
<lombok.version>1.18.22</lombok.version>
<asspectj.version>1.8.9</asspectj.version>
<jmockit.version>1.44</jmockit.version>
<mockito-inline.version>4.1.0</mockito-inline.version>

View File

@ -37,7 +37,6 @@
<module>core-java-collections-list</module>
<module>core-java-collections-list-2</module>
<module>core-java-collections-list-3</module>
<module>core-java-collections-list-4</module>
<module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>

View File

@ -26,7 +26,7 @@
<properties>
<java.version>1.8</java.version>
<guava.version>31.0.1-jre</guava.version>
<guava.version>31.1-jre</guava.version>
</properties>
</project>

View File

@ -48,7 +48,7 @@
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<guava.version>31.0.1-jre</guava.version>
<guava.version>31.1-jre</guava.version>
</properties>
</project>

View File

@ -4,4 +4,5 @@
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
- [Communication Between Multiple Docker Compose Projects](https://www.baeldung.com/ops/docker-compose-communication)
- [Difference Between links and depends_on in Docker Compose](https://www.baeldung.com/ops/docker-compose-links-depends-on)
- [Mounting Multiple Volumes on a Docker Container](https://www.baeldung.com/ops/docker-mounting-multiple-volumes)

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [How to Configure Conditional Dependencies in Gradle](https://www.baeldung.com/gradle-conditional-dependencies)

View File

@ -36,12 +36,10 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -51,13 +49,12 @@
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>${graphql-spring-boot-starter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>${jsonassert.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -65,7 +62,6 @@
<properties>
<graphql-spring-boot-starter.version>5.0.2</graphql-spring-boot-starter.version>
<graphql-java-tools.version>5.2.4</graphql-java-tools.version>
<jsonassert.version>1.5.0</jsonassert.version>
</properties>
</project>

View File

@ -1,6 +1,6 @@
package com.baeldung.graphql.error.handling.exception;
import graphql.ErrorType;
import graphql.ErrorClassification;
import graphql.ExceptionWhileDataFetching;
import graphql.GraphQLError;
import graphql.language.SourceLocation;
@ -27,7 +27,7 @@ public class GraphQLErrorAdapter implements GraphQLError {
}
@Override
public ErrorType getErrorType() {
public ErrorClassification getErrorType() {
return error.getErrorType();
}

View File

@ -12,4 +12,5 @@ This module contains articles about Jackson conversions.
- [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast)
- [Deserialize Snake Case to Camel Case With Jackson](https://www.baeldung.com/jackson-deserialize-snake-to-camel-case)
- [Serialize and Deserialize Booleans as Integers With Jackson](https://www.baeldung.com/jackson-booleans-as-integers)
- [Reading JSON From a URL in Java](https://www.baeldung.com/java-read-json-from-url)
- More articles: [[<-- prev]](../jackson-conversions)

View File

@ -32,6 +32,18 @@
<artifactId>jackson-dataformat-csv</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>${mockserver-netty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
</dependencies>
<build>
@ -44,4 +56,9 @@
</resources>
</build>
<properties>
<mockserver-netty.version>5.13.2</mockserver-netty.version>
<json.version>20220320</json.version>
</properties>
</project>

View File

@ -0,0 +1,62 @@
package com.baeldung.jackson.jsonurlreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUrlReader {
public static void main(String[] args) throws StreamReadException, DatabindException, MalformedURLException, IOException {
String url = args[0];
JsonNode node = JsonUrlReader.get(url);
System.out.println(node.toPrettyString());
}
public static String stream(String url) throws IOException {
try (InputStream input = new URL(url).openStream()) {
InputStreamReader isr = new InputStreamReader(input, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
StringBuilder json = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
json.append((char) c);
}
return json.toString();
}
}
public static JsonNode get(String url) throws StreamReadException, DatabindException, MalformedURLException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(new URL(url));
return json;
}
public static <T> T get(String url, Class<T> type) throws StreamReadException, DatabindException, MalformedURLException, IOException {
ObjectMapper mapper = new ObjectMapper();
T entity = mapper.readValue(new URL(url), type);
return entity;
}
public static String getString(String url) throws StreamReadException, DatabindException, MalformedURLException, IOException {
return get(url).toPrettyString();
}
public static JSONObject getJson(String url) throws MalformedURLException, IOException {
String json = IOUtils.toString(new URL(url), Charset.forName("UTF-8"));
JSONObject object = new JSONObject(json);
return object;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.jackson.jsonurlreader.data;
public class Example {
private String name;
private Integer n;
private Boolean real;
public Example() {
}
public Example(String name, Integer n, Boolean real) {
this.name = name;
this.n = n;
this.real = real;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public Boolean getReal() {
return real;
}
public void setReal(Boolean real) {
this.real = real;
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.jackson.jsonurlreader;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import java.io.IOException;
import java.net.ServerSocket;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpStatusCode;
import com.baeldung.jackson.jsonurlreader.data.Example;
public class JsonMockServer {
protected static final String JSON_RESPONSE = "{ \"name\": \"A\", \"n\": 1, \"real\": true }";
protected static final Example OBJECT_RESPONSE = new Example("A", 1, true);
protected static String serviceUrl;
private static final String SERVER_ADDRESS = "127.0.0.1";
private static final String PATH = "/sample-json";
private static ClientAndServer mockServer;
private static int serverPort;
@BeforeAll
static void startServer() throws IOException {
serverPort = getFreePort();
serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH;
mockServer = startClientAndServer(serverPort);
mockJsonRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
@SuppressWarnings("resource")
private static void mockJsonRequest() {
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(request()
.withPath(PATH)
.withMethod("GET"))
.respond(response()
.withStatusCode(HttpStatusCode.OK_200.code())
.withBody(JSON_RESPONSE)
);
}
private static int getFreePort() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.jackson.jsonurlreader;
import static org.junit.Assert.assertEquals;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import com.baeldung.jackson.jsonurlreader.data.Example;
import com.fasterxml.jackson.databind.JsonNode;
public class JsonUrlReaderIntegrationTest extends JsonMockServer {
@Test
public void whenStreamUrl_thenJsonStringReturned() throws Exception {
String jsonNode = JsonUrlReader.stream(serviceUrl);
assertEquals(jsonNode, JSON_RESPONSE);
}
@Test
public void whenGetUrl_thenJsonNodeReturned() throws Exception {
JsonNode jsonNode = JsonUrlReader.get(serviceUrl);
assertEquals(jsonNode.get("name")
.textValue(), "A");
assertEquals(jsonNode.get("n")
.intValue(), 1);
assertEquals(jsonNode.get("real")
.booleanValue(), true);
}
@Test
public void givenType_whenGetUrl_thenTypeReturned() throws Exception {
Example object = JsonUrlReader.get(serviceUrl, Example.class);
Integer n = 1;
assertEquals(object.getName(), "A");
assertEquals(object.getN(), n);
assertEquals(object.getReal(), true);
}
@Test
public void whenGetJsonUrl_thenJsonObjectReturned() throws Exception {
JSONObject jsonObject = JsonUrlReader.getJson(serviceUrl);
assertEquals(jsonObject.getString("name"), "A");
assertEquals(jsonObject.getInt("n"), 1);
assertEquals(jsonObject.getBoolean("real"), true);
}
}

View File

@ -7,7 +7,7 @@
<packaging>pom</packaging>
<parent>
<artifactId>jhipster</artifactId>
<artifactId>jhipster-modules</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>

View File

@ -7,7 +7,7 @@
<description>JHipster Monolithic Application</description>
<parent>
<artifactId>jhipster</artifactId>
<artifactId>jhipster-modules</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>

View File

@ -7,7 +7,7 @@
<packaging>pom</packaging>
<parent>
<artifactId>jhipster</artifactId>
<artifactId>jhipster-modules</artifactId>
<groupId>com.baeldung.jhipster</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>

View File

@ -3,9 +3,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>
<groupId>com.baeldung.jhipster</groupId>
<artifactId>jhipster</artifactId>
<artifactId>jhipster-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>jhipster</name>
<name>jhipster-modules</name>
<packaging>pom</packaging>
<parent>

View File

@ -67,7 +67,6 @@
<properties>
<gson.version>2.8.0</gson.version>
<joda-time.version>2.9.6</joda-time.version>
<guava.version>11.0.2</guava.version>
</properties>
</project>

View File

@ -16,15 +16,9 @@
<dependencies>
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
<version>${everit.json.schema.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${networknt.json.schema.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
@ -72,7 +66,7 @@
</dependencies>
<properties>
<everit.json.schema.version>1.4.1</everit.json.schema.version>
<networknt.json.schema.version>1.0.72</networknt.json.schema.version>
<jsonb-api.version>1.0</jsonb-api.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20211205</json.version>

View File

@ -1,32 +1,44 @@
package com.baeldung.json.schema;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.Set;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
public class JSONSchemaUnitTest {
@Test(expected = ValidationException.class)
public void givenInvalidInput_whenValidating_thenInvalid() {
private ObjectMapper mapper = new ObjectMapper();
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_invalid.json")));
@Test
public void givenInvalidInput_whenValidating_thenInvalid() throws IOException {
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonSubject);
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema jsonSchema = factory.getSchema(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json"));
JsonNode jsonNode = mapper.readTree(JSONSchemaUnitTest.class.getResourceAsStream("/product_invalid.json"));
Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
assertThat(errors).isNotEmpty()
.asString()
.contains("price: must have a minimum value of 0");
}
@Test
public void givenValidInput_whenValidating_thenValid() {
public void givenValidInput_whenValidating_thenValid() throws IOException {
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_valid.json")));
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema jsonSchema = factory.getSchema(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json"));
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonSubject);
JsonNode jsonNode = mapper.readTree(JSONSchemaUnitTest.class.getResourceAsStream("/product_valid.json"));
Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
assertThat(errors).isEmpty();
}
}

View File

@ -249,7 +249,6 @@
<properties>
<jcommander.version>1.78</jcommander.version>
<lombok.version>1.18.6</lombok.version>
<cactoos.version>0.43</cactoos.version>
<airline.version>2.7.2</airline.version>
<cache2k.version>1.2.3.Final</cache2k.version>

View File

@ -159,7 +159,6 @@
classname="com.gs.fw.common.mithra.generator.MithraGenerator" />
<gen-reladomo
xml="${project.basedir}/src/main/resources/reladomo/ReladomoClassList.xml"
generateGscListMethod="true"
generatedDir="${project.build.directory}/generated-sources/reladomo"
nonGeneratedDir="${project.basedir}/src/main/java" />
@ -268,7 +267,7 @@
<properties>
<ebean.plugin.version>11.11.2</ebean.plugin.version>
<reladomo.version>16.5.1</reladomo.version>
<reladomo.version>18.1.0</reladomo.version>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<ormlite.version>5.0</ormlite.version>

View File

@ -29,22 +29,22 @@ insert into dept values(40, 'OPERATIONS', 'BOSTON');
insert into emp values(
7839, 'KING', 'PRESIDENT', null,
to_date('17-11-1981','dd-mm-yyyy'),
parsedatetime('17-11-1981','dd-MM-yyyy'),
7698, null, 10
);
insert into emp values(
7698, 'BLAKE', 'MANAGER', 7839,
to_date('1-5-1981','dd-mm-yyyy'),
parsedatetime('01-05-1981','dd-MM-yyyy'),
7782, null, 20
);
insert into emp values(
7782, 'CLARK', 'MANAGER', 7839,
to_date('9-6-1981','dd-mm-yyyy'),
parsedatetime('09-06-1981','dd-MM-yyyy'),
7566, null, 30
);
insert into emp values(
7566, 'JONES', 'MANAGER', 7839,
to_date('2-4-1981','dd-mm-yyyy'),
parsedatetime('02-04-1981','dd-MM-yyyy'),
7839, null, 40
);

48
libraries-files/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>libraries-files</artifactId>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.ini4j</groupId>
<artifactId>ini4j</artifactId>
<version>${org.ini4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>${commons-configuration2}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<properties>
<org.ini4j.version>0.5.4</org.ini4j.version>
<commons-configuration2>2.8.0</commons-configuration2>
<jackson.version>2.13.1</jackson.version>
</properties>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.ini;
import org.apache.commons.configuration2.INIConfiguration;
import org.apache.commons.configuration2.SubnodeConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class CommonsParser {
public static Map<String, Map<String, String>> parseIniFile(File fileToParse) throws IOException, ConfigurationException {
Map<String, Map<String, String>> iniFileContents = new HashMap<>();
INIConfiguration iniConfiguration = new INIConfiguration();
try (FileReader fileReader = new FileReader(fileToParse)) {
iniConfiguration.read(fileReader);
}
for (String section : iniConfiguration.getSections()) {
Map<String, String> subSectionMap = new HashMap<>();
SubnodeConfiguration confSection = iniConfiguration.getSection(section);
Iterator<String> keyIterator = confSection.getKeys();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
String value = confSection.getProperty(key)
.toString();
subSectionMap.put(key, value);
}
iniFileContents.put(section, subSectionMap);
}
return iniFileContents;
}
public static String readIniFileValue(File fileToParse, String section, String value) throws IOException, ConfigurationException {
INIConfiguration iniConfiguration = new INIConfiguration();
try (FileReader fileReader = new FileReader(fileToParse)) {
iniConfiguration.read(fileReader);
}
return iniConfiguration.getSection(section).getProperty(value).toString();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.ini;
import org.ini4j.Ini;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static java.util.stream.Collectors.toMap;
public class Ini4JParser {
public static Map<String, Map<String, String>> parseIniFile(File fileToParse) throws IOException {
Ini ini = new Ini(fileToParse);
return ini.entrySet().stream()
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
}
public static String readIniFileValue(File fileToParse, String section, String key) throws IOException {
Ini ini = new Ini(fileToParse);
return ini.get(section, key);
}
}

View File

@ -0,0 +1,109 @@
package com.baeldung.ini;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
public class MyConfiguration {
@JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class)
public static class Fonts {
private String letter;
private int textSize;
public String getLetter() {
return letter;
}
public void setLetter(String letter) {
this.letter = letter;
}
public int getTextSize() {
return textSize;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
}
public static class Background {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public static class RequestResult {
private int requestCode;
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
}
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public static class ResponseResult {
private int resultCode;
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
}
private Fonts fonts;
private Background background;
@JsonProperty("RequestResult")
private RequestResult requestResult;
@JsonProperty("ResponseResult")
private ResponseResult responseResult;
public Fonts getFonts() {
return fonts;
}
public void setFonts(Fonts fonts) {
this.fonts = fonts;
}
public Background getBackground() {
return background;
}
public void setBackground(Background background) {
this.background = background;
}
public RequestResult getRequestResult() {
return requestResult;
}
public void setRequestResult(RequestResult requestResult) {
this.requestResult = requestResult;
}
public ResponseResult getResponseResult() {
return responseResult;
}
public void setResponseResult(ResponseResult responseResult) {
this.responseResult = responseResult;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.ini;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.file.Paths;
import java.util.Map;
import static com.baeldung.ini.CommonsParser.parseIniFile;
import static com.baeldung.ini.CommonsParser.readIniFileValue;
import static org.assertj.core.api.Assertions.assertThat;
class CommonsParserUnitTest {
private static final File TEST_FILE = Paths.get("src", "test", "resources", "sample.ini").toFile();
@Test
void givenIniFileThenCanParseWithIni4j() throws Exception {
Map<String, Map<String, String>> result =
parseIniFile(TEST_FILE);
assertThat(result.get("fonts"))
.containsEntry("letter", "bold")
.containsEntry("text-size", "28");
}
@Test
void givenIniFileThenCanReadKeyWithIni4j() throws Exception {
assertThat(readIniFileValue(TEST_FILE, "fonts", "letter"))
.isEqualTo("bold");
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.ini;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.file.Paths;
import java.util.Map;
import static com.baeldung.ini.Ini4JParser.readIniFileValue;
import static com.baeldung.ini.Ini4JParser.parseIniFile;
import static org.assertj.core.api.Assertions.assertThat;
class Ini4JParserUnitTest {
private static final File TEST_FILE = Paths.get("src", "test", "resources", "sample.ini").toFile();
@Test
void givenIniFileThenCanParseWithIni4j() throws Exception {
Map<String, Map<String, String>> result =
parseIniFile(TEST_FILE);
assertThat(result.get("fonts"))
.containsEntry("letter", "bold")
.containsEntry("text-size", "28");
}
@Test
void givenIniFileThenCanReadKeyFromIt() throws Exception {
assertThat(readIniFileValue(TEST_FILE, "fonts", "letter"))
.isEqualTo("bold");
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.ini;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.file.Paths;
import java.util.Map;
import static com.baeldung.ini.Ini4JParser.parseIniFile;
import static org.assertj.core.api.Assertions.assertThat;
class SerializeIntoPojoUnitTest {
private static final File TEST_FILE = Paths.get("src", "test", "resources", "sample.ini").toFile();
@Test
void givenAnIniFileThenCanLoadAsPojo() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Map<String, String>> iniKeys = parseIniFile(TEST_FILE);
MyConfiguration config = objectMapper.convertValue(iniKeys, MyConfiguration.class);
assertThat(config.getFonts().getLetter()).isEqualTo("bold");
assertThat(config.getFonts().getTextSize()).isEqualTo(28);
assertThat(config.getBackground().getColor()).isEqualTo("white");
assertThat(config.getRequestResult().getRequestCode()).isEqualTo(1);
assertThat(config.getResponseResult().getResultCode()).isZero();
}
}

View File

@ -0,0 +1,14 @@
; for 16-bit app support
[fonts]
letter=bold
text-size=28
[background]
color=white
[RequestResult]
RequestCode=1
[ResponseResult]
ResultCode=0

View File

@ -8,3 +8,4 @@
- [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers)
- [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins)
- [Printing Thread Info in Log File Using Log4j2](https://www.baeldung.com/log4j2-print-thread-info)
- [Log4j2 Logging to Both File and Console](https://www.baeldung.com/java-log4j2-file-and-console)

View File

@ -0,0 +1,14 @@
package com.baeldung.logging.log4j2.consoleandfile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2ConsoleAndFile {
private static final Logger logger = LogManager.getLogger(Log4j2ConsoleAndFile.class);
public static void main(String[] args) {
logger.info("Hello World!");
logger.debug("Hello World!");
}
}

View File

@ -0,0 +1,14 @@
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=logs/log4j.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.filter.threshold.type = ThresholdFilter
appender.file.filter.threshold.level = info
rootLogger=debug, STDOUT, LOGFILE

View File

@ -32,8 +32,4 @@
</pluginManagement>
</build>
<properties>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>

View File

@ -3,8 +3,8 @@
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>maven-repository-download</artifactId>
<name>Maven Release Repository</name>
<artifactId>maven-download-artifacts</artifactId>
<name>maven-download-artifacts</name>
<version>1.0.0-SNAPSHOT</version>
<parent>

View File

@ -4,7 +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>maven-release-repository</artifactId>
<name>Maven Release Repository</name>
<name>maven-release-repository</name>
<version>1.0.0</version>
<parent>

View File

@ -4,7 +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>maven-snapshot-repository</artifactId>
<name>Maven Snapshot Repository</name>
<name>maven-snapshot-repository</name>
<version>1.0.0-SNAPSHOT</version>
<parent>

View File

@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-repositories</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Maven Repositories</name>
<name>maven-repositories</name>
<packaging>pom</packaging>
<parent>

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