Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima 2022-08-08 13:34:28 -03:00 committed by GitHub
commit 2312eab3b9
247 changed files with 4059 additions and 524 deletions

View File

@ -5,4 +5,4 @@
- [Introduction to HexFormat in Java 17](https://www.baeldung.com/java-hexformat)
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)
- [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators)
- [Sealed Classes and Interfaces in Java 17](https://www.baeldung.com/java-sealed-classes-interfaces)
- [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces)

View File

@ -0,0 +1,48 @@
package com.baeldung.list.aslistvssingletonlist;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
class ArraysAsListVsSingletonListUnitTest {
@Test
void givenListFromArraysAsList_whenChangingStructureAndElement_thenGetExpectedResult() {
List<String> arraysAsList = Arrays.asList("ONE");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
() -> arraysAsList.add("TWO")
);
arraysAsList.set(0, "A brand new string");
assertThat(arraysAsList.get(0)).isEqualTo("A brand new string");
}
@Test
void givenSingletonList_whenChangingStructureAndElement_thenThrowException() {
List<String> singletonList = Collections.singletonList("ONE");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
() -> singletonList.add("TWO")
);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
() -> singletonList.set(0, "A brand new string")
);
}
@Test
void givenAnArray_whengetListByArraysAsList_thenTheListIsBackedByTheArray() {
String[] theArray = new String[] { "ONE", "TWO" };
List<String> theList = Arrays.asList(theArray);
//changing the list, the array is changed too
theList.set(0, "ONE [changed in list]");
assertThat(theArray[0]).isEqualTo("ONE [changed in list]");
//changing the array, the list is changed too
theArray[1] = "TWO [changed in array]";
assertThat(theList.get(1)).isEqualTo("TWO [changed in array]");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.list.replace;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class ReplaceUsingIndexInArrayListUnitTest {
private static final List<Integer> EXPECTED = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
@Test void givenArrayList_updateUsingSet() {
List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 7, 4, 5));
aList.set(2, 3);
assertThat(aList).isEqualTo(EXPECTED);
}
}

View File

@ -11,7 +11,6 @@ This module contains articles about advanced topics about multithreading with co
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](https://www.baeldung.com/java-fork-join)
- [Guide to ThreadLocalRandom in Java](https://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](https://www.baeldung.com/java-thread-join)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced)[[next -->]](/core-java-modules/core-java-concurrency-advanced-3)

View File

@ -0,0 +1,16 @@
package com.baeldung.atomicvsvolatile;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeAtomicCounter {
private final AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
}
public void increment() {
counter.incrementAndGet();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.atomicvsvolatile;
public class UnsafeCounter {
private int counter;
public int getValue() {
return counter;
}
public void increment() {
counter++;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.atomicvsvolatile;
public class UnsafeVolatileCounter {
private volatile int counter;
public int getValue() {
return counter;
}
public void increment() {
counter++;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.atomicvsvolatile;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
public class SafeAtomicCounterUnitTest {
private static final int INCREMENT_COUNTER = 1000;
private static final int TIMEOUT = 100;
private static final int POOL_SIZE = 3;
@Test
public void givenMultiThread_whenSafeAtomicCounterIncrement() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(POOL_SIZE);
SafeAtomicCounter safeCounter = new SafeAtomicCounter();
IntStream.range(0, INCREMENT_COUNTER).forEach(count -> service.submit(safeCounter::increment));
service.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS);
assertEquals(INCREMENT_COUNTER, safeCounter.getValue());
}
}

View File

@ -12,5 +12,4 @@ This module contains articles about advanced topics about multithreading with co
- [Guide to the Java Phaser](https://www.baeldung.com/java-phaser)
- [An Introduction to Atomic Variables in Java](https://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](https://www.baeldung.com/java-cyclic-barrier)
- [Guide to the Volatile Keyword in Java](https://www.baeldung.com/java-volatile)
- More Articles: [[next -->]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -5,10 +5,7 @@ This module contains articles about basic Java concurrency
### Relevant Articles:
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [wait and notify() Methods in Java](https://www.baeldung.com/java-wait-notify)
- [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep)
- [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized)
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)

View File

@ -3,8 +3,6 @@
This module contains articles about basic Java concurrency
### Relevant Articles:
- [Guide To CompletableFuture](https://www.baeldung.com/java-completablefuture)
- [A Guide to the Java ExecutorService](https://www.baeldung.com/java-executor-service-tutorial)
- [Guide to java.util.concurrent.Future](https://www.baeldung.com/java-future)
- [Overview of the java.util.concurrent](https://www.baeldung.com/java-util-concurrent)
- [Implementing a Runnable vs Extending a Thread](https://www.baeldung.com/java-runnable-vs-extending-thread)
@ -12,5 +10,4 @@ This module contains articles about basic Java concurrency
- [ExecutorService Waiting for Threads to Finish](https://www.baeldung.com/java-executor-wait-for-threads)
- [Runnable vs. Callable in Java](https://www.baeldung.com/java-runnable-callable)
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
- [[Next -->]](/core-java-modules/core-java-concurrency-basic-2)

View File

@ -0,0 +1,18 @@
### Mockito Articles that are also part of the e-book
This module contains articles about Java Concurrency that are also part of an Ebook.
## Relevant articles:
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
- [Thread's wait and notify() Methods in Java](https://www.baeldung.com/java-wait-notify)
- [The Thread.join() Method in Java](https://www.baeldung.com/java-thread-join)
- [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized)
- [Guide to the Volatile Keyword in Java](https://www.baeldung.com/java-volatile)
- [A Guide to the Java ExecutorService](https://www.baeldung.com/java-executor-service-tutorial)
- [Guide To CompletableFuture](https://www.baeldung.com/java-completablefuture)
### NOTE:
Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article.

View File

@ -0,0 +1,26 @@
<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>java-concurrency-simple</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-concurrency-simple</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<finalName>java-concurrency-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -2,6 +2,7 @@ package com.baeldung.timeago.version7;
import java.util.Date;
import java.util.TimeZone;
import java.util.Calendar;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@ -12,16 +13,30 @@ import org.joda.time.format.PeriodFormatterBuilder;
public class TimeAgoCalculator {
private static long getCurrentTime() {
Calendar calendar = Calendar.getInstance();
calendar.set(2020, 1, 1, 12, 0, 0);
return calendar.getTimeInMillis();
//We return a fixed date and time in order to avoid issues related to getting time from local in unit tests.
//return System.currentTimeMillis();
}
private static long getCurrentTimeByTimeZone(TimeZone zone) {
Calendar calendar = Calendar.getInstance(zone);
calendar.set(2020, 1, 1, 12, 0, 0);
return calendar.getTimeInMillis();
//We return a fixed date and time in order to avoid issues related to getting time from local in unit tests.
//return Calendar.getInstance(zone).getTimeInMillis();
}
public static String calculateTimeAgoByTimeGranularity(Date pastTime, TimeGranularity granularity) {
Date currentTime = new Date();
long timeDifferenceInMillis = currentTime.getTime() - pastTime.getTime();
long timeDifferenceInMillis = getCurrentTime() - pastTime.getTime();
return timeDifferenceInMillis / granularity.toMillis() + " " + granularity.name()
.toLowerCase() + " ago";
}
public static String calculateHumanFriendlyTimeAgo(Date pastTime) {
Date currentTime = new Date();
long timeDifferenceInMillis = currentTime.getTime() - pastTime.getTime();
long timeDifferenceInMillis = getCurrentTime() - pastTime.getTime();
if (timeDifferenceInMillis / TimeGranularity.DECADES.toMillis() > 0)
return "several decades ago";
else if (timeDifferenceInMillis / TimeGranularity.YEARS.toMillis() > 0)
@ -41,7 +56,7 @@ public class TimeAgoCalculator {
}
public static String calculateExactTimeAgoWithJodaTime(Date pastTime) {
Period period = new Period(new DateTime(pastTime.getTime()), new DateTime());
Period period = new Period(new DateTime(pastTime.getTime()), new DateTime(getCurrentTime()));
PeriodFormatter formatter = new PeriodFormatterBuilder().appendYears()
.appendSuffix(" year ", " years ")
.appendSeparator("and ")
@ -67,7 +82,7 @@ public class TimeAgoCalculator {
}
public static String calculateHumanFriendlyTimeAgoWithJodaTime(Date pastTime) {
Period period = new Period(new DateTime(pastTime.getTime()), new DateTime());
Period period = new Period(new DateTime(pastTime.getTime()), new DateTime(getCurrentTime()));
if (period.getYears() != 0)
return "several years ago";
else if (period.getMonths() != 0)
@ -86,7 +101,7 @@ public class TimeAgoCalculator {
public static String calculateZonedTimeAgoWithJodaTime(Date pastTime, TimeZone zone) {
DateTimeZone dateTimeZone = DateTimeZone.forID(zone.getID());
Period period = new Period(new DateTime(pastTime.getTime(), dateTimeZone), new DateTime(dateTimeZone));
Period period = new Period(new DateTime(pastTime.getTime(), dateTimeZone), new DateTime(getCurrentTimeByTimeZone(zone)));
return PeriodFormat.getDefault()
.print(period);
}

View File

@ -12,9 +12,17 @@ import org.ocpsoft.prettytime.PrettyTime;
public class TimeAgoCalculator {
private static LocalDateTime getCurrentTimeByTimeZone(ZoneId zone) {
LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 12, 0, 0);
return localDateTime.atZone(zone)
.toLocalDateTime();
//We return a fixed date and time in order to avoid issues related to getting time from local in unit tests.
//return LocalDateTime.now(zone);
}
public static String calculateTimeAgoWithPeriodAndDuration(LocalDateTime pastTime, ZoneId zone) {
Period period = Period.between(pastTime.toLocalDate(), LocalDate.now(zone));
Duration duration = Duration.between(pastTime, LocalDateTime.now(zone));
Period period = Period.between(pastTime.toLocalDate(), getCurrentTimeByTimeZone(zone).toLocalDate());
Duration duration = Duration.between(pastTime, getCurrentTimeByTimeZone(zone));
if (period.getYears() != 0)
return "several years ago";
else if (period.getMonths() != 0)

View File

@ -1,56 +1,64 @@
package com.baeldung.timeago.version7;
import java.util.Date;
import java.util.Calendar;
import org.junit.Assert;
import org.junit.Test;
public class TimeAgoCalculatorUnitTest {
// fixing tests in BAEL-5647
//@Test
private long getCurrentTime() {
Calendar calendar = Calendar.getInstance();
calendar.set(2020, 1, 1, 12, 0, 0);
return calendar.getTimeInMillis();
//We return a fixed date and time in order to avoid issues related to getting time from local in unit tests.
//return System.currentTimeMillis();
}
@Test
public void timeAgoByTimeGranularityTest() {
long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Assert.assertEquals("5 seconds ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * 1000)), TimeGranularity.SECONDS));
Assert.assertEquals("5 minutes ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * 60 * 1000)), TimeGranularity.MINUTES));
Assert.assertEquals("5 hours ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * 60 * 60 * 1000)), TimeGranularity.HOURS));
Assert.assertEquals("5 days ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS)), TimeGranularity.DAYS));
Assert.assertEquals("5 months ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 30)), TimeGranularity.MONTHS));
Assert.assertEquals("5 weeks ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 7)), TimeGranularity.WEEKS));
Assert.assertEquals("5 years ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 365)), TimeGranularity.YEARS));
Assert.assertEquals("5 decades ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 365 * 10)), TimeGranularity.DECADES));
Assert.assertEquals("5 seconds ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * 1000)), TimeGranularity.SECONDS));
Assert.assertEquals("5 minutes ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * 60 * 1000)), TimeGranularity.MINUTES));
Assert.assertEquals("5 hours ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * 60 * 60 * 1000)), TimeGranularity.HOURS));
Assert.assertEquals("5 days ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS)), TimeGranularity.DAYS));
Assert.assertEquals("5 months ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 30)), TimeGranularity.MONTHS));
Assert.assertEquals("5 weeks ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 7)), TimeGranularity.WEEKS));
Assert.assertEquals("5 years ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 365)), TimeGranularity.YEARS));
Assert.assertEquals("5 decades ago", TimeAgoCalculator.calculateTimeAgoByTimeGranularity(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 365 * 10)), TimeGranularity.DECADES));
}
//@Test
@Test
public void humanFriendlyTimeAgoTest() {
long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Assert.assertEquals("moments ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * 1000))));
Assert.assertEquals("several minutes ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * 60 * 1000))));
Assert.assertEquals("several hours ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * 60 * 60 * 1000))));
Assert.assertEquals("several days ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS))));
Assert.assertEquals("several months ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 30))));
Assert.assertEquals("several weeks ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (3 * DAY_IN_MILLIS * 7))));
Assert.assertEquals("several years ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 365))));
Assert.assertEquals("several decades ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 365 * 10))));
Assert.assertEquals("moments ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * 1000))));
Assert.assertEquals("several minutes ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * 60 * 1000))));
Assert.assertEquals("several hours ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * 60 * 60 * 1000))));
Assert.assertEquals("several days ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS))));
Assert.assertEquals("several months ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 30))));
Assert.assertEquals("several weeks ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (3 * DAY_IN_MILLIS * 7))));
Assert.assertEquals("several years ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 365))));
Assert.assertEquals("several decades ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgo(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 365 * 10))));
}
//@Test
@Test
public void calculateExactTimeAgoWithJodaTimeTest() {
Assert.assertEquals("5 hours and 15 minutes and 3 seconds", TimeAgoCalculator.calculateExactTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * 60 * 60 * 1000 + 15 * 60 * 1000 + 3 * 1000))));
Assert.assertEquals("5 hours and 1 minute and 1 second", TimeAgoCalculator.calculateExactTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * 60 * 60 * 1000 + 1 * 60 * 1000 + 1 * 1000))));
Assert.assertEquals("2 days and 1 minute and 1 second", TimeAgoCalculator.calculateExactTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (2 * 24 * 60 * 60 * 1000 + 1 * 60 * 1000 + 1 * 1000))));
Assert.assertEquals("5 hours and 15 minutes and 3 seconds", TimeAgoCalculator.calculateExactTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * 60 * 60 * 1000 + 15 * 60 * 1000 + 3 * 1000))));
Assert.assertEquals("5 hours and 1 minute and 1 second", TimeAgoCalculator.calculateExactTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * 60 * 60 * 1000 + 1 * 60 * 1000 + 1 * 1000))));
Assert.assertEquals("2 days and 1 minute and 1 second", TimeAgoCalculator.calculateExactTimeAgoWithJodaTime(new Date(getCurrentTime() - (2 * 24 * 60 * 60 * 1000 + 1 * 60 * 1000 + 1 * 1000))));
}
//@Test
@Test
public void calculateHumanFriendlyTimeAgoWithJodaTimeTest() {
long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Assert.assertEquals("moments ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * 1000))));
Assert.assertEquals("several minutes ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * 60 * 1000))));
Assert.assertEquals("several hours ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * 60 * 60 * 1000))));
Assert.assertEquals("several days ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS))));
Assert.assertEquals("several months ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 30))));
Assert.assertEquals("several weeks ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (3 * DAY_IN_MILLIS * 7))));
Assert.assertEquals("several years ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 365))));
Assert.assertEquals("moments ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * 1000))));
Assert.assertEquals("several minutes ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * 60 * 1000))));
Assert.assertEquals("several hours ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * 60 * 60 * 1000))));
Assert.assertEquals("several days ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS))));
Assert.assertEquals("several months ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 30))));
Assert.assertEquals("several weeks ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (3 * DAY_IN_MILLIS * 7))));
Assert.assertEquals("several years ago", TimeAgoCalculator.calculateHumanFriendlyTimeAgoWithJodaTime(new Date(getCurrentTime() - (5 * DAY_IN_MILLIS * 365))));
}
}

View File

@ -1,7 +1,9 @@
package com.baeldung.timeago.version8;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import org.junit.Assert;
@ -9,16 +11,22 @@ import org.junit.Test;
public class TimeAgoCalculatorUnitTest {
// fixing test in BAEL-5647
//@Test
private LocalDateTime getCurrentTime() {
LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 12, 0, 0);
return localDateTime.atZone(ZoneId.systemDefault())
.toLocalDateTime();
//We return a fixed date and time in order to avoid issues related to getting time from local in unit tests.
//return LocalDateTime.now(zone);
}
@Test
public void calculateTimeAgoWithPeriodAndDurationTest() {
long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Assert.assertEquals("moments ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("several seconds ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (5 * 1000)), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("several minutes ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (5 * 60 * 1000)), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("several hours ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (5 * 60 * 60 * 1000)), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("several days ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (5 * DAY_IN_MILLIS)), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("several months ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 30)), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("several years ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (5 * DAY_IN_MILLIS * 365)), ZoneId.systemDefault()), ZoneId.systemDefault()));
Assert.assertEquals("moments ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime(), ZoneId.systemDefault()));
Assert.assertEquals("several seconds ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime().minus(Duration.ofSeconds(5)), ZoneId.systemDefault()));
Assert.assertEquals("several minutes ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime().minus(Duration.ofMinutes(5)), ZoneId.systemDefault()));
Assert.assertEquals("several hours ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime().minus(Duration.ofHours(5)), ZoneId.systemDefault()));
Assert.assertEquals("several days ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime().minus(Period.ofDays(5)), ZoneId.systemDefault()));
Assert.assertEquals("several months ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime().minus(Period.ofMonths(5)), ZoneId.systemDefault()));
Assert.assertEquals("several years ago", TimeAgoCalculator.calculateTimeAgoWithPeriodAndDuration(getCurrentTime().minus(Period.ofYears(5)), ZoneId.systemDefault()));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.currentstacktrace;
public class DumpStackTraceDemo
{
public static void main(String[] args) {
methodA();
}
public static void methodA() {
try {
int num1 = 5/0; // java.lang.ArithmeticException: divide by zero
}
catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.exception.currentstacktrace;
public class StackTraceUsingThreadDemo {
public static void main(String[] args) {
methodA();
}
public static StackTraceElement[] methodA() {
return methodB();
}
public static StackTraceElement[] methodB() {
return Thread.currentThread().getStackTrace();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.exception.currentstacktrace;
public class StackTraceUsingThrowableDemo {
public static void main(String[] args) {
methodA();
}
public static StackTraceElement[] methodA() {
try {
methodB();
} catch (Throwable t) {
return t.getStackTrace();
}
return null;
}
public static void methodB() throws Throwable {
throw new Throwable("A test exception");
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.exception.currentstacktrace;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.exception.currentstacktrace.StackTraceUsingThreadDemo;
import com.baeldung.exception.currentstacktrace.StackTraceUsingThrowableDemo;
public class CurrentStacktraceDemoUnitTest {
@Test
public void whenElementIsFecthedUsingThread_thenCorrectMethodAndClassIsReturned() {
StackTraceElement[] stackTrace = new StackTraceUsingThreadDemo().methodA();
StackTraceElement elementZero = stackTrace[0];
assertEquals("java.lang.Thread", elementZero.getClassName());
assertEquals("getStackTrace", elementZero.getMethodName());
StackTraceElement elementOne = stackTrace[1];
assertEquals("com.baeldung.exception.currentstacktrace.StackTraceUsingThreadDemo", elementOne.getClassName());
assertEquals("methodB", elementOne.getMethodName());
StackTraceElement elementTwo = stackTrace[2];
assertEquals("com.baeldung.exception.currentstacktrace.StackTraceUsingThreadDemo", elementTwo.getClassName());
assertEquals("methodA", elementTwo.getMethodName());
StackTraceElement elementThree = stackTrace[3];
assertEquals("com.baeldung.exception.currentstacktrace.CurrentStacktraceDemoUnitTest", elementThree.getClassName());
assertEquals("whenElementIsFecthedUsingThread_thenCorrectMethodAndClassIsReturned", elementThree.getMethodName());
}
@Test
public void whenElementIsFecthedUsingThrowable_thenCorrectMethodAndClassIsReturned() {
StackTraceElement[] stackTrace = new StackTraceUsingThrowableDemo().methodA();
StackTraceElement elementZero = stackTrace[0];
assertEquals("com.baeldung.exception.currentstacktrace.StackTraceUsingThrowableDemo", elementZero.getClassName());
assertEquals("methodB", elementZero.getMethodName());
StackTraceElement elementOne = stackTrace[1];
assertEquals("com.baeldung.exception.currentstacktrace.StackTraceUsingThrowableDemo", elementOne.getClassName());
assertEquals("methodA", elementOne.getMethodName());
StackTraceElement elementThree = stackTrace[2];
assertEquals("com.baeldung.exception.currentstacktrace.CurrentStacktraceDemoUnitTest", elementThree.getClassName());
assertEquals("whenElementIsFecthedUsingThrowable_thenCorrectMethodAndClassIsReturned", elementThree.getMethodName());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.initializerblock.instanceblock;
public class InstanceBlockExample {
{
System.out.println("Instance initializer block 1");
}
{
System.out.println("Instance initializer block 2");
}
public InstanceBlockExample() {
System.out.println("Class constructor");
}
public static void main(String[] args) {
InstanceBlockExample iib = new InstanceBlockExample();
System.out.println("Main Method");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.initializerblock.staticblock;
public class StaticBlockExample {
static {
System.out.println("static block 1");
}
static {
System.out.println("static block 2");
}
public static void main(String[] args) {
System.out.println("Main Method");
}
}

View File

@ -4,7 +4,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class HttpClientUnitTest {
public class HttpClientLiveTest {
@Test
public void sendRquestWithAuthHeader() throws Exception {

View File

@ -22,4 +22,22 @@
</resources>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.intrange;
import org.apache.commons.lang3.Range;
public class IntRangeApacheCommons {
public static boolean isInClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.between(lowerBound, upperBound);
return range.contains(number);
}
public static boolean isInOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.between(lowerBound + 1, upperBound - 1);
return range.contains(number);
}
public static boolean isInOpenClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.between(lowerBound + 1, upperBound);
return range.contains(number);
}
public static boolean isInClosedOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.between(lowerBound, upperBound - 1);
return range.contains(number);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.intrange;
import com.google.common.collect.Range;
public class IntRangeGoogleGuava {
public static boolean isInClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.closed(lowerBound, upperBound);
return range.contains(number);
}
public static boolean isInOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.open(lowerBound, upperBound);
return range.contains(number);
}
public static boolean isInOpenClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.openClosed(lowerBound, upperBound);
return range.contains(number);
}
public static boolean isInClosedOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
final Range<Integer> range = Range.closedOpen(lowerBound, upperBound);
return range.contains(number);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.intrange;
public class IntRangeOperators {
public static boolean isInClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
return (lowerBound <= number && number <= upperBound);
}
public static boolean isInOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
return (lowerBound < number && number < upperBound);
}
public static boolean isInOpenClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
return (lowerBound < number && number <= upperBound);
}
public static boolean isInClosedOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
return (lowerBound <= number && number < upperBound);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.intrange;
import java.time.temporal.ValueRange;
public class IntRangeValueRange {
public static boolean isInClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
final ValueRange range = ValueRange.of(lowerBound, upperBound);
return range.isValidIntValue(number);
}
public static boolean isInOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
final ValueRange range = ValueRange.of(lowerBound + 1, upperBound - 1);
return range.isValidIntValue(number);
}
public static boolean isInOpenClosedRange(Integer number, Integer lowerBound, Integer upperBound) {
final ValueRange range = ValueRange.of(lowerBound + 1, upperBound);
return range.isValidIntValue(number);
}
public static boolean isInClosedOpenRange(Integer number, Integer lowerBound, Integer upperBound) {
final ValueRange range = ValueRange.of(lowerBound, upperBound - 1);
return range.isValidIntValue(number);
}
}

View File

@ -0,0 +1,97 @@
package com.baeldung.intrange;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class IntRangeApacheCommonsUnitTest {
@Test
void givenIntRangeApacheCommons_whenIsInClosedRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInClosedRange(10, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInClosedRange(20, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsNotInClosedRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInClosedRange(8, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInClosedRange(22, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsInOpenRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInOpenRange(11, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInOpenRange(19, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsNotInOpenRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInOpenRange(10, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInOpenRange(20, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsInOpenClosedRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInOpenClosedRange(11, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInOpenClosedRange(20, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsNotInOpenClosedRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInOpenClosedRange(10, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInOpenClosedRange(21, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsInClosedOpenRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInClosedOpenRange(10, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInClosedOpenRange(19, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeApacheCommons_whenIsNotInClosedOpenRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeApacheCommons.isInClosedOpenRange(9, 10, 20);
boolean resultUpperBound = IntRangeApacheCommons.isInClosedOpenRange(20, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.intrange;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class IntRangeGoogleGuavaUnitTest {
@Test
void givenIntRangeGoogleGuava_whenIsInOpenRange_thenSuccess() {
// when
boolean result = IntRangeGoogleGuava.isInOpenRange(14, 10, 20);
//then
assertTrue(result);
}
@Test
void givenIntRangeGoogleGuava_whenIsNotInOpenRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeGoogleGuava.isInOpenRange(10, 10, 20);
boolean resultUpperBound = IntRangeGoogleGuava.isInOpenRange(20, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeGoogleGuava_whenIsInClosedRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeGoogleGuava.isInClosedRange(-10, -10, 5);
boolean resultUpperBound = IntRangeGoogleGuava.isInClosedRange(5, -10, 5);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeGoogleGuava_whenIsNotInClosedRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeGoogleGuava.isInClosedRange(-11, -10, 5);
boolean resultUpperBound = IntRangeGoogleGuava.isInClosedRange(6, -10, 5);
//then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeGoogleGuava_whenIsInOpenClosedRange_thenSuccess() {
// when
boolean result = IntRangeGoogleGuava.isInOpenClosedRange(20, 10, 20);
// then
assertTrue(result);
}
@Test
void givenIntRangeGoogleGuava_whenIsNotInOpenClosedRange_thenFailure() {
// when
boolean result = IntRangeGoogleGuava.isInOpenClosedRange(10, 10, 20);
// then
assertFalse(result);
}
@Test
void givenIntRangeGoogleGuava_whenIsInClosedOpenRange_thenSuccess() {
// when
boolean result = IntRangeGoogleGuava.isInClosedOpenRange(10, 10, 20);
// then
assertTrue(result);
}
@Test
void givenIntRangeGoogleGuava_whenIsNotInClosedOpenRange_thenFailure() {
// when
boolean result = IntRangeGoogleGuava.isInClosedOpenRange(20, 10, 20);
// then
assertFalse(result);
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.intrange;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class IntRangeOperatorsUnitTest {
@Test
void givenIntRangeOperators_whenIsInOpenRange_thenSuccess() {
// when
boolean result = IntRangeOperators.isInOpenRange(11, 10, 20);
//then
assertTrue(result);
}
@Test
void givenIntRangeOperators_whenIsNotInOpenRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeOperators.isInOpenRange(10, 10, 20);
boolean resultUpperBound = IntRangeOperators.isInOpenRange(20, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeOperators_whenIsInClosedRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeOperators.isInClosedRange(-10, -10, 5);
boolean resultUpperBound = IntRangeOperators.isInClosedRange(5, -10, 5);
// then
assertTrue(resultUpperBound);
assertTrue(resultLowerBound);
}
@Test
void givenIntRangeOperators_whenIsNotInClosedRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeOperators.isInClosedRange(-11, -10, 5);
boolean resultUpperBound = IntRangeOperators.isInClosedRange(6, -10, 5);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeOperators_whenIsInOpenClosedRange_thenSuccess() {
// when
boolean result = IntRangeOperators.isInOpenClosedRange(20, 10, 20);
// then
assertTrue(result);
}
@Test
void givenIntRangeOperators_whenIsNotInOpenClosedRange_thenFailure() {
// when
boolean result = IntRangeOperators.isInOpenClosedRange(10, 10, 20);
// then
assertFalse(result);
}
@Test
void givenIntRangeOperators_whenIsInClosedOpenRange_thenSuccess() {
// when
boolean result = IntRangeOperators.isInClosedOpenRange(10, 10, 20);
// then
assertTrue(result);
}
@Test
void givenIntRangeOperators_whenIsNotInClosedOpenRange_thenFailure() {
// when
boolean result = IntRangeOperators.isInClosedOpenRange(20, 10, 20);
// then
assertFalse(result);
}
}

View File

@ -0,0 +1,97 @@
package com.baeldung.intrange;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class IntRangeValueRangeUnitTest {
@Test
void givenIntRangeValueRange_whenIsInClosedRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeValueRange.isInClosedRange(10, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInClosedRange(20, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsNotInClosedRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeValueRange.isInClosedRange(9, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInClosedRange(21, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsInOpenRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeValueRange.isInOpenRange(11, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInOpenRange(19, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsNotInOpenRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeValueRange.isInOpenRange(10, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInOpenRange(20, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsInOpenClosedRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeValueRange.isInOpenClosedRange(11, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInOpenClosedRange(20, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsNotInOpenClosedRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeValueRange.isInOpenClosedRange(10, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInOpenClosedRange(21, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsInClosedOpenRange_thenSuccess() {
// when
boolean resultLowerBound = IntRangeValueRange.isInClosedOpenRange(10, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInClosedOpenRange(19, 10, 20);
// then
assertTrue(resultLowerBound);
assertTrue(resultUpperBound);
}
@Test
void givenIntRangeValueRange_whenIsNotInClosedOpenRange_thenFailure() {
// when
boolean resultLowerBound = IntRangeValueRange.isInClosedOpenRange(9, 10, 20);
boolean resultUpperBound = IntRangeValueRange.isInClosedOpenRange(20, 10, 20);
// then
assertFalse(resultLowerBound);
assertFalse(resultUpperBound);
}
}

View File

@ -8,3 +8,4 @@
- [Check if a String Ends with a Certain Pattern in Java](https://www.baeldung.com/java-string-ends-pattern)
- [Check if a Character is a Vowel in Java](https://www.baeldung.com/java-check-character-vowel)
- [How to Truncate a String in Java](https://www.baeldung.com/java-truncating-strings)
- [Remove Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-whitespace)

View File

@ -42,6 +42,7 @@
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>
<module>core-java-collections-maps-5</module>
<module>core-java-concurrency-simple</module>
<module>core-java-concurrency-2</module>
<module>core-java-concurrency-advanced</module>
<module>core-java-concurrency-advanced-2</module>

View File

@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@ -0,0 +1,21 @@
plugins {
id("org.springframework.boot") version "2.7.2"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
id("java")
}
group = "com.baeldung.gradle"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter:2.7.2")
testImplementation("org.springframework.boot:spring-boot-starter-test:2.7.2")
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View File

@ -0,0 +1,25 @@
plugins {
id("java")
}
group = "com.baeldung.gradle"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.0")
testRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:5.7.0")
if(project.hasProperty("isLocal")) {
implementation("com.baeldung.gradle:provider1")
} else {
implementation("com.baeldung.gradle:provider2")
}
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View File

@ -0,0 +1,30 @@
plugins {
id("java")
}
group = "com.baeldung.gradle"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
}
configurations.all {
resolutionStrategy.dependencySubstitution {
if (project.hasProperty("isLocal"))
substitute(project(":provider1"))
.using(project(":provider2"))
.because("Project property override(isLocal).")
}
}
dependencies {
implementation(project(":provider1"))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.0")
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,19 @@
plugins {
id("java")
}
group = "com.baeldung.gradle"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.0")
testRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:5.9.0")
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View File

@ -0,0 +1,19 @@
plugins {
id("java")
}
group = "com.baeldung.gradle"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.0")
testRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:5.9.0")
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View File

@ -0,0 +1,5 @@
rootProject.name = "conditional-dependency-demo"
include("provider1")
include("provider2")
include("consumer1")
include("consumer2")

View File

@ -0,0 +1,15 @@
package com.baeldung.gradle.conditionaldependencydemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Arrays;
@SpringBootApplication
public class ConditionalDependencyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ConditionalDependencyDemoApplication.class, args);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.gradle.conditionaldependencydemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ConditionalDependencyDemoApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -2,3 +2,4 @@ rootProject.name = 'gradle-modules'
include 'gradle'
include 'gradle-5'
include 'gradle-6'
include 'gradle-7'

View File

@ -3,9 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jackson</artifactId>
<artifactId>jackson-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson</name>
<name>jackson-core</name>
<parent>
<groupId>com.baeldung</groupId>

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