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

This commit is contained in:
Maiklins 2023-12-10 19:00:44 +01:00 committed by GitHub
commit 3d685dc3b6
483 changed files with 5781 additions and 1037 deletions

View File

@ -63,11 +63,6 @@
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
<build>
@ -84,10 +79,9 @@
<mockserver.version>5.6.1</mockserver.version>
<wiremock.version>3.3.1</wiremock.version>
<!-- http client & core 5 -->
<httpcore5.version>5.2</httpcore5.version>
<httpclient5.version>5.2</httpclient5.version>
<httpclient5-fluent.version>5.2</httpclient5-fluent.version>
<httpclient.version>4.5.14</httpclient.version>
<httpcore5.version>5.2.2</httpcore5.version>
<httpclient5.version>5.2.2</httpclient5.version>
<httpclient5-fluent.version>5.2.2</httpclient5-fluent.version>
</properties>
</project>

View File

@ -25,6 +25,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
@ -33,7 +34,6 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.junit.jupiter.api.Test;
@ -120,7 +120,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
.build();
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSslContext(sslContext)
.build();

View File

@ -7,14 +7,14 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
public class CustomWebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@ -27,8 +27,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
@ -40,6 +40,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
return http.build();
}
@Bean

View File

@ -55,14 +55,14 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version} </version>
<version>${jackson.databind.version}</version>
</dependency>
</dependencies>
<properties>
<jna.version>5.7.0</jna.version>
<kafka.version>2.8.0</kafka.version>
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
<testcontainers-kafka.version>1.19.3</testcontainers-kafka.version>
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
<jackson.databind.version>2.15.2</jackson.databind.version>
</properties>

View File

@ -182,7 +182,7 @@
<properties>
<kafka.version>3.4.0</kafka.version>
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
<testcontainers-kafka.version>1.19.3</testcontainers-kafka.version>
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
<flink.version>1.16.1</flink.version>
<awaitility.version>3.0.0</awaitility.version>

View File

@ -1,7 +1,7 @@
<?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">
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>aws-dynamodb</artifactId>
<version>0.1.0-SNAPSHOT</version>
@ -40,22 +40,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -34,22 +34,6 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -93,7 +93,6 @@
<properties>
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.17.283</awssdk.version>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>

View File

@ -39,27 +39,6 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<commons-codec-version>1.10.L001</commons-codec-version>

View File

@ -5,6 +5,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-modules</artifactId>
<name>aws-modules</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
@ -15,12 +22,6 @@
</dependencies>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>aws-app-sync</module>
<module>aws-dynamodb</module>

View File

@ -167,7 +167,6 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons-lang3.version>3.9</commons-lang3.version>
<java.version>1.8</java.version>
<logback.version>1.2.3</logback.version>
</properties>
</project>

View File

@ -13,6 +13,13 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<pluginRepositories>
<pluginRepository>
<id>groovy-plugins-release</id>
<url>https://groovy.jfrog.io/artifactory/plugins-release-local</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@ -156,8 +163,8 @@
<groovy-wslite.version>1.1.3</groovy-wslite.version>
<assembly.plugin.version>3.4.2</assembly.plugin.version>
<compiler.plugin.version>3.8.1</compiler.plugin.version>
<groovy.compiler.version>3.7.0</groovy.compiler.version>
<groovy-eclipse-batch.version>3.0.8-01</groovy-eclipse-batch.version>
<groovy.compiler.version>3.9.0</groovy.compiler.version>
<groovy-eclipse-batch.version>3.0.9-03</groovy-eclipse-batch.version>
</properties>
</project>

View File

@ -45,7 +45,7 @@
<properties>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<jackson.version>2.14.1</jackson.version>
<jackson.version>2.16.0</jackson.version>
<gson.version>2.10</gson.version>
</properties>

View File

@ -21,8 +21,4 @@
</dependency>
</dependencies>
<properties>
<java.version>17</java.version>
</properties>
</project>

View File

@ -13,8 +13,4 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<java.version>17</java.version>
</properties>
</project>

View File

@ -26,8 +26,4 @@
</dependency>
</dependencies>
<properties>
<java.version>17</java.version>
</properties>
</project>

View File

@ -9,3 +9,4 @@
- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
- [Format Multiple or Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement)
- [Get All Record Fields and Its Values via Reflection](https://www.baeldung.com/java-reflection-record-fields-values)
- [Context-Specific Deserialization Filters in Java 17](https://www.baeldung.com/java-context-specific-deserialization-filters)

View File

@ -3,19 +3,34 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-20</artifactId>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>core-java-20</artifactId>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
@ -41,25 +56,10 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,5 @@
package com.baeldung.deserialization;
public record Contact(String email, String phone) {
// Constructor, getters, and other methods are automatically generated
}

View File

@ -0,0 +1,5 @@
package com.baeldung.deserialization;
public record Person(String name, int age, String address, Contact contact) {
// Constructor, getters, and other methods are automatically generated
}

View File

@ -0,0 +1,39 @@
package com.baeldung.deserialization;
import com.google.gson.Gson;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DeserializationUnitTest {
@Test
public void givenJsonString_whenDeserialized_thenPersonRecordCreated() {
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\"}";
Person person = new Gson().fromJson(json, Person.class);
assertEquals("John Doe", person.name());
assertEquals(30, person.age());
assertEquals("123 Main St", person.address());
}
@Test
public void givenNestedJsonString_whenDeserialized_thenPersonRecordCreated() {
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\",\"contact\":{\"email\":\"john.doe@example.com\",\"phone\":\"555-1234\"}}";
Person person = new Gson().fromJson(json, Person.class);
assertNotNull(person);
assertEquals("John Doe", person.name());
assertEquals(30, person.age());
assertEquals("123 Main St", person.address());
Contact contact = person.contact();
assertNotNull(contact);
assertEquals("john.doe@example.com", contact.email());
assertEquals("555-1234", contact.phone());
}
}

View File

@ -8,4 +8,5 @@
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)

View File

@ -0,0 +1,42 @@
package com.baeldung.unixtime;
import static org.junit.Assert.assertEquals;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Date;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
public class UnixTimeUnitTest {
@Test
public void givenTimeUsingDateApi_whenConvertedToUnixTime_thenMatch() {
Date date = new Date(2023 - 1900, 1, 15, 0, 0, 0);
long expected = 1676419200;
long actual = date.getTime() / 1000L;
assertEquals(expected, actual);
}
@Test
public void givenTimeUsingJodaTime_whenConvertedToUnixTime_thenMatch() {
DateTime dateTime = new DateTime(2023, 2, 15, 00, 00, 00, 0);
long expected = 1676419200;
long actual = dateTime.getMillis() / 1000L;
assertEquals(expected, actual);
}
@Test
public void givenTimeUsingLocalDate_whenConvertedToUnixTime_thenMatch() {
LocalDate date = LocalDate.of(2023, Month.FEBRUARY, 15);
Instant instant = date.atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
long expected = 1676419200;
long actual = instant.getEpochSecond();
assertEquals(expected, actual);
}
}

View File

@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char)

View File

@ -0,0 +1,47 @@
package com.baeldung.array.conversions;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertArrayEquals;
public class ByteToCharArrayUnitTest {
public static byte[] byteArray = {65, 66, 67, 68};
public static char[] expected = {'A', 'B', 'C', 'D'};
@Test
public void givenByteArray_WhenUsingStandardCharsets_thenConvertToCharArray() {
char[] charArray = new String(byteArray, StandardCharsets.UTF_8).toCharArray();
assertArrayEquals(expected, charArray);
}
@Test
public void givenByteArray_WhenUsingSUsingStreams_thenConvertToCharArray() throws IOException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
InputStreamReader reader = new InputStreamReader(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int data;
while ((data = reader.read()) != -1) {
char ch = (char) data;
outputStream.write(ch);
}
char[] charArray = outputStream.toString().toCharArray();
assertArrayEquals(expected, charArray);
}
@Test
public void givenByteArray_WhenUsingCharBuffer_thenConvertToCharArray() {
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer);
char[] charArray = new char[charBuffer.remaining()];
charBuffer.get(charArray);
assertArrayEquals(expected, charArray);
}
}

View File

@ -57,7 +57,7 @@
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>11</maven.compiler.release>
</properties>

View File

@ -10,4 +10,5 @@
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)

View File

@ -43,7 +43,6 @@
<properties>
<vavr.version>0.10.3</vavr.version>
<java.version>11</java.version>
<modelmapper.version>3.2.0</modelmapper.version>
</properties>
</project>

View File

@ -39,7 +39,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -67,7 +67,7 @@
<jmh.version>1.21</jmh.version>
<commons-lang.version>2.2</commons-lang.version>
<gson.version>2.10.1</gson.version>
<jackson.version>2.15.2</jackson.version>
<jackson.version>2.16.0</jackson.version>
<org.json.version>20230618</org.json.version>
</properties>
</project>

View File

@ -13,14 +13,11 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
<version>2.16.0</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
@ -40,7 +37,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -51,4 +48,8 @@
</dependency>
</dependencies>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
</project>

View File

@ -4,4 +4,7 @@
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound)
- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)

View File

@ -1,15 +1,11 @@
<?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">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-maps-7</artifactId>
<name>core-java-collections-maps-7</name>
<packaging>jar</packaging>
<properties>
<gson.version>2.10.1</gson.version>
<csv.version>1.5</csv.version>
</properties>
<parent>
<artifactId>core-java-modules</artifactId>
@ -38,6 +34,16 @@
<artifactId>guava</artifactId>
<version>32.1.2-jre</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.37</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.37</version>
</dependency>
</dependencies>
<build>
@ -53,4 +59,10 @@
</plugin>
</plugins>
</build>
<properties>
<gson.version>2.10.1</gson.version>
<csv.version>1.5</csv.version>
</properties>
</project>

View File

@ -0,0 +1,68 @@
package com.baeldung.map.incrementmapkey;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class BenchmarkMapMethodsJMH {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkGuavaMap() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingAtomicMap(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchContainsKeyMap() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingContainsKey(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkComputeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingCompute(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkMergeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingMerge(getString());
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
private String getString() {
return
"Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n"
+ "\n"
+ "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n"
+ "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n"
+ "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n"
+ "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n"
+ "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n"
+ "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n"
+ "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n"
+ "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe.";
}
}

View File

@ -0,0 +1,141 @@
package com.baeldung.map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.junit.jupiter.api.Test;
class Player {
private String name;
private Integer score = 0;
public Player(String name, Integer score) {
this.name = name;
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Player)) {
return false;
}
Player player = (Player) o;
if (!Objects.equals(name, player.name)) {
return false;
}
return Objects.equals(score, player.score);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (score != null ? score.hashCode() : 0);
return result;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
public class LinkedHashMapSortByValueUnitTest {
private static LinkedHashMap<String, Integer> MY_MAP = new LinkedHashMap<>();
static {
MY_MAP.put("key a", 4);
MY_MAP.put("key b", 1);
MY_MAP.put("key c", 3);
MY_MAP.put("key d", 2);
MY_MAP.put("key e", 5);
}
private static LinkedHashMap<String, Integer> EXPECTED_MY_MAP = new LinkedHashMap<>();
static {
EXPECTED_MY_MAP.put("key b", 1);
EXPECTED_MY_MAP.put("key d", 2);
EXPECTED_MY_MAP.put("key c", 3);
EXPECTED_MY_MAP.put("key a", 4);
EXPECTED_MY_MAP.put("key e", 5);
}
private static final LinkedHashMap<String, Player> PLAYERS = new LinkedHashMap<>();
static {
PLAYERS.put("player a", new Player("Eric", 9));
PLAYERS.put("player b", new Player("Kai", 7));
PLAYERS.put("player c", new Player("Amanda", 20));
PLAYERS.put("player d", new Player("Kevin", 4));
}
private static final LinkedHashMap<String, Player> EXPECTED_PLAYERS = new LinkedHashMap<>();
static {
EXPECTED_PLAYERS.put("player d", new Player("Kevin", 4));
EXPECTED_PLAYERS.put("player b", new Player("Kai", 7));
EXPECTED_PLAYERS.put("player a", new Player("Eric", 9));
EXPECTED_PLAYERS.put("player c", new Player("Amanda", 20));
}
@Test
void whenUsingCollectionSort_thenGetExpectedResult() {
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(MY_MAP.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue()
.compareTo(o2.getValue());
}
});
LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> e : entryList) {
result.put(e.getKey(), e.getValue());
}
assertEquals(EXPECTED_MY_MAP, result);
}
@Test
void whenUsingEntrycomparingByValueAndFillAMap_thenGetExpectedResult() {
LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
MY_MAP.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(entry -> result.put(entry.getKey(), entry.getValue()));
assertEquals(EXPECTED_MY_MAP, result);
}
@Test
void whenUsingEntrycomparingByValueAndCollect_thenGetExpectedResult() {
LinkedHashMap<String, Integer> result = MY_MAP.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll);
assertEquals(EXPECTED_MY_MAP, result);
}
@Test
void whenUsingEntrycomparingByValueAndComparator_thenGetExpectedResult() {
LinkedHashMap<String, Player> result = PLAYERS.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.comparing(Player::getScore)))
.collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll);
assertEquals(EXPECTED_PLAYERS, result);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.map;
package com.baeldung.map.incrementmapkey;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -9,6 +9,8 @@ import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.map.incrementmapkey.IncrementMapValueWays;
public class IncrementMapValueUnitTest {
@Test

View File

@ -0,0 +1,150 @@
package com.baeldung.concurrent.completablefuture;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.junit.Test;
public class CompletableFutureUnitTest {
@Test
public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException {
Microservice mockMicroserviceA = mock(Microservice.class);
Microservice mockMicroserviceB = mock(Microservice.class);
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World"));
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
String result = resultFuture.get();
assertEquals("HelloWorld", result);
}
@Test
public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() throws ExecutionException, InterruptedException {
Microservice mockMicroserviceA = mock(Microservice.class);
Microservice mockMicroserviceB = mock(Microservice.class);
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")));
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
// Use assertThrows to verify that the expected exception is thrown
ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get);
// Assert the exception message
assertEquals("Simulated Exception", exception.getCause()
.getMessage());
}
@Test
public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() throws ExecutionException, InterruptedException {
Microservice mockMicroserviceA = mock(Microservice.class);
Microservice mockMicroserviceB = mock(Microservice.class);
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor));
Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS);
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2));
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS));
}
@Test
public void givenCompletableFuture_whenCompleted_thenStateIsDone() {
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
assertFalse(allCf.isDone());
allCf.join();
String result = Arrays.stream(cfs)
.map(CompletableFuture::join)
.collect(Collectors.joining());
assertFalse(allCf.isCancelled());
assertTrue(allCf.isDone());
assertFalse(allCf.isCompletedExceptionally());
assertEquals(result, "Hello World!");
}
@Test
public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() throws ExecutionException, InterruptedException {
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
CompletableFuture<String> cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"));
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
assertFalse(allCf.isDone());
assertFalse(allCf.isCompletedExceptionally());
// Exception is expected, assert the cause
CompletionException exception = assertThrows(CompletionException.class, allCf::join);
assertEquals("Simulated Exception", exception.getCause()
.getMessage());
assertTrue(allCf.isCompletedExceptionally());
assertTrue(allCf.isDone());
assertFalse(allCf.isCancelled());
}
@Test
public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() throws ExecutionException, InterruptedException {
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
assertFalse(allCf.isDone());
assertFalse(allCf.isCompletedExceptionally());
allCf.cancel(true);
assertTrue(allCf.isCancelled());
assertTrue(allCf.isDone());
}
CompletableFuture<String> processAsync(List<Microservice> microservices) {
List<CompletableFuture<String>> dataFetchFutures = fetchDataAsync(microservices);
return combineResults(dataFetchFutures);
}
private List<CompletableFuture<String>> fetchDataAsync(List<Microservice> microservices) {
return microservices.stream()
.map(client -> client.retrieveAsync(""))
.collect(Collectors.toList());
}
private CompletableFuture<String> combineResults(List<CompletableFuture<String>> dataFetchFutures) {
return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> dataFetchFutures.stream()
.map(future -> future.exceptionally(ex -> {
throw new CompletionException(ex);
})
.join())
.collect(Collectors.joining()));
}
interface Microservice {
CompletableFuture<String> retrieveAsync(String input);
}
}

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization)
- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture)

View File

@ -2,7 +2,7 @@ package com.baeldung.wait_synchronization;
public class ConditionChecker {
private volatile Boolean jobIsDone;
private volatile boolean jobIsDone;
private final Object lock = new Object();
public void ensureCondition() {
@ -21,4 +21,4 @@ public class ConditionChecker {
lock.notify();
}
}
}
}

View File

@ -159,7 +159,7 @@
</profiles>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<ascii.version>0.3.2</ascii.version>

View File

@ -10,3 +10,5 @@ This module contains articles about converting between Java date and time object
- [Convert Between LocalDateTime and ZonedDateTime](https://www.baeldung.com/java-localdatetime-zoneddatetime)
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)

View File

@ -33,7 +33,7 @@
<properties>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>

View File

@ -61,7 +61,7 @@
</build>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<wiremock.version>3.3.1</wiremock.version>
</properties>

View File

@ -134,7 +134,7 @@
<properties>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.5.0</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<hsqldb.version>2.7.1</hsqldb.version>
<!-- Mime Type Libraries -->
<tika.version>2.8.0</tika.version>

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>core-java-ipc</artifactId>
<name>core-java-ipc</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.ipc;
import org.junit.jupiter.api.Test;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchEvent;
import java.nio.file.WatchService;
public class DirectoryLiveTest {
@Test
public void consumer() throws Exception {
WatchService watchService = FileSystems.getDefault().newWatchService();
// Set this to an appropriate directory.
Path path = Paths.get("/tmp/ipc");
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
// React to new file.
System.out.println(event);
}
key.reset();
}
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.ipc;
import org.junit.jupiter.api.Test;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
public class JmxLiveTest {
/*
* This test needs to be run with the following system properties defined:
* -Dcom.sun.management.jmxremote=true
* -Dcom.sun.management.jmxremote.port=1234
* -Dcom.sun.management.jmxremote.authenticate=false
* -Dcom.sun.management.jmxremote.ssl=false
*/
@Test
public void consumer() throws Exception {
ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test");
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.registerMBean(new IPCTest(), objectName);
TimeUnit.MINUTES.sleep(50);
}
@Test
public void producer() throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi");
try (JMXConnector jmxc = JMXConnectorFactory.connect(url, null)) {
ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test");
IPCTestMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(), objectName, IPCTestMBean.class, true);
mbeanProxy.sendMessage("Hello");
}
}
public interface IPCTestMBean {
void sendMessage(String message);
}
class IPCTest implements IPCTestMBean {
@Override
public void sendMessage(String message) {
System.out.println("Received message: " + message);
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.ipc;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketsLiveTest {
@Test
public void consumer() throws Exception {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("Received message: " + line);
}
}
}
@Test
public void producer() throws Exception {
try (Socket clientSocket = new Socket("localhost", 1234)) {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out.println("Hello");
String response = in.readLine();
}
}
}

View File

@ -274,7 +274,7 @@
<mockito.version>4.6.1</mockito.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<maven-assembly-plugin.version>3.3.0</maven-assembly-plugin.version>

View File

@ -9,4 +9,5 @@ This module contains articles about core features in the Java language
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)

View File

@ -0,0 +1,14 @@
package com.baeldung.staticfinal;
import java.util.HashMap;
public class Bike {
public static final int TIRE = 2;
public static final int PEDAL;
public static final HashMap<String, Integer> PART = new HashMap<>();
static {
PEDAL = 5;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.staticfinal;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class BikeUnitTest {
@Test
void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() {
assertEquals(2, Bike.TIRE);
}
@Test
void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() {
assertEquals(5, Bike.PEDAL);
}
@Test
void givenPartConstantObject_whenObjectStateChanged_thenCorrect() {
Bike.PART.put("seat", 1);
assertEquals(1, Bike.PART.get("seat"));
Bike.PART.put("seat", 5);
assertEquals(5, Bike.PART.get("seat"));
}
@Test
void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() {
assertEquals(3.141592653589793, Math.PI);
}
}

View File

@ -26,13 +26,25 @@ public class Rectangle {
this.topRight = topRight;
}
public boolean isOverlapping(Rectangle other) {
// one rectangle is to the top of the other
if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
public boolean isOverlapping(Rectangle comparedRectangle) {
// one rectangle is to the top of the comparedRectangle
if (this.topRight.getY() < comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() > comparedRectangle.topRight.getY()) {
return false;
}
// one rectangle is to the left of the other
if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
// one rectangle is to the left of the comparedRectangle
if (this.topRight.getX() < comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() > comparedRectangle.topRight.getX()) {
return false;
}
return true;
}
public boolean isOverlappingWithoutBorders(Rectangle comparedRectangle) {
// one rectangle is to the top of the comparedRectangle
if (this.topRight.getY() <= comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() >= comparedRectangle.topRight.getY()) {
return false;
}
// one rectangle is to the left of the comparedRectangle
if (this.topRight.getX() <= comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() >= comparedRectangle.topRight.getX()) {
return false;
}
return true;

View File

@ -1,7 +1,8 @@
package com.baeldung.algorithms.rectanglesoverlap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class RectangleUnitTest {
@ -36,4 +37,18 @@ public class RectangleUnitTest {
assertFalse(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenAdjacentRectangles_whensOverlappingCalled_shouldReturnTrue() {
Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14));
Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14));
assertTrue(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenAdjacentRectangles_whensOverlappingWithoutBordersCalled_shouldReturnFalse() {
Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14));
Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14));
assertFalse(rectangle1.isOverlappingWithoutBorders(rectangle2));
}
}

View File

@ -10,3 +10,4 @@ This module contains articles about types in Java
- [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list)
- [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum)
- [Implementing toString() on enums in Java](https://www.baeldung.com/java-enums-tostring)
- [Checking if an Objects Type Is Enum](https://www.baeldung.com/java-check-object-enum)

View File

@ -10,3 +10,4 @@ This module contains articles about Java operators
- [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans)
- [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives)
- [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan)
- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon)

View File

@ -0,0 +1,178 @@
package com.baeldung.colonexamples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
/**
* Examples of the different ways Java uses the colon (:) character.
*/
public class ColonExamples {
private final static Logger LOG = LoggerFactory.getLogger(ColonExamples.class);
public void example1_enhancedForLoop() {
// Original style
for(int i = 0; i < 10; i++) {
// do something
}
// Using enhanced for loop
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i : numbers) {
// do something
}
// Using List instead of array
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
for(Integer i : numbersList) {
// do something
}
}
public void example2_switchStatement(String animal) {
// Original style
if(animal.equals("cat")) {
System.out.println("meow");
}
else if(animal.equals("lion")) {
System.out.println("roar");
}
else if(animal.equals("dog") || animal.equals("seal")) {
System.out.println("bark");
}
else {
System.out.println("unknown");
}
// Using switch statement
switch(animal) {
case "cat":
System.out.println("meow");
break;
case "lion":
System.out.println("roar");
break;
case "dog":
case "seal":
System.out.println("bark");
break;
default:
System.out.println("unknown");
}
}
public void example3_labels() {
// For loops without labels
for(int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (checkSomeCondition()) {
break;
}
}
}
outterLoop: for(int i = 0; i < 10; i++) {
innerLoop: for (int j = 0; j < 10; j++) {
if (checkSomeCondition()) {
break outterLoop;
}
}
}
}
public void example4_ternaryOperator() {
// Original way using if/else
int x;
if(checkSomeCondition()) {
x = 1;
}
else {
x = 2;
}
// Using ternary operator
x = checkSomeCondition() ? 1 : 2;
// Using with other statements
boolean remoteCallResult = callRemoteApi();
LOG.info(String.format(
"The result of the remote API call %s successful",
remoteCallResult ? "was" : "was not"
));
}
public void example5_methodReferences() {
// Original way without lambdas and method references
List<String> names = Arrays.asList("ross", "joey", "chandler");
List<String> upperCaseNames = new ArrayList<>();
for(String name : names) {
upperCaseNames.add(name.toUpperCase());
}
// Using method reference with stream map operation
List<String> petNames = Arrays.asList("ross", "joey", "chandler");
List<String> petUpperCaseNames = petNames
.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Method reference with stream filter
List<Animal> pets = Arrays.asList(new Cat(), new Dog(), new Parrot());
List<Animal> onlyDogs = pets
.stream()
.filter(Dog.class::isInstance)
.collect(Collectors.toList());
// Method reference with constructors
Set<Animal> onlyDogsSet = pets
.stream()
.filter(Dog.class::isInstance)
.collect(Collectors.toCollection(TreeSet::new));
}
public void example6_asserttion() {
// Original way without assertions
Connection conn = getConnection();
if(conn == null) {
throw new RuntimeException("Connection is null");
}
// Using assert keyword
assert getConnection() != null : "Connection is null";
}
private boolean checkSomeCondition() {
return new Random().nextBoolean();
}
private boolean callRemoteApi() {
return new Random().nextBoolean();
}
private Connection getConnection() {
return null;
}
private static interface Animal {
}
private static class Dog implements Animal {
}
private static class Cat implements Animal {
}
private static class Parrot implements Animal {
}
}

View File

@ -11,55 +11,55 @@ import static org.junit.jupiter.api.Assertions.*;
public class InstanceOfUnitTest {
@Test
void giveWhenInstanceIsCorrect_thenReturnTrue() {
void givenWhenInstanceIsCorrect_thenReturnTrue() {
Ring ring = new Ring();
assertTrue(ring instanceof Round);
}
@Test
void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
Circle circle = new Circle();
assertTrue(circle instanceof Circle);
}
@Test
void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
Circle circle = new Circle();
assertTrue(circle instanceof Round);
}
@Test
void giveWhenTypeIsInterface_thenReturnTrue() {
void givenWhenTypeIsInterface_thenReturnTrue() {
Circle circle = new Circle();
assertTrue(circle instanceof Shape);
}
@Test
void giveWhenTypeIsOfObjectType_thenReturnTrue() {
void givenWhenTypeIsOfObjectType_thenReturnTrue() {
Thread thread = new Thread();
assertTrue(thread instanceof Object);
}
@Test
void giveWhenInstanceValueIsNull_thenReturnFalse() {
void givenWhenInstanceValueIsNull_thenReturnFalse() {
Circle circle = null;
assertFalse(circle instanceof Round);
}
@Test
void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
void givenWhenComparingClassInDiffHierarchy_thenCompilationError() {
//assertFalse( circle instanceof Triangle);
}
@Test
void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() {
void givenWhenStream_whenCastWithoutInstanceOfChk_thenGetException() {
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList()));
}
@Test
void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() {
void givenWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() {
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
List<Ring> ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList());
assertEquals(2, ringList.size());

View File

@ -56,7 +56,7 @@
<properties>
<apache.commons-validator.version>1.7</apache.commons-validator.version>
<jsoup.version>1.15.4</jsoup.version>
<jsoup.version>1.16.2</jsoup.version>
</properties>
</project>

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)

View File

@ -0,0 +1,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-numbers-7</artifactId>
<name>core-java-numbers-7</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-numbers-7</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,39 @@
package com.baeldung.bigdecimalzero;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.*;
public class BigDecimalZeroVsNewBigDecimalUnitTest {
@Test
void whenComparingZeroAndNewBigDecimal_thenGetExpectedResult() {
BigDecimal bd1 = new BigDecimal("42.00");
BigDecimal bd2 = new BigDecimal("42.0000");
assertEquals(0, bd1.compareTo(bd2));
assertNotEquals(bd1, bd2);
BigDecimal zero0 = new BigDecimal(0);
assertNotEquals(zero0, new BigDecimal("0.000"));
BigDecimal zero = BigDecimal.ZERO;
assertEquals(zero, zero0);
}
@Test
void whenCallingBigDecimalZero_thenAlwaysGetTheSameObject() {
BigDecimal z1 = BigDecimal.ZERO;
BigDecimal z2 = BigDecimal.ZERO;
assertSame(z1, z2);
}
@Test
void whenCallingNewBigDecimal_thenAlwaysGetTheSameObject() {
BigDecimal z1 = new BigDecimal(0);
BigDecimal z2 = new BigDecimal(0);
assertNotSame(z1, z2);
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.doubleisint;
import com.google.common.math.DoubleMath;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CheckDoubleIsAnIntegerUnitTest {
boolean notNaNOrInfinity(double d) {
return !(Double.isNaN(d) || Double.isInfinite(d));
}
@Test
void whenConvertingToInt_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1;
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2;
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3;
assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range
}
@Test
void whenUsingModuloOperator_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0;
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0;
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0;
assertTrue(d3IsInteger);
}
@Test
void whenCheckingFloorOrCeilingValue_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1;
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2;
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3;
assertTrue(d3IsInteger);
}
@Test
void whenUsingGuava_thenGetExpectedResult() {
double d1 = 42.0D;
boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1);
assertTrue(d1IsInteger);
double d2 = 42.42D;
boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2);
assertFalse(d2IsInteger);
double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3);
assertTrue(d3IsInteger);
boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY);
assertFalse(isInfinityInt);
boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN);
assertFalse(isNanInt);
}
}

View File

@ -4,3 +4,5 @@
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)

View File

@ -27,7 +27,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -0,0 +1,69 @@
package com.baeldung.negate;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.*;
public class NegateIntUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(NegateIntUnitTest.class);
@Test
void whenUsingUnaryMinusOperator_thenGetExpectedResult() {
int x = 42;
assertEquals(-42, -x);
int z = 0;
assertEquals(0, -z);
int n = -42;
assertEquals(42, -n);
}
@Test
void whenUsingBitwiseComplementOperator_thenGetExpectedResult() {
int x = 42;
assertEquals(-42, ~x + 1);
int z = 0;
assertEquals(0, ~z + 1);
int n = -42;
assertEquals(42, ~n + 1);
}
@Test
void givenIntMinValue_whenUsingUnaryMinusOperator_thenCannotGetExpectedResult() {
int min = Integer.MIN_VALUE;
LOG.info("The value of '-min' is: " + -min);
assertTrue((-min) < 0);
}
@Test
void givenIntMinValue_whenUsingBitwiseComplementOperator_thenCannotGetExpectedResult() {
int min = Integer.MIN_VALUE;
int result = ~min + 1;
LOG.info("The value of '~min + 1' is: " + result);
assertTrue(result < 0);
}
@Test
void whenUsingUnaryMinusOperatorWithMinInt_thenGetExpectedResult() {
int x = 42;
assertEquals(-42, Math.negateExact(x));
int z = 0;
assertEquals(0, Math.negateExact(z));
int n = -42;
assertEquals(42, Math.negateExact(n));
int min = Integer.MIN_VALUE;
assertThrowsExactly(ArithmeticException.class, () -> Math.negateExact(min));
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.roundnumbertonearestmultiple;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RoundNumberToNearestMultipleUnitTest {
public static int originalNumber = 18;
public static int expectedRoundedNumber = 20;
public static int nearest = 5;
@Test
public void givenNumber_whenUsingBasicMathOperations_thenRoundUpToNearestMultipleOf5() {
int roundedNumber = (originalNumber % nearest == 0) ? originalNumber : ((originalNumber / nearest) + 1) * nearest;
assertEquals(expectedRoundedNumber, roundedNumber);
}
@Test
public void givenNumber_whenUsingMathCeil_thenRoundUpToNearestMultipleOf5() {
int roundedNumber = (int) (Math.ceil(originalNumber / (float) (nearest)) * nearest);
assertEquals(expectedRoundedNumber, roundedNumber);
}
@Test
public void givenNumber_whenUsingMathRound_thenRoundUpToNearestMultipleOf5() {
int roundedNumber = Math.round(originalNumber / (float) (nearest)) * nearest;
assertEquals(expectedRoundedNumber, roundedNumber);
}
@Test
public void givenNumber_whenUsingMathFloor_thenRoundUpToNearestMultipleOf5() {
int roundedNumber = (int) (Math.floor((double) (originalNumber + nearest / 2) / nearest) * nearest);
assertEquals(expectedRoundedNumber, roundedNumber);
}
}

View File

@ -23,7 +23,7 @@ public class AppUnitTest {
soundRecorder.build(af);
try {
soundRecorder.start();
Thread.sleep(20000);
Thread.sleep(5000);
soundRecorder.stop();
} catch (InterruptedException ex) {
fail("Exception: " + ex);

View File

@ -69,7 +69,7 @@ public class ProcessApiUnitTest {
});
});
Thread.sleep(10000);
Thread.sleep(5000);
childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
@ -100,7 +100,7 @@ public class ProcessApiUnitTest {
private void waistCPU() throws NoSuchAlgorithmException {
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
SecureRandom sr = SecureRandom.getInstanceStrong();
Duration somecpu = Duration.ofMillis(4200L);
Duration somecpu = Duration.ofMillis(2000L);
Instant end = Instant.now().plus(somecpu);
while (Instant.now().isBefore(end)) {
// System.out.println(sr.nextInt());

View File

@ -1,7 +1,7 @@
<?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">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-reflection-3</artifactId>
<name>core-java-reflection-3</name>

View File

@ -5,4 +5,5 @@ This module contains articles about core Java Security
### Relevant Articles:
- [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign)
- [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate)
- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-3)

View File

@ -177,7 +177,7 @@
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<spring.core.version>4.3.20.RELEASE</spring.core.version>
</properties>

View File

@ -48,6 +48,11 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,21 @@
package com.baeldung.streams.firstmatchingelement;
public class User {
private String userName;
private Integer userId;
public User(Integer userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public String getUserName() {
return userName;
}
public Integer getUserId() {
return userId;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.findfirstnullpointerexception;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import org.junit.Test;
public class FindFirstNullPointerExceptionUnitTest {
private final List<String> inputs = Arrays.asList(null, "foo", "bar");
@Test(expected = NullPointerException.class)
public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() {
Optional<String> firstElement = inputs.stream()
.findFirst();
}
@Test
public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() {
Optional<String> firstElement = inputs.stream()
.map(Optional::ofNullable)
.findFirst()
.flatMap(Function.identity());
assertTrue(firstElement.isEmpty());
}
@Test
public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() {
Optional<String> firstNonNullElement = inputs.stream()
.filter(Objects::nonNull)
.findFirst();
assertTrue(firstNonNullElement.isPresent());
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.streams.firstmatchingelement;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.apache.commons.collections4.IterableUtils;
import org.junit.Test;
import com.google.common.collect.Iterables;
public class FirstMatchingElementUnitTest {
private List<User> userList = List.of(new User(1, "David"), new User(2, "John"), new User(3, "Roger"), new User(4, "John"));
private String searchName = "John";
@Test
public void whenUsingStream_thenFindFirstMatchingUserIndex() {
AtomicInteger counter = new AtomicInteger(-1);
int index = userList.stream()
.filter(user -> {
counter.getAndIncrement();
return searchName.equals(user.getUserName());
})
.mapToInt(user -> counter.get())
.findFirst()
.orElse(-1);
assertEquals(1, index);
}
@Test
public void whenUsingIntStream_thenFindFirstMatchingUserIndex() {
int index = IntStream.range(0, userList.size() - 1)
.filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName()))
.findFirst()
.orElse(-1);
assertEquals(1, index);
}
@Test
public void whenUsingTakeWhile_thenFindFirstMatchingUserIndex() {
long predicateIndex = userList.stream()
.takeWhile(user -> !user.getUserName().equals(searchName))
.count();
assertEquals(1, predicateIndex);
}
@Test
public void whenUsingTakeWhile_thenFindIndexFromNoMatchingElement() {
List<User> userList = List.of(new User(1, "David"), new User(2, "Vick"), new User(3, "Roger"), new User(4, "James"));
long predicateIndex = userList.stream()
.takeWhile(user -> !user.getUserName().equals(searchName))
.count();
assertEquals(4, predicateIndex);
}
@Test
public void whenUsingGoogleGuava_thenFindFirstMatchingUserIndex() {
int index = Iterables.indexOf(userList, user -> searchName.equals(user.getUserName()));
assertEquals(1, index);
}
@Test
public void whenUsingApacheCommons_thenFindFirstMatchingUserIndex() {
int index = IterableUtils.indexOf(userList, user -> searchName.equals(user.getUserName()));
assertEquals(1, index);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.skipinputstream;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.assertArrayEquals;
public class SkipInputStreamUnitTest {
@Test
public void givenInputStreamWithBytes_whenSkipBytes_thenRemainingBytes() throws IOException {
byte[] inputData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
InputStream inputStream = new ByteArrayInputStream(inputData);
long bytesToSkip = 3;
long skippedBytes = inputStream.skip(bytesToSkip);
assertArrayEquals(new byte[]{4, 5, 6, 7, 8, 9, 10}, readRemainingBytes(inputStream));
assert skippedBytes == bytesToSkip : "Incorrect number of bytes skipped";
}
private byte[] readRemainingBytes(InputStream inputStream) throws IOException {
byte[] buffer = new byte[inputStream.available()];
int bytesRead = inputStream.read(buffer);
if (bytesRead == -1) {
throw new IOException("End of stream reached");
}
return buffer;
}
}

View File

@ -44,10 +44,10 @@
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
</dependencies>

View File

@ -72,7 +72,7 @@
<spring-core.version>5.3.9</spring-core.version>
<maven-artifact.version>3.6.3</maven-artifact.version>
<gradle-core.version>6.1.1</gradle-core.version>
<jackson-core.version>2.11.1</jackson-core.version>
<jackson-core.version>2.16.0</jackson-core.version>
<semver4j.version>3.1.0</semver4j.version>
</properties>

View File

@ -87,7 +87,7 @@ public class VersionComparisonUnitTest {
assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0);
Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null);
assertEquals(0, version1_1.compareTo(version1_1_snapshot));
assertEquals(1, version1_1.compareTo(version1_1_snapshot));
assertTrue(version1_1_snapshot.isSnapshot());
}

View File

@ -5,3 +5,4 @@
- [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters)
- [Create a Mutable String in Java](https://www.baeldung.com/java-mutable-string)
- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence)
- [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank)

View File

@ -24,12 +24,6 @@
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@ -39,7 +33,7 @@
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<version>${liquibase.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -67,6 +61,7 @@
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
<commons-text.version>1.10.0</commons-text.version>
<liquibase.core.version>4.25.0</liquibase.core.version>
</properties>
</project>

View File

@ -0,0 +1,35 @@
package com.baeldung.stringmaxlength;
public class StringMaxLengthMain {
public static void main(String[] args) {
displayRuntimeMaxStringLength();
displayMaxStringLength();
simulateStringOverflow();
}
public static void simulateStringOverflow() {
try {
int maxLength = Integer.MAX_VALUE;
char[] charArray = new char[maxLength];
for (int i = 0; i < maxLength; i++) {
charArray[i] = 'a';
}
String longString = new String(charArray);
System.out.println("Successfully created a string of length: " + longString.length());
} catch (OutOfMemoryError e) {
System.err.println("Overflow error: Attempting to create a string longer than Integer.MAX_VALUE");
e.printStackTrace();
}
}
public static void displayRuntimeMaxStringLength() {
long maxMemory = Runtime.getRuntime().maxMemory();
System.out.println("Maximum String length based on available memory: " + (maxMemory));
}
public static void displayMaxStringLength() {
int maxStringLength = Integer.MAX_VALUE;
System.out.println("Maximum String length based on Integer.MAX_VALUE: " + maxStringLength);
}
}

View File

@ -1,6 +1,6 @@
package com.baeldung.centertext;
import liquibase.repackaged.org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

View File

@ -0,0 +1,64 @@
package com.baeldung.stringbuffer;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 10000, iterations = 10)
@Warmup(batchSize = 1000, iterations = 10)
@State(Scope.Thread)
public class ComparePerformance {
String strInitial = "springframework";
String strFinal = "";
String replacement = "java-";
@Benchmark
public String benchmarkStringConcatenation() {
strFinal = "";
strFinal += strInitial;
return strFinal;
}
@Benchmark
public StringBuffer benchmarkStringBufferConcatenation() {
StringBuffer stringBuffer = new StringBuffer(strFinal);
stringBuffer.append(strInitial);
return stringBuffer;
}
@Benchmark
public String benchmarkStringReplacement() {
strFinal = strInitial.replaceFirst("spring", replacement);
return strFinal;
}
@Benchmark
public StringBuffer benchmarkStringBufferReplacement() {
StringBuffer stringBuffer = new StringBuffer(strInitial);
stringBuffer.replace(0,6, replacement);
return stringBuffer;
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(ComparePerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stringbuffer;
public class HashCode {
public static long getHashCodeString(String string) {
return string.hashCode();
}
public static long getHashCodeSBuffer(StringBuffer strBuff) {
return strBuff.hashCode();
}
public static void main(String[] args) {
String str = "Spring";
System.out.println("String HashCode pre concatenation :" + getHashCodeString(str));
str += "Framework";
System.out.println("String HashCode post concatenation :" + getHashCodeString(str));
StringBuffer sBuf = new StringBuffer("Spring");
System.out.println("StringBuffer HashCode pre concatenation :" + getHashCodeSBuffer(sBuf));
sBuf.append("Framework");
System.out.println("StringBuffer HashCode post concatenation :" + getHashCodeSBuffer(sBuf));
}
}

View File

@ -17,7 +17,7 @@ public class StringIteratorTest {
public void whenUseJavaForLoop_thenIterate() {
String input = "Hello, Baeldung!";
String expectedOutput = "Hello, Baeldung!";
String result = StringIterator.javaForLoop(input);
String result = StringIterator.javaforLoop(input);
assertEquals(expectedOutput, result);
}
@ -25,7 +25,7 @@ public class StringIteratorTest {
public void whenUseForEachMethod_thenIterate() {
String input = "Hello, Baeldung!";
String expectedOutput = "Hello, Baeldung!";
String result = StringIterator.java8ForEach(input);
String result = StringIterator.java8forEach(input);
assertEquals(expectedOutput, result);
}

View File

@ -0,0 +1,32 @@
package com.baeldung.stringbuffer;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ComparePerformanceTest {
ComparePerformance cp = new ComparePerformance();
@Test
public void whenStringConcatenated_thenResultAsExpected() {
assertThat(cp.benchmarkStringConcatenation()).isEqualTo("springframework");
}
@Test
public void whenStringBufferConcatenated_thenResultAsExpected() {
StringBuffer stringBuffer = new StringBuffer("springframework");
assertThat(cp.benchmarkStringBufferConcatenation()).isEqualToIgnoringCase(stringBuffer);
}
@Test
public void whenStringReplaced_thenResultAsExpected() {
assertThat(cp.benchmarkStringReplacement()).isEqualTo("java-framework");
}
@Test
public void whenStringBufferReplaced_thenResultAsExpected() {
StringBuffer stringBuffer = new StringBuffer("java-framework");
assertThat(cp.benchmarkStringBufferReplacement()).isEqualToIgnoringCase(stringBuffer);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stringbuffer;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HashCodeTest {
String str = "Spring";
StringBuffer sBuf = new StringBuffer("Spring");
@Test
public void whenStringConcat_thenHashCodeChanges() {
HashCode hc = new HashCode();
long initialStringHashCode = hc.getHashCodeString(str);
long initialSBufHashCode = hc.getHashCodeSBuffer(sBuf);
str += "Framework";
sBuf.append("Framework");
assertThat(initialStringHashCode).isNotEqualTo(hc.getHashCodeString(str));
assertThat(initialSBufHashCode).isEqualTo(hc.getHashCodeSBuffer(sBuf));
}
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-string-swing</artifactId>
<name>core-java-string-swing</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.customfont;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class CustomFonts {
public static void main(String[] args) {
usingCustomFonts();
}
public static void usingCustomFonts() {
final GraphicsEnvironment GE = GraphicsEnvironment.getLocalGraphicsEnvironment();
final List<String> AVAILABLE_FONT_FAMILY_NAMES = Arrays.asList(GE.getAvailableFontFamilyNames());
try {
final List<File> LIST = Arrays.asList(
new File("font/JetBrainsMono/JetBrainsMono-Thin.ttf"),
new File("font/JetBrainsMono/JetBrainsMono-Light.ttf"),
new File("font/Roboto/Roboto-Light.ttf"),
new File("font/Roboto/Roboto-Regular.ttf"),
new File("font/Roboto/Roboto-Medium.ttf")
);
for (File LIST_ITEM : LIST) {
if (LIST_ITEM.exists()) {
Font FONT = Font.createFont(Font.TRUETYPE_FONT, LIST_ITEM);
if (!AVAILABLE_FONT_FAMILY_NAMES.contains(FONT.getFontName())) {
GE.registerFont(FONT);
}
}
}
} catch (FontFormatException | IOException exception) {
JOptionPane.showMessageDialog(null, exception.getMessage());
}
JFrame frame = new JFrame("Custom Font Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JLabel label1 = new JLabel("TEXT1");
label1.setFont(new Font("Roboto Medium", Font.PLAIN, 17));
JLabel label2 = new JLabel("TEXT2");
label2.setFont(new Font("JetBrainsMono-Thin", Font.PLAIN, 17));
frame.add(label1);
frame.add(label2);
frame.pack();
frame.setVisible(true);
}
}

View File

@ -6,3 +6,4 @@
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)
- [Generating Unique Positive long Using UUID in Java](https://www.baeldung.com/java-uuid-unique-long-generation)

View File

@ -154,7 +154,7 @@
</profiles>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,83 @@
package com.baeldung.uuid;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.UUID;
/**
* Methods are called by reflection in the unit test
*/
@SuppressWarnings("unused")
public class UUIDPositiveLongGenerator {
public long getLeastSignificantBits() {
return Math.abs(UUID.randomUUID().getLeastSignificantBits());
}
public long getMostSignificantBits() {
return Math.abs(UUID.randomUUID().getMostSignificantBits());
}
public long combineByteBuffer() {
UUID uuid = UUID.randomUUID();
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
bb.rewind();
return Math.abs(bb.getLong());
}
public long combineBitwise() {
UUID uniqueUUID = UUID.randomUUID();
long mostSignificantBits = uniqueUUID.getMostSignificantBits();
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
public long combineDirect() {
UUID uniqueUUID = UUID.randomUUID();
long mostSignificantBits = uniqueUUID.getMostSignificantBits();
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs(mostSignificantBits ^ (leastSignificantBits >> 1));
}
public long combinePermutation() {
UUID uuid = UUID.randomUUID();
long mostSigBits = uuid.getMostSignificantBits();
long leastSigBits = uuid.getLeastSignificantBits();
byte[] uuidBytes = new byte[16];
for (int i = 0; i < 8; i++) {
uuidBytes[i] = (byte) (mostSigBits >>> (8 * (7 - i)));
uuidBytes[i + 8] = (byte) (leastSigBits >>> (8 * (7 - i)));
}
long result = 0;
for (byte b : uuidBytes) {
result = (result << 8) | (b & 0xFF);
}
return Math.abs(result);
}
public long combineWithSecureRandom() {
UUID uniqueUUID = UUID.randomUUID();
SecureRandom secureRandom = new SecureRandom();
long randomBits = secureRandom.nextLong();
long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ randomBits;
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
public long combineWithNanoTime() {
UUID uniqueUUID = UUID.randomUUID();
long nanoTime = System.nanoTime();
long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ nanoTime;
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class UUIDPositiveLongGeneratorUnitTest {
private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator();
private final Set<Long> uniqueValues = new HashSet<>();
@Test
void whenForeachMethods_thenRetryWhileNotUnique() throws Exception {
for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) {
long uniqueValue;
do uniqueValue = (long) method.invoke(uuidLongGenerator); while (!isUnique(uniqueValue));
assertThat(uniqueValue).isPositive();
}
}
@Test
void whenGivenLongValue_thenCheckUniqueness() {
long uniqueValue = generateUniqueLong();
assertThat(uniqueValue).isPositive();
}
private long generateUniqueLong() {
long uniqueValue;
do uniqueValue = uuidLongGenerator.combineBitwise(); while (!isUnique(uniqueValue));
return uniqueValue;
}
private boolean isUnique(long value) {
// Implement uniqueness checking logic, for example, by checking in the database
return uniqueValues.add(value);
}
}

View File

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

View File

@ -54,20 +54,21 @@
<module>core-java-concurrency-simple</module>
<module>core-java-datetime-string</module>
<module>core-java-io-conversions-2</module>
<module>core-java-ipc</module>
<module>core-java-jpms</module>
<module>core-java-lang-oop-constructors-2</module>
<module>core-java-methods</module>
<module>core-java-networking-3</module>
<module>core-java-os</module>
<!--<module>core-java-os</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-perf-2</module>
<module>core-java-streams-4</module>
<module>core-java-streams-5</module>
<module>core-java-streams-collect</module>
<module>core-java-streams-maps</module>
<module>core-java-string-algorithms-3</module>
<module>core-java-string-operations-3</module>
<!--<module>core-java-string-operations-3</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-string-operations-4</module>
<module>core-java-string-operations-5</module>
<!--<module>core-java-string-operations-5</module>--> <!-- failing after upgrading to jdk17 -->
<!--<module>core-java-strings</module> Failing test cases JAVA-24414-->
<module>core-java-time-measurements</module>
<module>core-java-annotations</module>
@ -122,13 +123,13 @@
<module>core-java-io</module>
<module>core-java-io-2</module>
<module>core-java-io-3</module>
<module>core-java-io-4</module>
<!--<module>core-java-io-4</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-io-5</module>
<module>core-java-io-apis</module>
<module>core-java-io-apis-2</module>
<module>core-java-io-conversions</module>
<module>core-java-jar</module>
<module>core-java-jndi</module>
<!--<module>core-java-jndi</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-jvm</module>
<module>core-java-jvm-2</module>
<module>core-java-jvm-3</module>
@ -143,11 +144,11 @@
<module>core-java-lang-oop-constructors</module>
<module>core-java-lang-oop-patterns</module>
<module>core-java-lang-oop-generics</module>
<module>core-java-lang-oop-modifiers</module>
<!--<module>core-java-lang-oop-modifiers</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-lang-oop-types</module>
<module>core-java-lang-oop-types-2</module>
<module>core-java-lang-oop-inheritance</module>
<module>core-java-lang-oop-methods</module>
<!--<module>core-java-lang-oop-methods</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-lang-oop-others</module>
<module>core-java-lang-operators</module>
<module>core-java-lang-operators-2</module>
@ -165,6 +166,7 @@
<module>core-java-numbers-4</module>
<module>core-java-numbers-5</module>
<module>core-java-numbers-6</module>
<module>core-java-numbers-7</module>
<module>core-java-optional</module>
<module>core-java-perf</module>
<module>core-java-properties</module>
@ -183,7 +185,8 @@
<module>core-java-string-algorithms</module>
<module>core-java-string-algorithms-2</module>
<module>core-java-string-apis</module>
<module>core-java-string-apis-2</module>
<!--<module>core-java-string-apis-2</module>--> <!-- failing after upgrading to jdk17 -->
<module>core-java-swing</module>
<module>core-java-string-conversions</module>
<module>core-java-string-conversions-2</module>
<module>core-java-string-conversions-3</module>
@ -223,5 +226,4 @@
</dependency>
</dependencies>
</dependencyManagement>
</project>

View File

@ -68,7 +68,6 @@
<properties>
<dl4j.version>0.9.1</dl4j.version> <!-- Latest non beta version -->
<httpclient.version>4.3.5</httpclient.version>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>

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