This commit is contained in:
priyank-sriv 2020-05-24 16:44:20 +05:30
commit b2fac9be36
828 changed files with 12842 additions and 2352 deletions

View File

@ -21,10 +21,10 @@
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>

View File

@ -3,7 +3,7 @@
This module contains articles about Apache CXF
## Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -1,11 +1,14 @@
package com.baeldung;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;

View File

@ -1,16 +1,24 @@
package com.baeldung;
import org.apache.shiro.authc.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
public class MyCustomRealm extends JdbcRealm {

View File

@ -1,14 +1,15 @@
package com.baeldung.shiro.permissions.custom;
import com.baeldung.MyCustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,7 +1,6 @@
## Atomikos
This module contains articles about Atomikos
### Relevant Articles:
- [Guide Transactions Using Atomikos]()
- [A Guide to Atomikos](https://www.baeldung.com/java-atomikos)

56
aws-app-sync/pom.xml Normal file
View File

@ -0,0 +1,56 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-app-sync</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aws-app-sync</name>
<description>Spring Boot using AWS App Sync</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.awsappsync;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class AppSyncClientHelper {
static String apiUrl = "<INSERT API URL HERE>";
static String apiKey = "<INSERT API KEY HERE>";
static String API_KEY_HEADER = "x-api-key";
public static WebClient.ResponseSpec getResponseBodySpec(Map<String, Object> requestBody) {
return WebClient
.builder()
.baseUrl(apiUrl)
.defaultHeader(API_KEY_HEADER, apiKey)
.defaultHeader("Content-Type", "application/json")
.build()
.method(HttpMethod.POST)
.uri("/graphql")
.body(BodyInserters.fromValue(requestBody))
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.acceptCharset(StandardCharsets.UTF_8)
.retrieve();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.awsappsync;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AwsAppSyncApplication {
public static void main(String[] args) {
SpringApplication.run(AwsAppSyncApplication.class, args);
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.awsappsync;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@Disabled
class AwsAppSyncApplicationTests {
@Test
void givenGraphQuery_whenListEvents_thenReturnAllEvents() {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("query", "query ListEvents {"
+ " listEvents {"
+ " items {"
+ " id"
+ " name"
+ " where"
+ " when"
+ " description"
+ " }"
+ " }"
+ "}");
requestBody.put("variables", "");
requestBody.put("operationName", "ListEvents");
String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody)
.bodyToMono(String.class).block();
assertNotNull(bodyString);
assertTrue(bodyString.contains("My First Event"));
assertTrue(bodyString.contains("where"));
assertTrue(bodyString.contains("when"));
}
@Test
void givenGraphAdd_whenMutation_thenReturnIdNameDesc() {
String queryString = "mutation add {"
+ " createEvent("
+ " name:\"My added GraphQL event\""
+ " where:\"Day 2\""
+ " when:\"Saturday night\""
+ " description:\"Studying GraphQL\""
+ " ){"
+ " id"
+ " name"
+ " description"
+ " }"
+ "}";
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("query", queryString);
requestBody.put("variables", "");
requestBody.put("operationName", "add");
WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody);
String bodyString = response.bodyToMono(String.class).block();
assertNotNull(bodyString);
assertTrue(bodyString.contains("My added GraphQL event"));
assertFalse(bodyString.contains("where"));
assertFalse(bodyString.contains("when"));
}
}

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool)

View File

@ -16,10 +16,6 @@
<relativePath>../../parent-boot-2</relativePath>
</parent>
<properties>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -13,4 +13,5 @@ This module contains articles about core Groovy concepts
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
- [How to Determine the Data Type in Groovy](https://www.baeldung.com/groovy-determine-data-type)
- [[<-- Prev]](/core-groovy)

View File

@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
- [[More -->]](/core-groovy-2)
- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer)
- [[More -->]](/core-groovy-2)

View File

@ -8,3 +8,4 @@ This module contains articles about Java 14.
- [Java Text Blocks](https://www.baeldung.com/java-text-blocks)
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)

View File

@ -0,0 +1,22 @@
package com.baeldung.java14.record;
import java.util.Objects;
public record Person (String name, String address) {
public static String UNKWOWN_ADDRESS = "Unknown";
public static String UNNAMED = "Unnamed";
public Person {
Objects.requireNonNull(name);
Objects.requireNonNull(address);
}
public Person(String name) {
this(name, UNKWOWN_ADDRESS);
}
public static Person unnamed(String address) {
return new Person(UNNAMED, address);
}
}

View File

@ -0,0 +1,84 @@
package com.baeldung.java14.foreign.api;
import jdk.incubator.foreign.*;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
public class ForeignMemoryUnitTest {
@Test
public void whenAValueIsSet_thenAccessTheValue() {
long value = 10;
MemoryAddress memoryAddress =
MemorySegment.allocateNative(8).baseAddress();
VarHandle varHandle = MemoryHandles.varHandle(long.class,
ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
assertThat(varHandle.get(memoryAddress), is(value));
}
@Test
public void whenMultipleValuesAreSet_thenAccessAll() {
VarHandle varHandle = MemoryHandles.varHandle(int.class,
ByteOrder.nativeOrder());
try(MemorySegment memorySegment =
MemorySegment.allocateNative(100)) {
MemoryAddress base = memorySegment.baseAddress();
for(int i=0; i<25; i++) {
varHandle.set(base.addOffset((i*4)), i);
}
for(int i=0; i<25; i++) {
assertThat(varHandle.get(base.addOffset((i*4))), is(i));
}
}
}
@Test
public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() {
SequenceLayout sequenceLayout =
MemoryLayout.ofSequence(25,
MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder()));
VarHandle varHandle =
sequenceLayout.varHandle(long.class,
MemoryLayout.PathElement.sequenceElement());
try(MemorySegment memorySegment =
MemorySegment.allocateNative(sequenceLayout)) {
MemoryAddress base = memorySegment.baseAddress();
for(long i=0; i<sequenceLayout.elementCount().getAsLong(); i++) {
varHandle.set(base, i, i);
}
for(long i=0; i<sequenceLayout.elementCount().getAsLong(); i++) {
assertThat(varHandle.get(base, i), is(i));
}
}
}
@Test
public void whenSlicingMemorySegment_thenTheyCanBeAccessedIndividually() {
MemoryAddress memoryAddress =
MemorySegment.allocateNative(12).baseAddress();
MemoryAddress memoryAddress1 =
memoryAddress.segment().asSlice(0,4).baseAddress();
MemoryAddress memoryAddress2 =
memoryAddress.segment().asSlice(4,4).baseAddress();
MemoryAddress memoryAddress3 =
memoryAddress.segment().asSlice(8,4).baseAddress();
VarHandle intHandle =
MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
intHandle.set(memoryAddress1, Integer.MIN_VALUE);
intHandle.set(memoryAddress2, 0);
intHandle.set(memoryAddress3, Integer.MAX_VALUE);
assertThat(intHandle.get(memoryAddress1), is(Integer.MIN_VALUE));
assertThat(intHandle.get(memoryAddress2), is(0));
assertThat(intHandle.get(memoryAddress3), is(Integer.MAX_VALUE));
}
}

View File

@ -0,0 +1,150 @@
package com.baeldung.java14.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PersonTest {
@Test
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person1 = new Person(name, address);
Person person2 = new Person(name, address);
assertTrue(person1.equals(person2));
}
@Test
public void givenDifferentObject_whenEquals_thenNotEqual() {
Person person = new Person("John Doe", "100 Linda Ln.");
assertFalse(person.equals(new Object()));
}
@Test
public void givenDifferentName_whenEquals_thenPersonsNotEqual() {
String address = "100 Linda Ln.";
Person person1 = new Person("Jane Doe", address);
Person person2 = new Person("John Doe", address);
assertFalse(person1.equals(person2));
}
@Test
public void givenDifferentAddress_whenEquals_thenPersonsNotEqual() {
String name = "John Doe";
Person person1 = new Person(name, "100 Linda Ln.");
Person person2 = new Person(name, "200 London Ave.");
assertFalse(person1.equals(person2));
}
@Test
public void givenSameNameAndAddress_whenHashCode_thenPersonsEqual() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person1 = new Person(name, address);
Person person2 = new Person(name, address);
assertEquals(person1.hashCode(), person2.hashCode());
}
@Test
public void givenDifferentObject_whenHashCode_thenNotEqual() {
Person person = new Person("John Doe", "100 Linda Ln.");
assertNotEquals(person.hashCode(), new Object().hashCode());
}
@Test
public void givenDifferentName_whenHashCode_thenPersonsNotEqual() {
String address = "100 Linda Ln.";
Person person1 = new Person("Jane Doe", address);
Person person2 = new Person("John Doe", address);
assertNotEquals(person1.hashCode(), person2.hashCode());
}
@Test
public void givenDifferentAddress_whenHashCode_thenPersonsNotEqual() {
String name = "John Doe";
Person person1 = new Person(name, "100 Linda Ln.");
Person person2 = new Person(name, "200 London Ave.");
assertNotEquals(person1.hashCode(), person2.hashCode());
}
@Test
public void givenValidNameAndAddress_whenGetNameAndAddress_thenExpectedValuesReturned() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person = new Person(name, address);
assertEquals(name, person.name());
assertEquals(address, person.address());
}
@Test
public void givenValidNameAndAddress_whenToString_thenCorrectStringReturned() {
String name = "John Doe";
String address = "100 Linda Ln.";
Person person = new Person(name, address);
assertEquals("Person[name=" + name + ", address=" + address + "]", person.toString());
}
@Test(expected = NullPointerException.class)
public void givenNullName_whenConstruct_thenErrorThrown() {
new Person(null, "100 Linda Ln.");
}
@Test(expected = NullPointerException.class)
public void givenNullAddress_whenConstruct_thenErrorThrown() {
new Person("John Doe", null);
}
@Test
public void givenUnknownAddress_whenConstructing_thenAddressPopulated() {
String name = "John Doe";
Person person = new Person(name);
assertEquals(name, person.name());
assertEquals(Person.UNKWOWN_ADDRESS, person.address());
}
@Test
public void givenUnnamed_whenConstructingThroughFactory_thenNamePopulated() {
String address = "100 Linda Ln.";
Person person = Person.unnamed(address);
assertEquals(Person.UNNAMED, person.name());
assertEquals(address, person.address());
}
}

View File

@ -9,3 +9,4 @@ This module contains articles about the improvements to core Java features intro
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)

View File

@ -33,6 +33,11 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>

View File

@ -0,0 +1,57 @@
package com.baeldung.java9.io.conversion;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
public class InputStreamToByteArrayUnitTest {
@Test
public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = new byte[initialStream.available()];
initialStream.read(targetArray);
}
@Test
public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
final byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
final byte[] byteArray = buffer.toByteArray();
}
@Test
public void givenUsingPlainJava9_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
byte[] data = is.readAllBytes();
}
@Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 })
.openStream();
final byte[] targetArray = ByteStreams.toByteArray(initialStream);
}
@Test
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = IOUtils.toByteArray(initialStream);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.inputstreamtobytes;
package com.baeldung.java9.io.conversion;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;

View File

@ -5,4 +5,5 @@ This module contains articles about Map data structures in Java.
### Relevant Articles:
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -4,5 +4,5 @@
### Relevant Articles:
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
- [Testing Multi-Threaded Code in Java] (https://www.baeldung.com/java-testing-multithreaded)
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)

View File

@ -11,4 +11,5 @@ This module contains articles about advanced topics about multithreading with co
- [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing)
- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming)
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -0,0 +1,81 @@
package com.baeldung.lockfree;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class NonBlockingQueue<T> {
private final AtomicReference<Node<T>> head, tail;
private final AtomicInteger size;
public NonBlockingQueue() {
head = new AtomicReference<>(null);
tail = new AtomicReference<>(null);
size = new AtomicInteger();
size.set(0);
}
public void add(T element) {
if (element == null) {
throw new NullPointerException();
}
Node<T> node = new Node<>(element);
Node<T> currentTail;
do {
currentTail = tail.get();
node.setPrevious(currentTail);
} while(!tail.compareAndSet(currentTail, node));
if(node.previous != null) {
node.previous.next = node;
}
head.compareAndSet(null, node); //if we are inserting the first element
size.incrementAndGet();
}
public T get() {
if(head.get() == null) {
throw new NoSuchElementException();
}
Node<T> currentHead;
Node<T> nextNode;
do {
currentHead = head.get();
nextNode = currentHead.getNext();
} while(!head.compareAndSet(currentHead, nextNode));
size.decrementAndGet();
return currentHead.getValue();
}
public int size() {
return this.size.get();
}
private class Node<T> {
private final T value;
private volatile Node<T> next;
private volatile Node<T> previous;
public Node(T value) {
this.value = value;
this.next = null;
}
public T getValue() {
return value;
}
public Node<T> getNext() {
return next;
}
public void setPrevious(Node<T> previous) {
this.previous = previous;
}
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.exchanger;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import static java.util.concurrent.CompletableFuture.runAsync;
public class ExchangerPipeLineManualTest {
private static final int BUFFER_SIZE = 100;
@Test
public void givenData_whenPassedThrough_thenCorrect() throws InterruptedException, ExecutionException {
Exchanger<Queue<String>> readerExchanger = new Exchanger<>();
Exchanger<Queue<String>> writerExchanger = new Exchanger<>();
int counter = 0;
Runnable reader = () -> {
Queue<String> readerBuffer = new ConcurrentLinkedQueue<>();
while (true) {
readerBuffer.add(UUID.randomUUID().toString());
if (readerBuffer.size() >= BUFFER_SIZE) {
try {
readerBuffer = readerExchanger.exchange(readerBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
};
Runnable processor = () -> {
Queue<String> processorBuffer = new ConcurrentLinkedQueue<>();
Queue<String> writerBuffer = new ConcurrentLinkedQueue<>();
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
while (true) {
writerBuffer.add(processorBuffer.poll());
if (processorBuffer.isEmpty()) {
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
writerBuffer = writerExchanger.exchange(writerBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
Runnable writer = () -> {
Queue<String> writerBuffer = new ConcurrentLinkedQueue<>();
try {
writerBuffer = writerExchanger.exchange(writerBuffer);
while (true) {
System.out.println(writerBuffer.poll());
if (writerBuffer.isEmpty()) {
writerBuffer = writerExchanger.exchange(writerBuffer);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture.allOf(runAsync(reader), runAsync(processor), runAsync(writer)).get();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.exchanger;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import static java.util.concurrent.CompletableFuture.runAsync;
public class ExchangerUnitTest {
@Test
public void givenThreads_whenMessageExchanged_thenCorrect() {
Exchanger<String> exchanger = new Exchanger<>();
Runnable taskA = () -> {
try {
String message = exchanger.exchange("from A");
assertEquals("from B", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
Runnable taskB = () -> {
try {
String message = exchanger.exchange("from B");
assertEquals("from A", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture.allOf(runAsync(taskA), runAsync(taskB)).join();
}
@Test
public void givenThread_WhenExchangedMessage_thenCorrect() throws InterruptedException, ExecutionException {
Exchanger<String> exchanger = new Exchanger<>();
Runnable runner = () -> {
try {
String message = exchanger.exchange("from runner");
assertEquals("to runner", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture<Void> result = CompletableFuture.runAsync(runner);
String msg = exchanger.exchange("to runner");
assertEquals("from runner", msg);
result.join();
}
}

View File

@ -23,7 +23,12 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
@ -42,6 +47,8 @@
<properties>
<jmh.version>1.21</jmh.version>
<guava.version>28.2-jre</guava.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,66 @@
package com.baeldung.concurrent.queue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestConcurrentLinkedQueue {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
Collection<Integer> elements = Arrays.asList(1, 2, 3, 4, 5);
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>(elements);
assertThat(concurrentLinkedQueue).containsExactly(1, 2, 3, 4, 5);
}
@Test
public void givenQueueIsEmpty_WhenAccessingTheQueue_ThenQueueReturnsNull() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
executorService.submit(() -> assertNull("Retrieve object is null", concurrentLinkedQueue.poll()));
TimeUnit.SECONDS.sleep(1);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
@Test
public void givenProducerOffersElementInQueue_WhenConsumerPollsQueue_ThenItRetrievesElement() throws Exception {
int element = 1;
ExecutorService executorService = Executors.newFixedThreadPool(2);
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
Runnable offerTask = () -> concurrentLinkedQueue.offer(element);
Callable<Integer> pollTask = () -> {
while (concurrentLinkedQueue.peek() != null) {
return concurrentLinkedQueue.poll()
.intValue();
}
return null;
};
executorService.submit(offerTask);
TimeUnit.SECONDS.sleep(1);
Future<Integer> returnedElement = executorService.submit(pollTask);
assertThat(returnedElement.get()
.intValue(), is(equalTo(element)));
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.concurrent.queue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestLinkedBlockingQueue {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
Collection<Integer> elements = Arrays.asList(1, 2, 3, 4, 5);
LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>(elements);
assertThat(linkedBlockingQueue).containsExactly(1, 2, 3, 4, 5);
}
@Test
public void givenQueueIsEmpty_WhenAccessingTheQueue_ThenThreadBlocks() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>();
executorService.submit(() -> {
try {
linkedBlockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
TimeUnit.SECONDS.sleep(1);
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService.shutdown();
}
@Test
public void givenProducerPutsElementInQueue_WhenConsumerAccessQueue_ThenItRetrieve() {
int element = 10;
ExecutorService executorService = Executors.newFixedThreadPool(2);
LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>();
Runnable putTask = () -> {
try {
linkedBlockingQueue.put(element);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Callable<Integer> takeTask = () -> {
try {
return linkedBlockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
};
executorService.submit(putTask);
Future<Integer> returnElement = executorService.submit(takeTask);
try {
TimeUnit.SECONDS.sleep(1);
assertThat(returnElement.get()
.intValue(), is(equalTo(element)));
executorService.awaitTermination(1, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
executorService.shutdown();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.weeknumber;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class WeekNumberUsingCalendar {
public int getWeekNumberFrom(String day, String dateFormat, Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance(locale);
Date date = sdf.parse(day);
calendar.setTime(date);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekNumberFrom(int year, int month, int day, Locale locale) {
Calendar calendar = Calendar.getInstance(locale);
calendar.set(year, month, day);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekNumberFrom(int year, int month, int day, int firstDayOfWeek, int minimalDaysInFirstWeek, Locale locale) {
Calendar calendar = Calendar.getInstance(locale);
calendar.setFirstDayOfWeek(firstDayOfWeek);
calendar.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
calendar.set(year, month, day);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public static void main(String[] args) {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
System.out.println(calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.weeknumber;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class WeekNumberUsingLocalDate {
public Integer getWeekNumberUsingWeekFiedsFrom(String day, String dayFormat, Locale locale) {
LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat));
return date.get(WeekFields.of(locale)
.weekOfYear());
}
public Integer getWeekNumberUsinWeekFieldsFrom(int year, int month, int day, Locale locale) {
LocalDate date = LocalDate.of(year, month, day);
return date.get(WeekFields.of(locale)
.weekOfYear());
}
public Integer getWeekNumberUsingChronoFieldFrom(int year, int month, int day) {
LocalDate date = LocalDate.of(year, month, day);
return date.get(ChronoField.ALIGNED_WEEK_OF_YEAR);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;
import org.junit.Test;
public class WeekNumberUsingCalendarUnitTest {
@Test
public void givenDateInStringAndDateFormatUsingLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(12, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.ITALY));
}
@Test
public void givenDateInStringAndDateFormatUsingLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.CANADA));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(12, calendar.getWeekNumberFrom(2020, 2, 22, Locale.ITALY));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleItalyChangingWeekCalculationSettings_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Calendar.SUNDAY, 4, Locale.ITALY));
}
@Test
public void givenDateInYearMonthDayNumbersLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() {
WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar();
assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA));
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
public class WeekNumberUsingLocalDateUnitTest {
@Test
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.ITALY)
.longValue());
}
@Test
public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(13, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.CANADA)
.longValue());
}
@Test
public void givenDateInStringAndDateFormatUsingChronoFieds_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsingChronoFieldFrom(2020, 3, 22)
.longValue());
}
@Test
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(12, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.ITALY)
.longValue());
}
@Test
public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() {
WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate();
assertEquals(13, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.CANADA)
.longValue());
}
}

View File

@ -9,3 +9,6 @@ This module contains articles about core java exceptions
- [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception)
- [How to Handle Java SocketException](https://www.baeldung.com/java-socketexception)
- [Java Suppressed Exceptions](https://www.baeldung.com/java-suppressed-exceptions)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)

View File

@ -23,6 +23,11 @@
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
</dependencies>
<description> </description>
@ -30,6 +35,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons.lang3.version>3.10</commons.lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.io.BufferedReader;
import java.io.File;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.util.ArrayList;
import java.util.Iterator;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.net.MalformedURLException;
import java.net.URL;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import java.text.DateFormat;
import java.text.ParseException;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.rootcausefinder;
package com.baeldung.rootcausefinder;
import java.time.LocalDate;
import java.time.Period;

View File

@ -1,4 +1,4 @@
package com.baeldung.exceptions.globalexceptionhandler;
package com.baeldung.globalexceptionhandler;
import org.junit.After;
import org.junit.Before;

View File

@ -1,7 +1,7 @@
package com.baeldung.exceptions.rootcausefinder;
package com.baeldung.rootcausefinder;
import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.CalculationException;
import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.DateOutOfRangeException;
import com.baeldung.rootcausefinder.RootCauseFinder.CalculationException;
import com.baeldung.rootcausefinder.RootCauseFinder.DateOutOfRangeException;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.jupiter.api.Assertions;
@ -11,8 +11,7 @@ import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.AgeCalculator;
import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.findCauseUsingPlainJava;
import static com.baeldung.rootcausefinder.RootCauseFinder.AgeCalculator;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@ -38,7 +37,7 @@ public class RootCauseFinderUnitTest {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
}
}
@ -47,7 +46,7 @@ public class RootCauseFinderUnitTest {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
}
}
@ -56,7 +55,7 @@ public class RootCauseFinderUnitTest {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
}
}

View File

@ -12,9 +12,5 @@ This module contains articles about core java exceptions
- [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws)
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)
- [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
- [[Next -->]](/core-java-modules/core-java-exceptions-2)

View File

@ -4,6 +4,5 @@ This module contains articles about core Java input/output(IO) conversions.
### Relevant Articles:
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
- [Java Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)

View File

@ -2,7 +2,6 @@ package com.baeldung.inputstreamtostring;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
@ -11,13 +10,26 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
@ -46,6 +58,18 @@ public class JavaInputStreamToXUnitTest {
assertEquals(textBuilder.toString(), originalString);
}
@Test
public void givenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect() {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
.lines()
.collect(Collectors.joining("\n"));
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
@ -127,42 +151,6 @@ public class JavaInputStreamToXUnitTest {
assertThat(result, equalTo(originalString));
}
// tests - InputStream to byte[]
@Test
public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = new byte[initialStream.available()];
initialStream.read(targetArray);
}
@Test
public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
final byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
final byte[] byteArray = buffer.toByteArray();
}
@Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 }).openStream();
final byte[] targetArray = ByteStreams.toByteArray(initialStream);
}
@Test
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
final byte[] targetArray = IOUtils.toByteArray(initialStream);
}
// tests - InputStream to File
@Test

View File

@ -20,7 +20,12 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
@ -65,6 +70,8 @@
<jmh-generator.version>1.19</jmh-generator.version>
<assertj.version>3.12.2</assertj.version>
<commons.beanutils.version>1.9.4</commons.beanutils.version>
<commons-lang3.version>3.10</commons-lang3.version>
<guava.version>29.0-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,51 @@
package com.baeldung.comparing;
import java.time.LocalDate;
import java.util.Objects;
public class PersonWithEquals {
private String firstName;
private String lastName;
private LocalDate birthDate;
public PersonWithEquals(String firstName, String lastName) {
if (firstName == null || lastName == null) {
throw new NullPointerException("Names can't be null");
}
this.firstName = firstName;
this.lastName = lastName;
}
public PersonWithEquals(String firstName, String lastName, LocalDate birthDate) {
this(firstName, lastName);
this.birthDate = birthDate;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public LocalDate birthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEquals that = (PersonWithEquals) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName) &&
Objects.equals(birthDate, that.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.comparing;
import java.time.LocalDate;
import java.util.Objects;
public class PersonWithEqualsAndComparable implements Comparable<PersonWithEqualsAndComparable> {
private String firstName;
private String lastName;
private LocalDate birthDate;
public PersonWithEqualsAndComparable(String firstName, String lastName) {
if (firstName == null || lastName == null) {
throw new NullPointerException("Names can't be null");
}
this.firstName = firstName;
this.lastName = lastName;
}
public PersonWithEqualsAndComparable(String firstName, String lastName, LocalDate birthDate) {
this(firstName, lastName);
this.birthDate = birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEqualsAndComparable that = (PersonWithEqualsAndComparable) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName) &&
Objects.equals(birthDate, that.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
@Override
public int compareTo(PersonWithEqualsAndComparable o) {
int lastNamesComparison = this.lastName.compareTo(o.lastName);
if (lastNamesComparison == 0) {
int firstNamesComparison = this.firstName.compareTo(o.firstName);
if (firstNamesComparison == 0) {
if (this.birthDate != null && o.birthDate != null) {
return this.birthDate.compareTo(o.birthDate);
} else if (this.birthDate != null) {
return 1;
} else if (o.birthDate != null) {
return -1;
} else {
return 0;
}
} else {
return firstNamesComparison;
}
} else {
return lastNamesComparison;
}
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.comparing;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.Objects;
public class PersonWithEqualsAndComparableUsingComparator implements Comparable<PersonWithEqualsAndComparableUsingComparator> {
private String firstName;
private String lastName;
private LocalDate birthDate;
public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName) {
if (firstName == null || lastName == null) {
throw new NullPointerException("Names can't be null");
}
this.firstName = firstName;
this.lastName = lastName;
}
public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName, LocalDate birthDate) {
this(firstName, lastName);
this.birthDate = birthDate;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public LocalDate birthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEqualsAndComparableUsingComparator that = (PersonWithEqualsAndComparableUsingComparator) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName) &&
Objects.equals(birthDate, that.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
@Override
public int compareTo(PersonWithEqualsAndComparableUsingComparator o) {
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder()))
.compare(this, o);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.comparing;
import java.time.LocalDate;
import java.util.Objects;
public class PersonWithEqualsAndWrongComparable implements Comparable<PersonWithEqualsAndWrongComparable> {
private String firstName;
private String lastName;
private LocalDate birthDate;
public PersonWithEqualsAndWrongComparable(String firstName, String lastName) {
if (firstName == null || lastName == null) {
throw new NullPointerException("Names can't be null");
}
this.firstName = firstName;
this.lastName = lastName;
}
public PersonWithEqualsAndWrongComparable(String firstName, String lastName, LocalDate birthDate) {
this(firstName, lastName);
this.birthDate = birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEqualsAndWrongComparable that = (PersonWithEqualsAndWrongComparable) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName) &&
Objects.equals(birthDate, that.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
@Override
public int compareTo(PersonWithEqualsAndWrongComparable o) {
return this.lastName.compareTo(o.lastName);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.comparing;
public class PersonWithoutEquals {
private String firstName;
private String lastName;
public PersonWithoutEquals(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.comparing;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ApacheCommonsObjectUtilsUnitTest {
@Test
void givenTwoStringsWithSameValues_whenApacheCommonsEqualityMethods_thenEqualsTrueNotEqualsFalse() {
String a = new String("Hello!");
String b = new String("Hello!");
assertThat(ObjectUtils.equals(a, b)).isTrue();
assertThat(ObjectUtils.notEqual(a, b)).isFalse();
}
@Test
void givenTwoStringsWithDifferentValues_whenApacheCommonsEqualityMethods_thenEqualsFalseNotEqualsTrue() {
String a = new String("Hello!");
String b = new String("Hello World!");
assertThat(ObjectUtils.equals(a, b)).isFalse();
assertThat(ObjectUtils.notEqual(a, b)).isTrue();
}
@Test
void givenTwoStringsWithConsecutiveValues_whenApacheCommonsCompare_thenNegative() {
String first = new String("Hello!");
String second = new String("How are you?");
assertThat(ObjectUtils.compare(first, second)).isNegative();
}
@Test
void givenTwoStringsWithSameValues_whenApacheCommonsEqualityMethods_thenEqualsFalseNotEqualsTrue() {
String first = new String("Hello!");
String second = new String("Hello!");
assertThat(ObjectUtils.compare(first, second)).isZero();
}
@Test
void givenTwoStringsWithConsecutiveValues_whenApacheCommonsCompareReversed_thenPositive() {
String first = new String("Hello!");
String second = new String("How are you?");
assertThat(ObjectUtils.compare(second, first)).isPositive();
}
@Test
void givenTwoStringsOneNull_whenApacheCommonsCompare_thenPositive() {
String first = new String("Hello!");
String second = null;
assertThat(ObjectUtils.compare(first, second, false)).isPositive();
}
}

View File

@ -0,0 +1,107 @@
package com.baeldung.comparing;
import org.junit.jupiter.api.Test;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
class ComparableInterfaceUnitTest {
@Test
void givenTwoConsecutiveStrings_whenCompareTo_thenNegative() {
String first = "Google";
String second = "Microsoft";
assertThat(first.compareTo(second)).isNegative();
}
@Test
void givenTwoEqualsStrings_whenCompareTo_thenZero() {
String first = "Google";
String second = "Google";
assertThat(first.compareTo(second)).isZero();
}
@Test
void givenTwoConsecutiveStrings_whenReversedCompareTo_thenPositive() {
String first = "Google";
String second = "Microsoft";
assertThat(second.compareTo(first)).isPositive();
}
@Test
void givenTwoPersonWithEqualsAndWrongComparableAndConsecutiveLastNames_whenCompareTo_thenNegative() {
PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson");
PersonWithEqualsAndWrongComparable joe = new PersonWithEqualsAndWrongComparable("Joe", "Portman");
assertThat(richard.compareTo(joe)).isNegative();
}
@Test
void givenTwoPersonWithEqualsAndWrongComparableAndSameLastNames_whenReversedCompareTo_thenZero() {
PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson");
PersonWithEqualsAndWrongComparable mike = new PersonWithEqualsAndWrongComparable("Mike", "Jefferson");
assertThat(richard.compareTo(mike)).isZero();
}
@Test
void givenTwoPersonWithEqualsAndWrongComparableAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() {
PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson");
PersonWithEqualsAndWrongComparable joe = new PersonWithEqualsAndWrongComparable("Joe", "Portman");
assertThat(joe.compareTo(richard)).isPositive();
}
@Test
void givenTwoPersonWithEqualsAndWrongComparableAndSameLastNames_whenSortedSet_thenProblem() {
PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson");
PersonWithEqualsAndWrongComparable mike = new PersonWithEqualsAndWrongComparable("Mike", "Jefferson");
SortedSet<PersonWithEqualsAndWrongComparable> people = new TreeSet<>();
people.add(richard);
people.add(mike);
assertThat(people).containsExactly(richard);
}
@Test
void givenTwoPersonWithEqualsAndComparableAndConsecutiveLastNames_whenCompareTo_thenNegative() {
PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson");
PersonWithEqualsAndComparable joe = new PersonWithEqualsAndComparable("Joe", "Portman");
assertThat(richard.compareTo(joe)).isNegative();
}
@Test
void givenTwoPersonWithEqualsAndComparableAndSameLastNames_whenReversedCompareTo_thenZero() {
PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson");
PersonWithEqualsAndComparable mike = new PersonWithEqualsAndComparable("Mike", "Jefferson");
assertThat(richard.compareTo(mike)).isPositive();
}
@Test
void givenTwoPersonWithEqualsAndComparableAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() {
PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson");
PersonWithEqualsAndComparable joe = new PersonWithEqualsAndComparable("Joe", "Portman");
assertThat(joe.compareTo(richard)).isPositive();
}
@Test
void givenTwoPersonWithEqualsAndComparableAndSameLastNames_whenSortedSet_thenProblem() {
PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson");
PersonWithEqualsAndComparable mike = new PersonWithEqualsAndComparable("Mike", "Jefferson");
SortedSet<PersonWithEqualsAndComparable> people = new TreeSet<>();
people.add(richard);
people.add(mike);
assertThat(people).containsExactly(mike, richard);
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.comparing;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
class ComparatorInterfaceUnitTest {
@Test
void givenListOfTwoPersonWithEqualsAndComparatorByFirstName_whenSort_thenSortedByFirstNames() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals allan = new PersonWithEquals("Allan", "Dale");
List<PersonWithEquals> people = new ArrayList<>();
people.add(joe);
people.add(allan);
Comparator<PersonWithEquals> compareByFirstNames = new Comparator<PersonWithEquals>() {
@Override
public int compare(PersonWithEquals o1, PersonWithEquals o2) {
return o1.firstName().compareTo(o2.firstName());
}
};
people.sort(compareByFirstNames);
assertThat(people).containsExactly(allan, joe);
}
@Test
void givenListOfTwoPersonWithEqualsAndComparatorByFirstNameFunctionalStyle_whenSort_thenSortedByFirstNames() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals allan = new PersonWithEquals("Allan", "Dale");
List<PersonWithEquals> people = new ArrayList<>();
people.add(joe);
people.add(allan);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::firstName);
people.sort(compareByFirstNames);
assertThat(people).containsExactly(allan, joe);
}
@Test
void givenTwoPersonWithEqualsAndComparableUsingComparatorAndConsecutiveLastNames_whenCompareTo_thenNegative() {
PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson");
PersonWithEqualsAndComparableUsingComparator joe = new PersonWithEqualsAndComparableUsingComparator("Joe", "Portman");
assertThat(richard.compareTo(joe)).isNegative();
}
@Test
void givenTwoPersonWithEqualsAndComparableUsingComparatorAndSameLastNames_whenReversedCompareTo_thenZero() {
PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson");
PersonWithEqualsAndComparableUsingComparator mike = new PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson");
assertThat(richard.compareTo(mike)).isPositive();
}
@Test
void givenTwoPersonWithEqualsAndComparableUsingComparatorAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() {
PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson");
PersonWithEqualsAndComparableUsingComparator joe = new PersonWithEqualsAndComparableUsingComparator("Joe", "Portman");
assertThat(joe.compareTo(richard)).isPositive();
}
@Test
void givenTwoPersonWithEqualsAndComparableUsingComparatorAndSameLastNames_whenSortedSet_thenProblem() {
PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson");
PersonWithEqualsAndComparableUsingComparator mike = new PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson");
SortedSet<PersonWithEqualsAndComparableUsingComparator> people = new TreeSet<>();
people.add(richard);
people.add(mike);
assertThat(people).containsExactly(mike, richard);
}
}

View File

@ -0,0 +1,116 @@
package com.baeldung.comparing;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class EqualityOperatorUnitTest {
@Test
void givenTwoIntsWithSameValues_whenEqualityOperators_thenConsideredSame() {
int a = 1;
int b = 1;
assertThat(a == b).isTrue();
assertThat(a != b).isFalse();
}
@Test
void givenTwoIntsWithDifferentValues_whenEqualityOperators_thenNotConsideredSame() {
int a = 1;
int b = 2;
assertThat(a == b).isFalse();
assertThat(a != b).isTrue();
}
@Test
void givenTwoIntsWithSameValuesOneWrapped_whenEqualityOperators_thenConsideredSame() {
int a = 1;
Integer b = new Integer(1);
assertThat(a == b).isTrue();
assertThat(a != b).isFalse();
}
@Test
void givenTwoIntsWithDifferentValuesOneWrapped_whenEqualityOperators_thenNotConsideredSame() {
int a = 1;
Integer b = new Integer(2);
assertThat(a == b).isFalse();
assertThat(a != b).isTrue();
}
@Test
void givenTwoIntegersWithSameValues_whenEqualityOperators_thenNotConsideredSame() {
Integer a = new Integer(1);
Integer b = new Integer(1);
assertThat(a == b).isFalse();
assertThat(a != b).isTrue();
}
@Test
void givenTwoIntegersWithDifferentValues_whenEqualityOperators_thenNotConsideredSame() {
Integer a = new Integer(1);
Integer b = new Integer(2);
assertThat(a == b).isFalse();
assertThat(a != b).isTrue();
}
@Test
void givenTwoIntegersWithSameReference_whenEqualityOperators_thenConsideredSame() {
Integer a = new Integer(1);
Integer b = a;
assertThat(a == b).isTrue();
assertThat(a != b).isFalse();
}
@Test
void givenTwoIntegersFromValueOfWithSameValues_whenEqualityOperators_thenConsideredSame() {
Integer a = Integer.valueOf(1);
Integer b = Integer.valueOf(1);
assertThat(a == b).isTrue();
assertThat(a != b).isFalse();
}
@Test
void givenTwoStringsWithSameValues_whenEqualityOperators_thenNotConsideredSame() {
String a = new String("Hello!");
String b = new String("Hello!");
assertThat(a == b).isFalse();
assertThat(a != b).isTrue();
}
@Test
void givenTwoStringsFromLiteralsWithSameValues_whenEqualityOperators_thenConsideredSame() {
String a = "Hello!";
String b = "Hello!";
assertThat(a == b).isTrue();
assertThat(a != b).isFalse();
}
@Test
void givenTwoNullObjects_whenEqualityOperators_thenConsideredSame() {
Object a = null;
Object b = null;
assertThat(a == b).isTrue();
assertThat(a != b).isFalse();
}
@Test
void givenTwoObjectsOneNull_whenEqualityOperators_thenNotConsideredSame() {
Object a = null;
Object b = "Hello!";
assertThat(a == b).isFalse();
assertThat(a != b).isTrue();
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.comparing;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class EqualsMethodUnitTest {
@Test
void givenTwoIntegersWithSameValue_whenEquals_thenTrue() {
Integer a = new Integer(1);
Integer b = new Integer(1);
assertThat(a.equals(b)).isTrue();
}
@Test
void givenTwoStringsWithSameValue_whenEquals_thenTrue() {
String a = new String("Hello!");
String b = new String("Hello!");
assertThat(a.equals(b)).isTrue();
}
@Test
void givenTwoStringsWithDifferentValue_whenEquals_thenFalse() {
String a = new String("Hello!");
String b = new String("Hello World!");
assertThat(a.equals(b)).isFalse();
}
@Test
void givenTwoObjectsFirstNull_whenEquals_thenNullPointerExceptionThrown() {
Object a = null;
Object b = new String("Hello!");
assertThrows(NullPointerException.class, () -> a.equals(b));
}
@Test
void givenTwoObjectsSecondNull_whenEquals_thenFalse() {
Object a = new String("Hello!");
Object b = null;
assertThat(a.equals(b)).isFalse();
}
@Test
void givenTwoPersonWithoutEqualsWithSameNames_whenEquals_thenFalse() {
PersonWithoutEquals joe = new PersonWithoutEquals("Joe", "Portman");
PersonWithoutEquals joeAgain = new PersonWithoutEquals("Joe", "Portman");
assertThat(joe.equals(joeAgain)).isFalse();
}
@Test
void givenTwoPersonWithEqualsWithSameNames_whenEquals_thenTrue() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals joeAgain = new PersonWithEquals("Joe", "Portman");
assertThat(joe.equals(joeAgain)).isTrue();
}
@Test
void givenTwoPersonWittEqualsWithDifferentNames_whenEquals_thenFalse() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals natalie = new PersonWithEquals("Natalie", "Portman");
assertThat(joe.equals(natalie)).isFalse();
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.comparing;
import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import com.google.common.primitives.Ints;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class GuavaUnitTest {
@Nested
class ObjectsEqualMethod {
@Test
void givenTwoStringsWithSameValues_whenObjectsEqualMethods_thenTrue() {
String a = new String("Hello!");
String b = new String("Hello!");
assertThat(Objects.equal(a, b)).isTrue();
}
@Test
void givenTwoStringsWithDifferentValues_whenObjectsEqualMethods_thenFalse() {
String a = new String("Hello!");
String b = new String("Hello World!");
assertThat(Objects.equal(a, b)).isFalse();
}
}
@Nested
class ComparisonMethods {
@Test
void givenTwoIntsWithConsecutiveValues_whenIntsCompareMethods_thenNegative() {
int first = 1;
int second = 2;
assertThat(Ints.compare(first, second)).isNegative();
}
@Test
void givenTwoIntsWithSameValues_whenIntsCompareMethods_thenZero() {
int first = 1;
int second = 1;
assertThat(Ints.compare(first, second)).isZero();
}
@Test
void givenTwoIntsWithConsecutiveValues_whenIntsCompareMethodsReversed_thenNegative() {
int first = 1;
int second = 2;
assertThat(Ints.compare(second, first)).isPositive();
}
}
@Nested
class ComparisonChainClass {
@Test
void givenTwoPersonWithEquals_whenComparisonChainByLastNameThenFirstName_thenSortedJoeFirstAndNatalieSecond() {
PersonWithEquals natalie = new PersonWithEquals("Natalie", "Portman");
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
int comparisonResult = ComparisonChain.start()
.compare(natalie.lastName(), joe.lastName())
.compare(natalie.firstName(), joe.firstName())
.result();
assertThat(comparisonResult).isPositive();
}
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.comparing;
import org.junit.jupiter.api.Test;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
class ObjectsEqualsStaticMethodUnitTest {
@Test
void givenTwoPersonWithEqualsWithSameNames_whenObjectsEquals_thenTrue() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals joeAgain = new PersonWithEquals("Joe", "Portman");
assertThat(Objects.equals(joe, joeAgain)).isTrue();
}
@Test
void givenTwoPersonWithEqualsWithDifferentNames_whenObjectsEquals_thenFalse() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals natalie = new PersonWithEquals("Natalie", "Portman");
assertThat(Objects.equals(joe, natalie)).isFalse();
}
@Test
void givenTwoPersonWithEqualsFirstNull_whenObjectsEquals_thenFalse() {
PersonWithEquals nobody = null;
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
assertThat(Objects.equals(nobody, joe)).isFalse();
}
@Test
void givenTwoObjectsSecondtNull_whenObjectsEquals_thenFalse() {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
PersonWithEquals nobody = null;
assertThat(Objects.equals(joe, nobody)).isFalse();
}
@Test
void givenTwoObjectsNull_whenObjectsEquals_thenTrue() {
PersonWithEquals nobody = null;
PersonWithEquals nobodyAgain = null;
assertThat(Objects.equals(nobody, nobodyAgain)).isTrue();
}
}

View File

@ -1,4 +0,0 @@
target/
.idea/
bin/
*.iml

View File

@ -1,18 +0,0 @@
## Core Java Lang OOP (Part 2)
This module contains articles about Object-oriented programming (OOP) in Java
### Relevant Articles:
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](https://www.baeldung.com/java-inheritance-composition)
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Static and Default Methods in Interfaces in Java](https://www.baeldung.com/java-static-default-methods)
- [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
- [[<-- Prev]](/core-java-modules/core-java-lang-oop)[[More -->]](/core-java-modules/core-java-lang-oop-3)

View File

@ -1,51 +0,0 @@
<?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-lang-oop-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
<version>${equalsverifier.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-oop-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<equalsverifier.version>3.0.3</equalsverifier.version>
</properties>
</project>

View File

@ -1,16 +0,0 @@
## Core Java Lang OOP (Part 3)
This module contains articles about Object-oriented programming (OOP) in Java
### Relevant Articles:
- [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Access Modifiers in Java](https://www.baeldung.com/java-access-modifiers)
- [Guide to the super Java Keyword](https://www.baeldung.com/java-super)
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
- [Java public Access Modifier](https://www.baeldung.com/java-public-keyword)
- [Composition, Aggregation, and Association in Java](https://www.baeldung.com/java-composition-aggregation-association)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2)[[More -->]](/core-java-modules/core-java-lang-oop-4)

View File

@ -1,60 +0,0 @@
<?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-lang-oop-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-oop-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -1,9 +0,0 @@
## Core Java Lang OOP (Part 4)
This module contains articles about Object-oriented programming (OOP) in Java
### Relevant Articles:
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Methods in Java](https://www.baeldung.com/java-methods)
- [Java private Access Modifier](https://www.baeldung.com/java-private-keyword)
- [[<-- Prev]](/core-java-modules/core-java-lang-oop-3)

View File

@ -1,60 +0,0 @@
<?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-lang-oop-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-oop-4</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -0,0 +1,8 @@
## Core Java Lang OOP - Constructors
This module contains article about constructors in Java
### Relevant Articles:
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor)
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)

View File

@ -0,0 +1,28 @@
<?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">
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-oop-constructors</artifactId>
<name>core-java-lang-oop-constructors</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -6,7 +6,7 @@ class BankAccount {
String name;
LocalDateTime opened;
double balance;
@Override
public String toString() {
return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
@ -47,14 +47,13 @@ class BankAccountCopyConstructor extends BankAccount {
this.opened = opened;
this.balance = balance;
}
public BankAccountCopyConstructor(BankAccount other) {
this.name = other.name;
this.opened = LocalDateTime.now();
this.balance = 0.0f;
}
}
class BankAccountChainedConstructors extends BankAccount {
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
this.name = name;
@ -65,4 +64,4 @@ class BankAccountChainedConstructors extends BankAccount {
public BankAccountChainedConstructors(String name) {
this(name, LocalDateTime.now(), 0.0f);
}
}
}

View File

@ -1,20 +1,19 @@
package com.baeldung.constructors;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class ConstructorUnitTest {
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
@Test
public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount();
assertThatThrownBy(() -> {
Assertions.assertThatThrownBy(() -> {
account.toString();
}).isInstanceOf(Exception.class);
}
@ -22,7 +21,7 @@ public class ConstructorUnitTest {
@Test
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
assertThatCode(() -> {
Assertions.assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@ -33,7 +32,7 @@ public class ConstructorUnitTest {
BankAccountParameterizedConstructor account =
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
assertThatCode(() -> {
Assertions.assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}

View File

@ -0,0 +1,8 @@
## Core Java Lang OOP - Generics
This module contains articles about generics in Java
### Relevant Articles:
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure)
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)

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">
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-oop-generics</artifactId>
<name>core-java-lang-oop-generics</name>
<packaging>jar</packaging>
</project>

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