Initial commit

This commit is contained in:
Piotr Dec 2024-03-16 12:51:44 +01:00
commit 159ce68dec
Signed by: stawros
GPG key ID: F89F27AD8F881A91
21 changed files with 924 additions and 0 deletions

3
.gitignore vendored Normal file
View file

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

28
hazelcast/pom.xml Normal file
View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>eu.ztsh.lib</groupId>
<artifactId>time-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>eu.ztsh.lib.time</groupId>
<artifactId>hazelcast</artifactId>
<dependencies>
<dependency>
<groupId>eu.ztsh.lib.time</groupId>
<artifactId>time</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-all</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

13
hazelcast/readme.md Normal file
View file

@ -0,0 +1,13 @@
# Hazelcast serializer
Provides custom serializer for `TimeRange`.
## Usage
In `hazelcast.yaml` just add
```yaml
hazelcast:
serialization:
serializers:
- type-class: eu.ztsh.lib.time.TimeRange
class-name: eu.ztsh.lib.time.hazelcast.TimeRangeSerializer
```

View file

@ -0,0 +1,33 @@
package eu.ztsh.lib.time.hazelcast;
import com.hazelcast.nio.serialization.ByteArraySerializer;
import eu.ztsh.lib.time.TimeRange;
import java.io.IOException;
import java.time.LocalDate;
import static eu.ztsh.lib.time.Formatters.yearMonthDay;
public class TimeRangeSerializer implements ByteArraySerializer<TimeRange> {
@Override
public byte[] write(TimeRange timeRange) throws IOException {
return (yearMonthDay.format(timeRange.from()) + ":" + yearMonthDay.format(timeRange.to())).getBytes();
}
@Override
public TimeRange read(byte[] bytes) throws IOException {
var stringData = new String(bytes).split(":");
return new TimeRange(parse(stringData[0]), parse(stringData[1]));
}
private static LocalDate parse(String input) {
return LocalDate.parse(input, yearMonthDay);
}
@Override
public int getTypeId() {
return 150;
}
}

View file

@ -0,0 +1,35 @@
package eu.ztsh.lib.time.hazelcast;
import eu.ztsh.lib.time.TimeRange;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
class TimeRangeSerializerTest {
private final LocalDate date1 = LocalDate.of(2023, 10, 10);
private final LocalDate date2 = LocalDate.of(2023, 10, 11);
private final LocalDate date3 = LocalDate.of(2023, 10, 12);
private final TimeRangeSerializer serializer = new TimeRangeSerializer();
@Test
public void identityTest() throws IOException {
var range1 = new TimeRange(date1, date2);
var range2 = serializer.read(serializer.write(range1));
assertThat(range2).isEqualTo(range1);
}
@Test
public void nonIdentityTest() throws IOException {
var range1 = new TimeRange(date1, date2);
var range2 = new TimeRange(date1, date3);
var range3 = serializer.read(serializer.write(range1));
assertThat(range1).isNotEqualTo(range2);
assertThat(range3).isNotEqualTo(range2);
}
}

65
pom.xml Normal file
View file

@ -0,0 +1,65 @@
<?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>
<groupId>eu.ztsh.lib</groupId>
<artifactId>time-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>time</module>
<module>hazelcast</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>17</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<jakarta-validation.version>3.0.2</jakarta-validation.version>
<hazelcast.version>4.2.8</hazelcast.version>
<assertj.version>3.24.2</assertj.version>
<junit-jupiter.version>5.9.3</junit-jupiter.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>eu.ztsh.lib.time</groupId>
<artifactId>time</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>${jakarta-validation.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-all</artifactId>
<version>${hazelcast.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

8
readme.md Normal file
View file

@ -0,0 +1,8 @@
# Time range library
This library was created as an effect of creating multiple time management applications.
Main concepts:
- TimeRange: a both end closed range of LocalDates with iterator
- Diff: representation of difference between expected and actual time duration
- Duration: seconds between `LocalDateTime`s or other `Duration`s

22
time/pom.xml Normal file
View file

@ -0,0 +1,22 @@
<?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>
<parent>
<groupId>eu.ztsh.lib</groupId>
<artifactId>time-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>eu.ztsh.lib.time</groupId>
<artifactId>time</artifactId>
<dependencies>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,22 @@
package eu.ztsh.lib.time;
/**
* Structure for summarized work time.
*
* @param summary Short description
* @param time String representation of spent hours
* @param diff Difference between expected and real work time as {@link Diff} object
*/
public record Calculation(String summary, String time, Diff diff) {
public static Calculation calculate(String summary, long daysTillToday, long secondsSpent) {
return new Calculation(summary,
String.valueOf(((double) secondsSpent) / (60 * 60)),
Diff.calculate(daysTillToday, secondsSpent));
}
public static Calculation off(String summary) {
return new Calculation(summary, "0.0", Diff.OFF);
}
}

View file

@ -0,0 +1,49 @@
package eu.ztsh.lib.time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import static eu.ztsh.lib.time.Formatters.hourMinutesShort;
/**
* Work time diff counter.
*
* <p> Can be used for:
* <ul>
* <li>days</li>
* <ul>
* <li>daysTillToday: 1</li>
* <li>secondsSpent: amount of work done on that day (in seconds)</li>
* </ul>
* <li>weeks</li>
* <ul>
* <li>daysTillToday: 5</li>
* <li>secondsSpent: amount of work done on that week (in seconds)</li>
* </ul>
* <li>any other period of time</li>
* </ul>
*
* @param value String representation of difference between expected and real time
* @param state Diff placement on timeline
*/
public record Diff(String value, State state) {
public static final Diff OFF = new Diff("0:00", State.OFF);
public static Diff calculate(long daysTillToday, long secondsSpent) {
var totalSeconds = TimeUnit.HOURS.toSeconds(daysTillToday * 8);
var diff = secondsSpent - totalSeconds;
if (diff == 0) {
return new Diff("0:00", State.EQUAL);
}
return diff > 0
? new Diff("+" + todayWithSeconds(diff).format(hourMinutesShort), State.ADVANCED)
: new Diff("-" + todayWithSeconds(-diff).format(hourMinutesShort), State.OVERDUE);
}
private static LocalDateTime todayWithSeconds(long seconds) {
return LocalDate.now().atTime(0, 0).plusSeconds(seconds);
}
}

View file

@ -0,0 +1,87 @@
package eu.ztsh.lib.time;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import static eu.ztsh.lib.time.Formatters.hourMinutes;
/**
* Object representation od elapsed time
*/
public class Duration implements Comparable<Duration> {
private final LocalDateTime started;
private final int timeSpentSeconds;
private final LocalDateTime finished;
public static Duration between(Duration previous, Duration next) {
if (previous.started.equals(next.started)) {
return new Duration(previous.started, 0, next.started);
}
var seconds = secondsBetween(previous.finished, next.started);
return seconds < 0
? new Duration(next.finished, seconds, previous.started)
: new Duration(previous.finished, seconds, next.started);
}
Duration(LocalDateTime started, LocalDateTime finished) {
this.started = started;
this.finished = finished;
this.timeSpentSeconds = secondsBetween(started, finished);
}
Duration(LocalDateTime started, int timeSpentSeconds, LocalDateTime finished) {
this.started = started;
this.timeSpentSeconds = timeSpentSeconds;
this.finished = finished;
}
public LocalDateTime getStarted() {
return started;
}
public int getTimeSpentSeconds() {
return timeSpentSeconds;
}
public LocalDateTime getFinished() {
return finished;
}
/**
* long -> gap -> short
*
* @param duration the object to be compared.
* @return comparison result
*/
@Override
public int compareTo(@NotNull Duration duration) {
var dates = started.compareTo(duration.started);
return dates != 0 ? dates : duration.timeSpentSeconds - timeSpentSeconds;
}
@Override
public String toString() {
return "Duration(" + hourMinutes.format(started) + "-" + hourMinutes.format(finished) + ")";
}
@Override
public int hashCode() {
return Objects.hash(started, finished);
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Duration duration)
&& duration.started.equals(this.started)
&& duration.finished.equals(this.finished);
}
private static int secondsBetween(LocalDateTime from, LocalDateTime to) {
return Math.toIntExact(from.until(to, ChronoUnit.SECONDS));
}
}

View file

@ -0,0 +1,16 @@
package eu.ztsh.lib.time;
import java.time.format.DateTimeFormatter;
/**
* Collection of most commonly used DateTime formatters
*/
public class Formatters {
public final static DateTimeFormatter hourMinutes = DateTimeFormatter.ofPattern("HH:mm");
public final static DateTimeFormatter hourMinutesShort = DateTimeFormatter.ofPattern("H:mm");
public final static DateTimeFormatter dayMonth = DateTimeFormatter.ofPattern("dd.MM");
public final static DateTimeFormatter yearMonthDay = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public final static DateTimeFormatter monthYear = DateTimeFormatter.ofPattern("MM.yyyy");
}

View file

@ -0,0 +1,12 @@
package eu.ztsh.lib.time;
/**
* {@link Diff} state with graphical representation
*/
public enum State {
OFF,
OVERDUE,
EQUAL,
ADVANCED
}

View file

@ -0,0 +1,98 @@
package eu.ztsh.lib.time;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import static eu.ztsh.lib.time.Formatters.dayMonth;
/**
* A range of dates.
*
* @param from Start date (inclusive)
* @param to End date (inclusive)
*/
public record TimeRange(LocalDate from, LocalDate to) {
public TimeRange {
to = Objects.requireNonNullElse(to, LocalDate.now());
}
public TimeRange(LocalDate from) {
this(from, null);
}
public Iterator<LocalDate> iterator() {
return new TimeRangeIterator(from, to);
}
public List<LocalDate> getDates() {
return from.datesUntil(to.plusDays(1)).toList();
}
public long getLength() {
return getDates().size();
}
public TimeRange expand(LocalDate target) {
if (target.isBefore(from)) {
return new TimeRange(target, to);
} else if (target.isAfter(to)) {
return new TimeRange(from, target);
}
return this;
}
public TimeRange merge(TimeRange other) {
var merged = Stream.concat(getDates().stream(), other.getDates().stream()).sorted().distinct().toList();
var first = merged.get(0);
var last = merged.get(merged.size() - 1);
if (first.until(last).getDays() > merged.size()) {
throw new IllegalArgumentException("Adjacent ranges");
}
return new TimeRange(first, last);
}
@Override
public boolean equals(Object o) {
return this == o || (o instanceof TimeRange that)
&& this.from.equals(that.from)
&& this.to.equals(that.to);
}
@Override
public int hashCode() {
return Objects.hash(from, to);
}
@Override
public String toString() {
return dayMonth.format(from) + "-" + dayMonth.format(to);
}
private static class TimeRangeIterator implements Iterator<LocalDate> {
private final LocalDate to;
private LocalDate now;
private TimeRangeIterator(LocalDate from, LocalDate to) {
this.to = to;
now = from;
}
@Override
public boolean hasNext() {
return !now.isAfter(to);
}
@Override
public LocalDate next() {
now = now.plusDays(1);
return now.minusDays(1);
}
}
}

View file

@ -0,0 +1,26 @@
package eu.ztsh.lib.time;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class Timer {
private LocalDateTime currentSession;
private final List<Duration> sessions = new ArrayList<>();
public void start() {
currentSession = LocalDateTime.now();
}
public int stop() {
var elapsed = new Duration(currentSession, LocalDateTime.now());
sessions.add(elapsed);
return elapsed.getTimeSpentSeconds();
}
public int getElapsed() {
return sessions.stream().mapToInt(Duration::getTimeSpentSeconds).sum();
}
}

View file

@ -0,0 +1,67 @@
package eu.ztsh.lib.time.util;
import eu.ztsh.lib.time.TimeRange;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static eu.ztsh.lib.time.util.TimeUtil.*;
public class TimeRangeUtil {
public static List<TimeRange> createRanges(Date today) {
return createRanges(convert(today));
}
public static List<TimeRange> createRanges() {
return createRanges(LocalDate.now());
}
public static List<TimeRange> createRanges(LocalDate today) {
List<TimeRange> ranges = new ArrayList<>();
FridaySupplier fridaySupplier = isWeekend(today) ? TimeUtil::getLastFriday : TimeUtil::getNextFriday;
// current range
ranges.add(new TimeRange(getLastMonday(today), fridaySupplier.supply(today)));
var limitMonth = today.getMonth().minus(isMonthBeginning(today) ? 2 : 1);
while (true) {
today = today.minusWeeks(1);
var monday = getLastMonday(today);
var sunday = getNextSunday(today);
// check if whole week is out of bounds
if (monday.getMonth().equals(limitMonth) && sunday.getMonth().equals(limitMonth)) {
break;
}
ranges.add(new TimeRange(monday, fridaySupplier.supply(today)));
}
Collections.reverse(ranges);
return ranges;
}
public static TimeRange getCurrentWeek() {
return getWeekFor(LocalDate.now());
}
public static TimeRange getLastWeek() {
return getWeekFor(LocalDate.now().minusWeeks(1));
}
private static TimeRange getWeekFor(LocalDate today) {
FridaySupplier fridaySupplier = isWeekend(today) ? TimeUtil::getLastFriday : TimeUtil::getNextFriday;
// current range
return new TimeRange(getLastMonday(today), fridaySupplier.supply(today));
}
private interface FridaySupplier {
LocalDate supply(LocalDate input);
}
private TimeRangeUtil() {
throw new IllegalStateException("Utility class");
}
}

View file

@ -0,0 +1,89 @@
package eu.ztsh.lib.time.util;
import eu.ztsh.lib.time.TimeRange;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
/**
* Collection of common DateTime oriented functions
*/
public class TimeUtil {
public static LocalDate today() {
return LocalDate.now();
}
public static LocalDate convert(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static Date convert(LocalDate dateToConvert) {
return Date.from(dateToConvert.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
public static LocalDateTime convertFull(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static boolean isMonday(LocalDate today) {
return today.getDayOfWeek() == DayOfWeek.MONDAY;
}
public static boolean isWeekend(LocalDate today) {
return today.getDayOfWeek() == DayOfWeek.SATURDAY
|| today.getDayOfWeek() == DayOfWeek.SUNDAY;
}
public static boolean isMonthBeginning(LocalDate today) {
return !today.minusWeeks(1).getMonth().equals(today.getMonth());
}
public static LocalDate getLastMonday(LocalDate today) {
return today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
public static LocalDate getNextSunday(LocalDate today) {
return today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static LocalDate getNextFriday(LocalDate today) {
return today.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
}
public static LocalDate getLastFriday(LocalDate today) {
return today.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
}
public static LocalDate getFirstDayOfMonth(LocalDate today) {
return today.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDate getLastDayOfMonth(LocalDate today) {
return today.with(TemporalAdjusters.lastDayOfMonth());
}
public static long countUntil(List<TimeRange> ranges, LocalDate today) {
return ranges.stream()
.map(TimeRange::getDates)
.flatMap(List::stream)
.filter(date -> date.getMonth().equals(today.getMonth()) && (date.isBefore(today) || date.equals(today)))
.count();
}
private TimeUtil() {
throw new IllegalStateException("Utility class");
}
}

View file

@ -0,0 +1,35 @@
package eu.ztsh.lib.time;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
class DiffTest {
private final static long days = 2;
private final static long secondsSpent = TimeUnit.HOURS.toSeconds(days * 8);
@Test
void equalCountTest() {
commonTest(days, "0:00", State.EQUAL);
}
@Test
void overdueCountTest() {
commonTest(days + 1, "-8:00", State.OVERDUE);
}
@Test
void advancedCountTest() {
commonTest(days - 1, "+8:00", State.ADVANCED);
}
private static void commonTest(long days, String expectedValue, State expectedState) {
var diff = Diff.calculate(days, secondsSpent);
assertThat(diff.value()).isEqualTo(expectedValue);
assertThat(diff.state()).isEqualTo(expectedState);
}
}

View file

@ -0,0 +1,43 @@
package eu.ztsh.lib.time;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
class DurationTest {
private final LocalDateTime base = LocalDateTime.of(2023, Month.JULY, 3, 8, 45);
private final Duration nullDuration = new Duration(base, 0, base);
private final Duration longDuration = new Duration(base, 3 * 60 * 60, base.plusHours(3));
private final Duration shortDuration = new Duration(base, 30 * 60, base.plusMinutes(30));
@Test
public void betweenSimpleComputeTest() {
var next = base.plusSeconds(100);
var previousDuration = new Duration(base, 0, base);
var nextDuration = new Duration(next, 0, next);
assertThat(Duration.between(previousDuration, nextDuration).getTimeSpentSeconds()).isEqualTo(100);
}
@Test
public void betweenInboundComputeTest() {
assertThat(Duration.between(longDuration, shortDuration)).isEqualByComparingTo(nullDuration);
assertThat(Duration.between(shortDuration, longDuration)).isEqualByComparingTo(nullDuration);
}
@Test
public void sortingTest() {
var set = new TreeSet<Duration>();
set.add(nullDuration);
set.add(shortDuration);
set.add(longDuration);
assertThat(set).containsExactly(longDuration, shortDuration, nullDuration);
}
}

View file

@ -0,0 +1,123 @@
package eu.ztsh.lib.time;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class TimeRangeTest {
private final LocalDate date1 = LocalDate.of(2023, 10, 10);
private final LocalDate date2 = LocalDate.of(2023, 10, 12);
private final LocalDate date3 = LocalDate.of(2023, 10, 13);
private final LocalDate date4 = LocalDate.of(2023, 10, 15);
@Test
public void lengthTest() {
var range = new TimeRange(date1, date2);
assertThat(range.getDates()).hasSize(3);
assertThat(range.getLength()).isEqualTo(3);
}
@Test
public void equalityTest() {
var range1 = new TimeRange(date1, date2);
var range2 = new TimeRange(date1, date2);
assertThat(range1).isEqualTo(range2);
}
@Test
public void nonEqualityTest() {
var range1 = new TimeRange(date1, date2);
var range2 = new TimeRange(date1, date3);
assertThat(range1).isNotEqualTo(range2);
}
@Test
public void expandAfterTest() {
var test = new TimeRange(date1, date2);
var expected = new TimeRange(date1, date3);
var result = test.expand(date3);
assertThat(result).isEqualTo(expected);
}
@Test
public void expandBeforeTest() {
var test = new TimeRange(date2, date3);
var expected = new TimeRange(date1, date3);
var result = test.expand(date1);
assertThat(result).isEqualTo(expected);
}
@Test
public void expandInternalTest() {
var test = new TimeRange(date1, date3);
var expected = new TimeRange(date1, date3);
var result = test.expand(date2);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeAfterTest() {
var test1 = new TimeRange(date1, date2);
var test2 = new TimeRange(date3, date4);
var expected = new TimeRange(date1, date4);
var result = test1.merge(test2);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeBeforeTest() {
var test1 = new TimeRange(date1, date2);
var test2 = new TimeRange(date3, date4);
var expected = new TimeRange(date1, date4);
var result = test2.merge(test1);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeIntersectingBeforeTest() {
var test1 = new TimeRange(date1, date3);
var test2 = new TimeRange(date2, date4);
var expected = new TimeRange(date1, date4);
var result = test1.merge(test2);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeIntersectionAfterTest() {
var test1 = new TimeRange(date1, date3);
var test2 = new TimeRange(date2, date4);
var expected = new TimeRange(date1, date4);
var result = test2.merge(test1);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeMinorContainingTest() {
var test1 = new TimeRange(date1, date4);
var test2 = new TimeRange(date2, date3);
var expected = new TimeRange(date1, date4);
var result = test1.merge(test2);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeMajorContainingTest() {
var test1 = new TimeRange(date1, date4);
var test2 = new TimeRange(date2, date3);
var expected = new TimeRange(date1, date4);
var result = test2.merge(test1);
assertThat(result).isEqualTo(expected);
}
@Test
public void mergeAdjacentTest() {
var test1 = new TimeRange(date1, date2);
var test2 = new TimeRange(date4, date4);
assertThatThrownBy(() -> test1.merge(test2)).isInstanceOf(IllegalArgumentException.class);
}
}

View file

@ -0,0 +1,50 @@
package eu.ztsh.lib.time.util;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static eu.ztsh.lib.time.util.TimeUtil.countUntil;
import static org.assertj.core.api.Assertions.assertThat;
class TimeUtilTest {
@Test
public void secondMondayTest() {
assertThat(TimeUtil.isMonthBeginning(LocalDate.of(2023, 5, 8))).isFalse();
}
@Test
public void firstSundayTest() {
assertThat(TimeUtil.isMonthBeginning(LocalDate.of(2023, 5, 7))).isTrue();
}
@Test
public void firstTuesdayTest() {
assertThat(TimeUtil.isMonthBeginning(LocalDate.of(2023, 5, 2))).isTrue();
}
@Test
public void firstMondayTest() {
assertThat(TimeUtil.isMonthBeginning(LocalDate.of(2022, 11, 7))).isTrue();
}
@Test
public void countTest() {
var today = LocalDate.of(2023, 7, 23); // Sunday
var last = TimeUtil.getLastDayOfMonth(today);
var ranges = TimeRangeUtil.createRanges(last);
assertThat(ranges).hasSize(6);
assertThat(countUntil(ranges, today)).isEqualTo(15);
assertThat(countUntil(ranges, today.plusDays(1))) // Monday
.isEqualTo(16);
}
@Test
public void mondayCalculationTest() {
var monday = LocalDate.of(2023, 5, 1);
assertThat(TimeUtil.getLastMonday(monday)).isEqualTo(monday);
assertThat(TimeUtil.getLastMonday(monday.plusDays(2))).isEqualTo(monday);
}
}