Revert "BAEL-4134"

This commit is contained in:
Loredana Crusoveanu
2020-07-07 14:18:10 +03:00
committed by GitHub
parent dffa1f64e6
commit 485b4e3e99
2477 changed files with 9477 additions and 547819 deletions

View File

@@ -9,3 +9,4 @@ This module contains articles about Java 14.
- [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)
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)

View File

@@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-8-datetime-2</artifactId>
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@@ -5,7 +5,7 @@ This module contains articles about the improvements to core Java features intro
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [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)

View File

@@ -64,7 +64,7 @@
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>

View File

@@ -16,6 +16,11 @@
</parent>
<dependencies>
<dependency>
<groupId>io.reactivex.rxjava3</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -144,11 +149,12 @@
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<properties>
<rxjava.version>3.0.0</rxjava.version>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>

View File

@@ -0,0 +1,23 @@
package com.baeldung.java9.currentmethod;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CurrentExecutingMethodUnitTest {
@Test
public void givenJava9_whenWalkingTheStack_thenFindMethod() {
StackWalker walker = StackWalker.getInstance();
Optional<String> methodName = walker.walk(frames -> frames
.findFirst()
.map(StackWalker.StackFrame::getMethodName)
);
assertTrue(methodName.isPresent());
assertEquals("givenJava9_whenWalkingTheStack_thenFindMethod", methodName.get());
}
}

View File

@@ -0,0 +1,71 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class FlowApiLiveVideo {
static class VideoPlayer implements Flow.Subscriber<VideoFrame> {
Flow.Subscription subscription = null;
private long consumerDelay = 30;
public VideoPlayer(long consumerDelay) {
this.consumerDelay = consumerDelay;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(VideoFrame item) {
try {
Thread.sleep(consumerDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
static class VideoStreamServer extends SubmissionPublisher<VideoFrame> {
ScheduledExecutorService executor = null;
public VideoStreamServer(int bufferSize) {
super(Executors.newSingleThreadExecutor(), bufferSize);
executor = Executors.newScheduledThreadPool(1);
}
void startStreaming(long produceDelay, Runnable onDrop) {
AtomicLong frameNumber = new AtomicLong();
executor.scheduleWithFixedDelay(() -> {
offer(new VideoFrame(frameNumber.getAndIncrement()), (subscriber, videoFrame) -> {
subscriber.onError(new RuntimeException("Frame#" + videoFrame.getNumber() + " dropped because of back pressure"));
onDrop.run();
return true;
});
}, 0, produceDelay, TimeUnit.MILLISECONDS);
}
}
public static void streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError){
FlowApiLiveVideo.VideoStreamServer streamServer = new FlowApiLiveVideo.VideoStreamServer(bufferSize);
streamServer.subscribe(new FlowApiLiveVideo.VideoPlayer(consumeDelay));
streamServer.startStreaming(produceDelay, onError);
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import static org.awaitility.Awaitility.await;
public class LiveVideoFlowVsRxUnitTest {
private final static long SLOW_CONSUMER_DELAY = 30;
private final static long FAST_CONSUMER_DELAY = 1;
private final static long PRODUCER_DELAY = 1;
private final static int BUFFER_SIZE = 10;
private final static long AWAIT = 1000;
@Test
public void givenSlowVideoPlayer_whenSubscribedToFlowApiLiveVideo_thenExpectErrorOnBackPressure() {
AtomicLong errors = new AtomicLong();
FlowApiLiveVideo.streamLiveVideo(PRODUCER_DELAY, SLOW_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
await()
.atMost(AWAIT, TimeUnit.MILLISECONDS)
.untilAsserted(() -> Assertions.assertTrue(errors.get() > 0));
}
@Test
public void givenFastVideoPlayer_whenSubscribedToFlowApiLiveVideo_thenExpectNoErrorOnBackPressure() throws InterruptedException {
AtomicLong errors = new AtomicLong();
FlowApiLiveVideo.streamLiveVideo(PRODUCER_DELAY, FAST_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
Thread.sleep(AWAIT);
Assertions.assertEquals(0, errors.get());
}
@Test
public void givenSlowVideoPlayer_whenSubscribedToRxJavaLiveVideo_thenExpectErrorOnBackPressure() {
AtomicLong errors = new AtomicLong();
RxJavaLiveVideo.streamLiveVideo(PRODUCER_DELAY, SLOW_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
await()
.atMost(AWAIT, TimeUnit.MILLISECONDS)
.untilAsserted(() -> Assertions.assertTrue(errors.get() > 0));
}
@Test
public void givenFastVideoPlayer_whenSubscribedToRxJavaLiveVideo_thenExpectNoErrorOnBackPressure() throws InterruptedException {
AtomicLong errors = new AtomicLong();
RxJavaLiveVideo.streamLiveVideo(PRODUCER_DELAY, FAST_CONSUMER_DELAY, BUFFER_SIZE, errors::incrementAndGet);
Thread.sleep(AWAIT);
Assertions.assertEquals(0, errors.get());
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class RxJavaLiveVideo {
public static Disposable streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError) {
return Flowable
.fromStream(Stream.iterate(new VideoFrame(0), videoFrame -> {
sleep(produceDelay);
return new VideoFrame(videoFrame.getNumber() + 1);
}))
.subscribeOn(Schedulers.from(Executors.newSingleThreadScheduledExecutor()), true)
.onBackpressureBuffer(bufferSize, null, BackpressureOverflowStrategy.ERROR)
.observeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
.subscribe(item -> {
sleep(consumeDelay);
}, throwable -> {
onError.run();
});
}
private static void sleep(long i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.java9.streams.reactive.flowvsrx;
class VideoFrame {
private long number;
public VideoFrame(long number) {
this.number = number;
}
public long getNumber() {
return number;
}
}

View File

@@ -64,7 +64,7 @@
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>

View File

@@ -0,0 +1,87 @@
package com.baeldung.java9.inputstream.outputstream;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertEquals;
import java.io.*;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.google.common.io.ByteStreams;
public class InputStreamToOutputStreamUnitTest {
/**
* Reads all bytes from an input stream and writes them to an output stream.
* @param source - input stream to copy data from
* @param target - output stream to copy data too
*/
void copy(InputStream source, OutputStream target) throws IOException {
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
target.write(buf, 0, length);
}
}
@Test
public void givenUsingJavaEight_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingJavaEight_whenCopyingLongInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = randomAlphabetic(20480);
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingJavaNine_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
inputStream.transferTo(targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingGuava_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
ByteStreams.copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
@Test
public void givenUsingCommonsIO_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException {
String initialString = "Hello World!";
try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes());
ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) {
IOUtils.copy(inputStream, targetStream);
assertEquals(initialString, new String(targetStream.toByteArray()));
}
}
}

View File

@@ -4,4 +4,5 @@ This module contains complete guides about arrays in Java
### Relevant Articles:
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is [Ljava.lang.Object;?]](https://www.baeldung.com/java-tostring-array)

View File

@@ -13,32 +13,6 @@
<name>core-java-arrays-operations-basic</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@@ -66,6 +40,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>

View File

@@ -14,32 +14,6 @@
<name>core-java-arrays-sorting</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Utilities -->
<dependency>
@@ -74,6 +48,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>

View File

@@ -19,31 +19,31 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId>
<version>0.2</version>
<version>${threadweaver.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.tempus-fugit</groupId>
<artifactId>tempus-fugit</artifactId>
<version>1.1</version>
<version>${tempus-fugit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.multithreadedtc</groupId>
<artifactId>multithreadedtc</artifactId>
<version>1.01</version>
<version>${multithreadedtc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jcstress</groupId>
<artifactId>jcstress-core</artifactId>
<version>0.5</version>
<version>${jcstress-core.version}</version>
</dependency>
</dependencies>
@@ -63,8 +63,8 @@
<version>3.1</version>
<configuration>
<compilerVersion>${javac.target}</compilerVersion>
<source>${javac.target}</source>
<target>${javac.target}</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
@@ -99,7 +99,11 @@
</build>
<properties>
<javac.target>1.8</javac.target>
<junit.version>4.13</junit.version>
<threadweaver.version>0.2</threadweaver.version>
<tempus-fugit.version>1.1</tempus-fugit.version>
<multithreadedtc.version>1.01</multithreadedtc.version>
<jcstress-core.version>0.5</jcstress-core.version>
</properties>
</project>

View File

@@ -13,4 +13,6 @@ This module contains articles about advanced topics about multithreading with co
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@@ -0,0 +1,16 @@
package com.baeldung.thisescape;
public class ImplicitEscape {
public ImplicitEscape() {
Thread t = new Thread() {
@Override
public void run() {
System.out.println("Started...");
}
};
t.start();
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.thisescape;
public class LoggerRunnable implements Runnable {
public LoggerRunnable() {
Thread thread = new Thread(this); // this escapes
thread.start();
}
@Override
public void run() {
System.out.println("Started...");
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.thisescape;
public class SafePublication implements Runnable {
private final Thread thread;
public SafePublication() {
thread = new Thread(this);
}
@Override
public void run() {
System.out.println("Started...");
}
public void start() {
thread.start();
}
public static void main(String[] args) {
SafePublication publication = new SafePublication();
publication.start();
}
}

View File

@@ -34,4 +34,20 @@ public class BaeldungSychronizedBlockUnitTest {
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
}
@Test
public void givenHoldingTheLock_whenReentrant_thenCanAcquireItAgain() {
Object lock = new Object();
synchronized (lock) {
System.out.println("First time acquiring it");
synchronized (lock) {
System.out.println("Entering again");
synchronized (lock) {
System.out.println("And again");
}
}
}
}
}

View File

@@ -13,3 +13,4 @@ This module contains articles about concurrent Java collections
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)

View File

@@ -1,41 +0,0 @@
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

@@ -1,30 +0,0 @@
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,64 @@
package com.baeldung.weeknumber;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.WeekFields;
import java.util.Calendar;
import java.util.Locale;
import org.junit.Test;
public class GetWeekNumberUnitTest {
@Test
public void givenDateUsingFieldsAndLocaleItaly_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
Calendar calendar = Calendar.getInstance(Locale.ITALY);
calendar.set(2020, 10, 22);
assertEquals(47, calendar.get(Calendar.WEEK_OF_YEAR));
}
@Test
public void givenDateUsingFieldsAndLocaleCanada_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
Calendar calendar = Calendar.getInstance(Locale.CANADA);
calendar.set(2020, 10, 22);
assertEquals(48, calendar.get(Calendar.WEEK_OF_YEAR));
}
@Test
public void givenDateUsingFieldsAndLocaleItaly_whenChangingWeekCalcSettings_thenWeekIsReturnedCorrectly() {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.setMinimalDaysInFirstWeek(4);
calendar.set(2020, 2, 22);
assertEquals(13, calendar.get(Calendar.WEEK_OF_YEAR));
}
@Test
public void givenDateUsingChronoFields_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
LocalDate date = LocalDate.of(2020, 3, 22);
assertEquals(12, date.get(ChronoField.ALIGNED_WEEK_OF_YEAR));
}
@Test
public void givenDateUsingFieldsWithLocaleItaly_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
LocalDate date = LocalDate.of(2020, 3, 22);
assertEquals(12, date.get(WeekFields.of(Locale.ITALY)
.weekOfYear()));
}
@Test
public void givenDateUsingFieldsWithLocaleCanada_whenGetWeekNumber_thenWeekIsReturnedCorrectly() {
LocalDate date = LocalDate.of(2020, 3, 22);
assertEquals(13, date.get(WeekFields.of(Locale.CANADA)
.weekOfYear()));
}
}

View File

@@ -1,46 +0,0 @@
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

@@ -1,49 +0,0 @@
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

@@ -0,0 +1,55 @@
package com.baeldung.exceptionininitializererror;
import org.junit.Test;
import java.lang.reflect.Constructor;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExceptionInInitializerErrorUnitTest {
@Test
public void givenStaticVar_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
assertThatThrownBy(StaticVar::new)
.isInstanceOf(ExceptionInInitializerError.class)
.hasCauseInstanceOf(RuntimeException.class);
}
@Test
public void givenStaticBlock_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
assertThatThrownBy(StaticBlock::new)
.isInstanceOf(ExceptionInInitializerError.class)
.hasCauseInstanceOf(ArithmeticException.class);
}
private static class CheckedConvention {
private static Constructor<?> constructor;
static {
try {
constructor = CheckedConvention.class.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
throw new ExceptionInInitializerError(e);
}
}
}
private static class StaticVar {
private static int state = initializeState();
private static int initializeState() {
throw new RuntimeException();
}
}
private static class StaticBlock {
private static int state;
static {
state = 42 / 0;
}
}
}

View File

@@ -0,0 +1,87 @@
package com.baeldung.exceptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
public class TooManyOpenFilesExceptionLiveTest {
//This is not a regular UnitTest due to the fact that it depends on System.gc() to work properly.
//As we have to force the JVM to run out of file descriptors, any other tests that uses IO may fail.
//This may indirectly affect other tests that are part of the Jenkins Build.
private File tempFile;
@BeforeEach
public void setUp() throws IOException {
tempFile = File.createTempFile("testForException", "tmp");
}
@AfterEach
public void tearDown() {
//Enforce a GC to clear unreferenced files and release descriptors
System.gc();
tempFile.delete();
}
@Test
public void whenNotClosingResoures_thenIOExceptionShouldBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
FileInputStream leakyHandle = new FileInputStream(tempFile);
}
Assertions.fail("Method Should Have Failed");
} catch (IOException e) {
assertTrue(e.getMessage().toLowerCase().contains("too many open files"));
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
@Test
public void whenClosingResoures_thenIOExceptionShouldNotBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
FileInputStream nonLeakyHandle = null;
try {
nonLeakyHandle = new FileInputStream(tempFile);
} finally {
if (nonLeakyHandle != null) {
nonLeakyHandle.close();
}
}
}
} catch (IOException e) {
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
Assertions.fail("Method Should Not Have Failed");
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
@Test
public void whenUsingTryWithResoures_thenIOExceptionShouldNotBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
try (FileInputStream nonLeakyHandle = new FileInputStream(tempFile)) {
//Do something with the file
}
}
} catch (IOException e) {
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
Assertions.fail("Method Should Not Have Failed");
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
}

View File

@@ -50,7 +50,7 @@
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.26.3</version>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
@@ -80,6 +80,7 @@
<properties>
<assertj.version>3.6.1</assertj.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<wiremock.version>2.26.3</wiremock.version>
</properties>
</project>

View File

@@ -24,7 +24,7 @@
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
<version>${json.version}</version>
</dependency>
</dependencies>
@@ -38,4 +38,8 @@
</resources>
</build>
<properties>
<json.version>20200518</json.version>
</properties>
</project>

View File

@@ -72,7 +72,7 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final Iterable<File> files = com.google.common.io.Files.fileTraverser().breadthFirst(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
assertEquals(EXPECTED_SIZE, size);

View File

@@ -0,0 +1,5 @@
## Core Java JVM Cookbooks and Examples
This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:

View File

@@ -0,0 +1,43 @@
<?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-jvm-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-jvm-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties>
</project>

View File

@@ -0,0 +1,13 @@
package com.baeldung.arraylength;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
public class ArrayLengthUnitTest {
@Test
public void printingTheArrayLength() {
int[] ints = new int[42];
System.out.println(ClassLayout.parseInstance(ints).toPrintable());
}
}

View File

@@ -0,0 +1,108 @@
package com.baeldung.memlayout;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
import sun.misc.Contended;
public class MemoryLayoutUnitTest {
private volatile Object consumer;
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void simpleMemoryLayout() {
System.out.println(ClassLayout.parseClass(SimpleInt.class).toPrintable());
}
@Test
public void identityHashCodeMemoryLayout() {
SimpleInt instance = new SimpleInt();
System.out.println(ClassLayout.parseInstance(instance).toPrintable());
System.out.println("The identity hash code is " + System.identityHashCode(instance));
System.out.println(ClassLayout.parseInstance(instance).toPrintable());
}
@Test
public void alignmentMemoryLayout() {
System.out.println(ClassLayout.parseClass(SimpleLong.class).toPrintable());
}
@Test
public void fieldPackingMemoryLayout() {
System.out.println(ClassLayout.parseClass(FieldsArrangement.class).toPrintable());
}
@Test
public void monitorLockMemoryLayout() {
Lock lock = new Lock();
System.out.println(ClassLayout.parseInstance(lock).toPrintable());
synchronized (lock) {
System.out.println(ClassLayout.parseInstance(lock).toPrintable());
}
}
@Test
public void ageAndTenuringMemoryLayout() {
Object instance = new Object();
long lastAddr = VM.current().addressOf(instance);
ClassLayout layout = ClassLayout.parseInstance(instance);
for (int i = 0; i < 10_000; i++) {
long currentAddr = VM.current().addressOf(instance);
if (currentAddr != lastAddr) {
System.out.println(layout.toPrintable());
}
for (int j = 0; j < 10_000; j++) {
consumer = new Object();
}
lastAddr = currentAddr;
}
}
@Test
public void contendedMemoryLayout() {
System.out.println(ClassLayout.parseClass(Isolated.class).toPrintable());
}
@Test
public void arrayMemoryLayout() {
boolean[] booleans = new boolean[3];
System.out.println(ClassLayout.parseInstance(booleans).toPrintable());
}
private static class SimpleInt {
private int state;
}
private static class SimpleLong {
private long state;
}
private static class FieldsArrangement {
private boolean first;
private char second;
private double third;
private int fourth;
private boolean fifth;
}
private static class Lock {}
private static class Isolated {
@Contended
private int i;
@Contended
private long l;
}
}

View File

@@ -13,3 +13,6 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Runtime.getRuntime().halt() vs System.exit() in Java](https://www.baeldung.com/java-runtime-halt-vs-system-exit)
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
- [What Causes java.lang.OutOfMemoryError: unable to create new native thread](https://www.baeldung.com/java-outofmemoryerror-unable-to-create-new-native-thread)
- [View Bytecode of a Class File in Java](https://www.baeldung.com/java-class-view-bytecode)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)

View File

@@ -65,7 +65,12 @@
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
<version>${bcel.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
</dependencies>
<properties>
@@ -74,6 +79,7 @@
<javaassist.version>3.27.0-GA</javaassist.version>
<esapi.version>2.1.0.1</esapi.version>
<sun.tools.version>1.8.0</sun.tools.version>
<jol-core.version>0.10</jol-core.version>
<asm.version>8.0.1</asm.version>
<bcel.version>6.5.0</bcel.version>
</properties>

View File

@@ -0,0 +1,25 @@
package com.baeldung.boolsize;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
public class BooleanSizeUnitTest {
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void printingTheBoolWrapper() {
System.out.println(ClassLayout.parseClass(BooleanWrapper.class).toPrintable());
}
@Test
public void printingTheBoolArray() {
boolean[] value = new boolean[3];
System.out.println(ClassLayout.parseInstance(value).toPrintable());
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.boolsize;
class BooleanWrapper {
private boolean value;
}

View File

@@ -11,4 +11,6 @@ This module contains articles about core features in the Java language
- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword)
- [The Java Headless Mode](https://www.baeldung.com/java-headless-mode)
- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values)
- [Comparing Objects in Java](https://www.baeldung.com/java-comparing-objects)
- [Casting int to Enum in Java](https://www.baeldung.com/java-cast-int-to-enum)
- [[<-- Prev]](/core-java-modules/core-java-lang)

View File

@@ -22,15 +22,15 @@ public class PersonWithEquals {
this.birthDate = birthDate;
}
public String firstName() {
public String getFirstName() {
return firstName;
}
public String lastName() {
public String getLastName() {
return lastName;
}
public LocalDate birthDate() {
public LocalDate getBirthDate() {
return birthDate;
}

View File

@@ -22,6 +22,18 @@ public class PersonWithEqualsAndComparable implements Comparable<PersonWithEqual
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@@ -23,15 +23,15 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
this.birthDate = birthDate;
}
public String firstName() {
public String getFirstName() {
return firstName;
}
public String lastName() {
public String getLastName() {
return lastName;
}
public LocalDate birthDate() {
public LocalDate getBirthDate() {
return birthDate;
}
@@ -52,9 +52,9 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
@Override
public int compareTo(PersonWithEqualsAndComparableUsingComparator o) {
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder()))
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::getLastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getFirstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getBirthDate, Comparator.nullsLast(Comparator.naturalOrder()))
.compare(this, o);
}
}

View File

@@ -22,6 +22,18 @@ public class PersonWithEqualsAndWrongComparable implements Comparable<PersonWith
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@@ -8,4 +8,12 @@ public class PersonWithoutEquals {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

View File

@@ -21,11 +21,10 @@ public enum PizzaStatus {
private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();
static {
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
timeToDeliveryToEnumValuesMapping.put(
pizzaStatuses[pizzaStatusIndex].getTimeToDelivery(),
pizzaStatuses[pizzaStatusIndex]
pizzaStatus.getTimeToDelivery(),
pizzaStatus
);
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public class IsoscelesTriangle extends Triangle {
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public interface Shape {
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public class Triangle implements Shape {
}

View File

@@ -20,7 +20,7 @@ class ComparatorInterfaceUnitTest {
Comparator<PersonWithEquals> compareByFirstNames = new Comparator<PersonWithEquals>() {
@Override
public int compare(PersonWithEquals o1, PersonWithEquals o2) {
return o1.firstName().compareTo(o2.firstName());
return o1.getFirstName().compareTo(o2.getFirstName());
}
};
people.sort(compareByFirstNames);
@@ -37,7 +37,7 @@ class ComparatorInterfaceUnitTest {
people.add(joe);
people.add(allan);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::firstName);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::getFirstName);
people.sort(compareByFirstNames);
assertThat(people).containsExactly(allan, joe);

View File

@@ -63,8 +63,8 @@ class GuavaUnitTest {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
int comparisonResult = ComparisonChain.start()
.compare(natalie.lastName(), joe.lastName())
.compare(natalie.firstName(), joe.firstName())
.compare(natalie.getLastName(), joe.getLastName())
.compare(natalie.getFirstName(), joe.getFirstName())
.result();
assertThat(comparisonResult).isPositive();

View File

@@ -1,7 +1,12 @@
package com.baeldung.inttoenum;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public class IntToEnumUnitTest {
@@ -9,19 +14,33 @@ public class IntToEnumUnitTest {
@Test
public void whenIntToEnumUsingValuesMethod_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
PizzaStatus pizzaOrderedStatus = null;
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
if (pizzaStatuses[pizzaStatusIndex].getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatuses[pizzaStatusIndex];
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
if (pizzaStatus.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatus;
}
}
assertEquals(pizzaOrderedStatus, PizzaStatus.ORDERED);
assertThat(pizzaOrderedStatus).isEqualTo(PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingMap_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
assertEquals(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus), PizzaStatus.ORDERED);
assertThat(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus)).isEqualTo(PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingStream_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
Optional<PizzaStatus> pizzaStatus = Arrays.stream(PizzaStatus.values())
.filter(p -> p.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus)
.findFirst();
assertThat(pizzaStatus).hasValue(PizzaStatus.ORDERED);
}
}

View File

@@ -0,0 +1,67 @@
package com.baeldung.isinstancevsisassignablefrom;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IsInstanceIsAssignableFromUnitTest {
@Test
public void whenUsingIsInstanceProperly_desiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
Shape nonspecificShape = null;
assertTrue(Shape.class.isInstance(shape));
assertTrue(Shape.class.isInstance(triangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle2));
assertFalse(Shape.class.isInstance(nonspecificShape));
assertTrue(Triangle.class.isInstance(shape));
assertTrue(Triangle.class.isInstance(triangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle2));
assertFalse(IsoscelesTriangle.class.isInstance(shape));
assertFalse(IsoscelesTriangle.class.isInstance(triangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle2));
}
@Test
public void whenUsingIsAssignableFromProperly_desiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
assertFalse(shape.getClass().isAssignableFrom(Shape.class));
assertTrue(shape.getClass().isAssignableFrom(shape.getClass()));
assertTrue(shape.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(triangle.getClass().isAssignableFrom(Shape.class));
assertTrue(triangle.getClass().isAssignableFrom(shape.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
}
}

View File

@@ -6,7 +6,6 @@
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set)

View File

@@ -6,3 +6,4 @@ This module contains articles about generics in Java
- [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)
- [Super Type Tokens in Java Generics](https://www.baeldung.com/java-super-type-tokens)

View File

@@ -0,0 +1,8 @@
package com.baeldung.covariance;
public class IntegerProducer extends Producer {
@Override
public Integer produce(String input) {
return Integer.parseInt(input);
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.covariance;
public class Producer {
public Object produce(String input) {
Object result = input.toLowerCase();
return result;
}
}

View File

@@ -0,0 +1,49 @@
package com.baeldung.covariance;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CovariantProducersUnitTest {
@Test
public void whenInputIsArbitrary_thenProducerProducesString() {
String arbitraryInput = "just a random text";
Producer producer = new Producer();
Object objectOutput = producer.produce(arbitraryInput);
assertEquals(arbitraryInput, objectOutput);
assertEquals(String.class, objectOutput.getClass());
}
@Test
public void whenInputIsArbitrary_thenIntegerProducerFails() {
String arbitraryInput = "just a random text";
Producer producer = new IntegerProducer();
assertThrows(NumberFormatException.class, () -> producer.produce(arbitraryInput));
}
@Test
public void whenInputIsSupported_thenProducerCreatesInteger() {
String integerAsString = "42";
Producer producer = new IntegerProducer();
Object result = producer.produce(integerAsString);
assertEquals(Integer.class, result.getClass());
assertEquals(Integer.parseInt(integerAsString), result);
}
@Test
public void whenInputIsSupported_thenIntegerProducerCreatesIntegerWithoutCasting() {
String integerAsString = "42";
IntegerProducer producer = new IntegerProducer();
Integer result = producer.produce(integerAsString);
assertEquals(Integer.parseInt(integerAsString), result);
}
}

View File

@@ -12,3 +12,4 @@ This module contains articles about Java operators
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
- [Bitwise & vs Logical && Operators](https://www.baeldung.com/java-bitwise-vs-logical-and)
- [Finding an Objects Class in Java](https://www.baeldung.com/java-finding-class)

View File

@@ -0,0 +1,23 @@
package com.baeldung.macaddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetAllMacAddressesDemo {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
byte[] hardwareAddress = ni.getHardwareAddress();
if (hardwareAddress != null) {
String[] hexadecimalFormat = new String[hardwareAddress.length];
for (int i = 0; i < hardwareAddress.length; i++) {
hexadecimalFormat[i] = String.format("%02X", hardwareAddress[i]);
}
System.out.println(String.join("-", hexadecimalFormat));
}
}
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.macaddress;
import org.junit.Test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import static org.junit.Assert.assertEquals;
public class MacAddressUnitTest {
@Test
public void givenNetworkInterface_whenUsingLocalHost_thenGetMacAddress() throws UnknownHostException, SocketException {
InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
byte[] macAddress = ni.getHardwareAddress();
assertEquals(6, macAddress.length);
}
}

View File

@@ -29,7 +29,7 @@
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.15.0</version>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -44,4 +44,8 @@
</resources>
</build>
<properties>
<assertj-core.version>3.15.0</assertj-core.version>
</properties>
</project>

View File

@@ -0,0 +1,110 @@
package com.baeldung.regex.countmatches;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
/**
* Unit Test intended to count number of matches of a RegEx using Java 8 and 9.
*
* Java 9 is needed to run the commented out tests.
*/
public class CountMatchesUnitTest {
private static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile("([a-z0-9_.-]+)@([a-z0-9_.-]+[a-z])");
private static final String TEXT_CONTAINING_EMAIL_ADDRESSES = "You can contact me through: writer@baeldung.com, editor@baeldung.com and team@bealdung.com";
private static final String TEXT_CONTAINING_FIVE_EMAIL_ADDRESSES = "Valid emails are: me@gmail.com, you@baeldung.com, contact@hotmail.com, press@anysite.com and support@bealdung.com";
private static final String TEXT_CONTAINING_OVERLAP_EMAIL_ADDRESSES = "Try to contact us at team@baeldung.comeditor@baeldung.com, support@baeldung.com.";
@Test
public void givenContainingEmailString_whenJava8Match_thenCountMacthesFound() {
Matcher countEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_EMAIL_ADDRESSES);
int count = 0;
while (countEmailMatcher.find()) {
count++;
}
assertEquals(3, count);
}
@Test
public void givenContainingFiveEmailsString_whenJava8Match_thenCountMacthesFound() {
Matcher countFiveEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_FIVE_EMAIL_ADDRESSES);
int count = 0;
while (countFiveEmailsMatcher.find()) {
count++;
}
assertEquals(5, count);
}
@Test
public void givenStringWithoutEmails_whenJava8Match_thenCountMacthesNotFound() {
Matcher noEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher("Simple text without emails.");
int count = 0;
while (noEmailMatcher.find()) {
count++;
}
assertEquals(0, count);
}
@Test
public void givenStringWithOverlappingEmails_whenJava8Match_thenCountWrongMatches() {
Matcher countOverlappingEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_OVERLAP_EMAIL_ADDRESSES);
int count = 0;
while (countOverlappingEmailsMatcher.find()) {
count++;
}
assertNotEquals(3, count);
}
@Test
public void givenContainingEmailString_whenStartingInJava9Match_thenCountMacthesFound() {
// uncomment to try with Java 9
// Matcher countEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_EMAIL_ADDRESSES);
// long count = countEmailMatcher.results().count();
// assertEquals(3, count);
}
@Test
public void givenContainingFiveEmailsString_whenStartingInJava9Match_thenCountMacthesFound() {
// uncomment to try with Java 9
// Matcher countFiveEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_FIVE_EMAIL_ADDRESSES);
// long count = countFiveEmailsMatcher.results().count();
// assertEquals(5, count);
}
@Test
public void givenStringWithoutEmails_whenJava9Match_thenCountMacthesNotFound() {
// uncomment to try with Java 9
// Matcher noEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher("Simple text without emails.");
// long count = noEmailMatcher.results().count();
// assertEquals(0, count);
}
@Test
public void givenStringWithOverlappingEmails_whenJava9Match_thenCountWrongMatches() {
// uncomment to try with Java 9
// Matcher countOverlappingEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_OVERLAP_EMAIL_ADDRESSES);
// long count = countOverlappingEmailsMatcher.results().count();
// assertNotEquals(3, count);
}
}

View File

@@ -41,7 +41,7 @@
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
<version>${jaxb-api.version}</version>
</dependency>
@@ -54,6 +54,7 @@
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
</properties>
</project>

View File

@@ -13,4 +13,5 @@ This module contains articles about the Stream API in Java.
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
- More articles: [[next -->]](/../core-java-streams-2)
- [How to Find all Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
- More articles: [[next -->]](/../core-java-streams-2)

View File

@@ -17,6 +17,15 @@ public class StringToIntOrIntegerUnitTest {
assertThat(result).isEqualTo(42);
}
@Test
public void givenBinaryString_whenParsingInt_shouldConvertToInt() {
String givenString = "101010";
int result = Integer.parseInt(givenString, 2);
assertThat(result).isEqualTo(42);
}
@Test
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "42";
@@ -27,6 +36,15 @@ public class StringToIntOrIntegerUnitTest {
}
@Test
public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "101010";
Integer result = Integer.valueOf(givenString, 2);
assertThat(result).isEqualTo(new Integer(42));
}
@Test
public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
for (int i = -128; i <= 127; i++) {
String value = i + "";

View File

@@ -0,0 +1,15 @@
package com.baeldung.deserialization;
import java.io.IOException;
import java.io.Serializable;
public class DefaultSerial implements Serializable {
private String name;
public static void main(String[] args) throws IOException, ClassNotFoundException {
String digest = "rO0ABXNyACpjb20uYmFlbGR1bmcuZGVzZXJpY"
+ "WxpemF0aW9uLkRlZmF1bHRTZXJpYWx9iVz3Lz/mdAIAAHhw";
DefaultSerial instance = (DefaultSerial) DeserializationUtility.deSerializeObjectFromString(digest);
}
}

View File

@@ -80,6 +80,7 @@
<module>core-java-jndi</module>
<!-- <module>core-java-jpms</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<module>core-java-jvm</module>
<module>core-java-jvm-2</module>
<module>core-java-lambdas</module>
<module>core-java-lang</module>
@@ -133,18 +134,6 @@
<module>pre-jpms</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
@@ -162,6 +151,18 @@
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>