Skip to content

Commit

Permalink
✨ feat: add unify functions Date4j, Time4j and String4j #4
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed May 25, 2024
1 parent 7ddec95 commit a3a6122
Show file tree
Hide file tree
Showing 7 changed files with 437 additions and 9 deletions.
4 changes: 3 additions & 1 deletion plugin/src/main/groovy/org/unify4j/common/Cookie4j.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ public static Map<String, String> getCookies(HttpServletRequest request) {
return Arrays.stream(request.getCookies()).collect(Collectors.toMap(Cookie::getName, // Use cookie's name as the map key
Cookie::getValue, // Use cookie's value as the map value
(cookie1, cookie2) -> { // Merge function for handling duplicate keys
logger.info("cookie duplicated key found by cookie-1: {} and cookie-2: {}", cookie1, cookie2);
if (logger.isInfoEnabled()) {
logger.info("cookie duplicated key found by cookie-1: {} and cookie-2: {}", cookie1, cookie2);
}
return cookie1; // Keep the value of the first cookie in case of a duplicate key
}));
}
Expand Down
328 changes: 328 additions & 0 deletions plugin/src/main/groovy/org/unify4j/common/Date4j.java

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions plugin/src/main/groovy/org/unify4j/common/String4j.java
Original file line number Diff line number Diff line change
Expand Up @@ -799,4 +799,19 @@ public static boolean hasContent(String s) {
public static int length(CharSequence cs) {
return cs == null ? 0 : cs.length();
}

/**
* Removes the leading and trailing brackets from a string, if present.
* This function checks if the input string is empty or null using the String4j utility,
* and then uses a regular expression to replace any brackets at the start or end of the string.
*
* @param input the string from which brackets are to be removed
* @return the input string with leading and trailing brackets removed, or the original string if it is empty or null
*/
public static String removeBrackets(String input) {
if (String4j.isEmpty(input)) {
return input;
}
return input.replaceAll("^\\[|]$", "");
}
}
72 changes: 69 additions & 3 deletions plugin/src/main/groovy/org/unify4j/common/Time4j.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@
public class Time4j {
protected static final Logger logger = LoggerFactory.getLogger(Time4j.class);

/**
* Converts a fractional second string representation to nanoseconds.
* Parses the given fractionalSecondText to a double, representing a fraction of a second.
* Multiplies the fractional value by 1,000,000,000 (nanoseconds in a second) and returns the result
* as a long integer, representing the equivalent nanoseconds.
*
* @param fractionalSecondText The string representation of the fractional part of a second.
* @return The equivalent nanoseconds of the given fractional second.
*/
public static long fromFractionToNanos(String fractionalSecondText) {
double fractionalSecond = Double.parseDouble(fractionalSecondText);
// Multiply the fractional value by 1,000,000,000 (nanoseconds in a second) and cast it to a long.
return (long) (fractionalSecond * 1_000_000_000);
}

/**
* Converts milliseconds to seconds.
*
Expand Down Expand Up @@ -1102,8 +1117,23 @@ public static boolean isWithinRange(Date date, Date from, Date to) {
* @return A string describing the elapsed time in a human-readable format.
*/
public static String since(Date date) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
return since(new Date(), date);
}

/**
* Provides a human-readable string representing the time elapsed since the given date.
* <p>
* This function calculates the duration between the provided date and the current date,
* and returns a string describing this duration in a human-readable format such as "just now",
* "X minutes ago", "X hours ago", etc.
*
* @param source The reference date to calculate the duration from. Typically, this would be the current date.
* @param target The date from which the elapsed time is calculated.
* @return A string describing the elapsed time in a human-readable format.
*/
public static String since(Date source, Date target) {
LocalDateTime now = transform(source);
LocalDateTime then = LocalDateTime.ofInstant(target.toInstant(), ZoneId.systemDefault());
Duration duration = Duration.between(then, now);
long seconds = duration.getSeconds();
long minutes = duration.toMinutes();
Expand All @@ -1112,7 +1142,6 @@ public static String since(Date date) {
long weeks = days / 7;
long months = days / 30;
long years = days / 365;

if (seconds < 60) {
return "just now";
} else if (minutes < 60) {
Expand All @@ -1129,4 +1158,41 @@ public static String since(Date date) {
return years + " year" + (years > 1 ? "s" : "") + " ago";
}
}

/**
* Retrieves the ZoneId corresponding to the given time zone identifier.
* If the provided time zone identifier is empty or null, the system default ZoneId is returned.
* If the time zone identifier starts with a plus (+) or minus (-) sign, it is treated as an offset
* and converted to a ZoneId using the GMT time zone.
* If the time zone identifier is a valid time zone identifier, it is converted to a ZoneId directly.
* If the time zone identifier is not valid or cannot be recognized, an attempt is made to retrieve
* the corresponding TimeZone instance, and its ZoneId is returned. If the TimeZone instance has
* a raw offset of 0 (indicating an unknown or invalid time zone), an exception is thrown.
*
* @param tz The time zone identifier string.
* @return The corresponding ZoneId for the given time zone identifier.
* @throws IllegalArgumentException if the time zone identifier is invalid or cannot be recognized.
*/
public static ZoneId parseTimeZone(String tz) {
if (String4j.isEmpty(tz)) {
return ZoneId.systemDefault();
}
if (tz.startsWith("-") || tz.startsWith("+")) {
ZoneOffset offset = ZoneOffset.of(tz); // If the time zone identifier starts with '+' or '-', treat it as an offset and convert it to a ZoneId.
return ZoneId.ofOffset("GMT", offset);
} else {
try {
return ZoneId.of(tz); // Attempt to parse the time zone identifier directly as a ZoneId.
} catch (Exception e) {
// If the time zone identifier is not recognized as a valid ZoneId, attempt to retrieve the corresponding TimeZone.
TimeZone timezone = TimeZone.getTimeZone(tz);
if (timezone.getRawOffset() == 0) {
// If the retrieved TimeZone has a raw offset of 0, indicating an unknown or invalid time zone, throw an exception.
throw e;
}
// Otherwise, convert the retrieved TimeZone to a ZoneId and return it.
return timezone.toZoneId();
}
}
}
}
8 changes: 4 additions & 4 deletions plugin/src/main/groovy/org/unify4j/text/TimeFormatText.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ public class TimeFormatText {
public static final String MEDIUM_EPOCH_PATTERN = "MMM d, y, h:mm:ss a";

/**
* Format: June 15, 2019 at 10:54:25 PM GMT+5
* Format: June 15, 2019, at 10:54:25 PM GMT+5
* Description: Long pattern for date and time including full month name, day, year, hour, minutes, seconds, AM/PM indicator, and timezone.
*/
public static final String LONG_EPOCH_PATTERN = "MMMM d, y, h:mm:ss a z";

/**
* Format: Saturday, June 15, 2019 at 10:54:25 PM GMT+05:30
* Format: Saturday, June 15, 2019, at 10:54:25 PM GMT+05:30
* Description: Completed pattern for date and time including day of the week, full month name, day, year, hour, minutes, seconds, AM/PM indicator, and timezone.
*/
public static final String COMPLETED_EPOCH_PATTERN = "EEEE, MMMM d, y, h:mm:ss a zzzz";
Expand All @@ -40,13 +40,13 @@ public class TimeFormatText {
public static final String MEDIUM_DATE_EPOCH_PATTERN = "MMM d, y";

/**
* Format: June 15, 2019
* Format: June 15, 2019,
* Description: Long pattern for date only including full month name, day, and year.
*/
public static final String LONG_DATE_EPOCH_PATTERN = "MMMM d, y";

/**
* Format: Saturday, June 15, 2019
* Format: Saturday, June 15, 2019,
* Description: Completed pattern for date only including day of the week, full month name, day, and year.
*/
public static final String COMPLETED_DATE_EPOCH_PATTERN = "EEEE, MMMM d, y";
Expand Down
17 changes: 17 additions & 0 deletions plugin/src/test/groovy/org/unify4j/Date4jTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.unify4j;

import org.junit.Test;
import org.unify4j.common.Date4j;
import org.unify4j.common.Time4j;
import org.unify4j.text.TimeFormatText;

import java.util.Date;

public class Date4jTest {

@Test
public void testParseDate() {
Date date = Date4j.parse("2024/05/25 19:54:23");
System.out.println(Time4j.since(date) + " * " + Time4j.format(date, TimeFormatText.SPREADSHEET_BIBLIOGRAPHY_EPOCH_PATTERN));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import static org.junit.Assert.assertEquals;
import static org.unify4j.common.UniqueId4j.*;

public class UniqueIdTest {
public class UniqueId4jTest {
protected static final int bucketSize = 200000;

@Test
Expand Down

0 comments on commit a3a6122

Please sign in to comment.