Fix several date parsing issues discovered via code review. I've learned we must always use the correct java.time.* object and cannot use Instant everywhere.

This commit is contained in:
Tim Donohue
2025-02-26 16:49:50 -06:00
parent fe9b58d936
commit 825b223b4f
15 changed files with 57 additions and 48 deletions

View File

@@ -10,7 +10,6 @@ package org.dspace.app.ldn.action;
import static java.lang.String.format;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@@ -34,8 +33,6 @@ public class LDNEmailAction implements LDNAction {
private static final Logger log = LogManager.getLogger(LDNEmailAction.class);
private final static String DATE_PATTERN = "dd-MM-yyyy HH:mm:ss";
@Autowired
private ConfigurationService configurationService;
@@ -80,7 +77,7 @@ public class LDNEmailAction implements LDNAction {
email.addRecipient(recipient);
}
String date = DateTimeFormatter.ofPattern(DATE_PATTERN).format(Instant.now());
String date = Instant.now().toString();
email.addArgument(notification.getActor().getName());
email.addArgument(item.getName());

View File

@@ -11,6 +11,7 @@ import java.io.File;
import java.io.FilenameFilter;
import java.time.Instant;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
@@ -103,7 +104,7 @@ public class StatisticsLoader {
int i = 0;
for (String date : keys) {
try {
dates[i] = LocalDate.parse(date, monthlySDF.get());
dates[i] = YearMonth.parse(date, monthlySDF.get()).atDay(1);
} catch (DateTimeParseException pe) {
//ignore
}

View File

@@ -11,6 +11,8 @@ import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
@@ -328,6 +330,6 @@ public class SimpleReporterServiceImpl implements SimpleReporterService {
}
protected String applyDateFormatShort(Instant thisDate) {
return DateTimeFormatter.ISO_LOCAL_DATE.format(thisDate);
return DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.ofInstant(thisDate, ZoneOffset.UTC));
}
}

View File

@@ -13,7 +13,8 @@ import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import org.dspace.services.ConfigurationService;
@@ -41,7 +42,7 @@ public class FileReporter
throws IOException {
// Calculate a unique(?) file name.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'hhmmssSSS");
String filename = String.format("curation-%s.report", formatter.format(Instant.now()));
String filename = String.format("curation-%s.report", formatter.format(LocalDateTime.now(ZoneOffset.UTC)));
// Build a path to the directory which is to receive the file.
ConfigurationService cfg = new DSpace().getConfigurationService();

View File

@@ -424,7 +424,7 @@ public class ItemIndexFactoryImpl extends DSpaceObjectIndexFactoryImpl<Indexable
date = MultiFormatDateParser.parse(value);
if (date != null) {
//TODO: make this date format configurable !
value = DateTimeFormatter.ISO_LOCAL_DATE.format(date);
value = DateTimeFormatter.ISO_LOCAL_DATE.format(date.toLocalDateTime().toLocalDate());
}
}
doc.addField(searchFilter.getIndexFieldName(), value);
@@ -714,7 +714,7 @@ public class ItemIndexFactoryImpl extends DSpaceObjectIndexFactoryImpl<Indexable
} else if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
if (date != null) {
String indexField = searchFilter.getIndexFieldName() + ".year";
String yearUTC = DateTimeFormatter.ofPattern("yyyy").format(date);
String yearUTC = String.valueOf(date.getYear());
doc.addField(searchFilter.getIndexFieldName() + "_keyword", yearUTC);
// add the year to the autocomplete index
doc.addField(searchFilter.getIndexFieldName() + "_ac", yearUTC);

View File

@@ -10,6 +10,7 @@ package org.dspace.discovery.indexobject;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
@@ -139,7 +140,8 @@ public class LDNMessageEntityIndexFactoryImpl extends IndexFactoryImpl<Indexable
private void indexDateFieldForFacet(SolrInputDocument doc, Instant queueLastStartTime) {
if (queueLastStartTime != null) {
String value = DateTimeFormatter.ISO_LOCAL_DATE.format(queueLastStartTime);
String value = DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.ofInstant(queueLastStartTime,
ZoneOffset.UTC));
addFacetIndex(doc, "queue_last_start_time", value, value);
doc.addField("queue_last_start_time", value);
doc.addField("queue_last_start_time_dt", queueLastStartTime);

View File

@@ -10,7 +10,8 @@ package org.dspace.eperson;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
@@ -63,7 +64,7 @@ public class Groomer {
options.addOption("b", "last-used-before", true,
"date of last login was before this (for example: "
+ DateTimeFormatter.ISO_LOCAL_DATE.format(Instant.now())
+ DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now(ZoneOffset.UTC))
+ ')');
options.addOption("d", "delete", false, "delete matching epersons");
@@ -107,9 +108,9 @@ public class Groomer {
System.exit(1);
}
Instant before = null;
LocalDate before = null;
try {
before = DateTimeFormatter.ISO_LOCAL_DATE.parse(command.getOptionValue('b'), Instant::from);
before = LocalDate.parse(command.getOptionValue('b'));
} catch (DateTimeParseException ex) {
System.err.println(ex.getMessage());
System.exit(1);
@@ -118,7 +119,8 @@ public class Groomer {
boolean delete = command.hasOption('d');
Context myContext = new Context();
List<EPerson> epeople = ePersonService.findNotActiveSince(myContext, before);
List<EPerson> epeople = ePersonService.findNotActiveSince(myContext,
before.atStartOfDay().toInstant(ZoneOffset.UTC));
myContext.turnOffAuthorisationSystem();
for (EPerson account : epeople) {

View File

@@ -27,6 +27,7 @@ import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
@@ -995,18 +996,18 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea
} catch (DateTimeParseException e) {
e.printStackTrace();
}
String dateformatString = "dd-MM-yyyy";
if ("DAY".equals(type)) {
dateformatString = "dd-MM-yyyy";
} else if ("MONTH".equals(type)) {
dateformatString = "MMMM yyyy";
} else if ("YEAR".equals(type)) {
dateformatString = "yyyy";
}
DateTimeFormatter simpleFormat = DateTimeFormatter.ofPattern(dateformatString);
if (date != null) {
name = simpleFormat.format(date);
String dateformatString = "dd-MM-yyyy";
if ("DAY".equals(type)) {
DateTimeFormatter simpleFormat = DateTimeFormatter.ofPattern(dateformatString);
name = simpleFormat.format(date);
} else if ("MONTH".equals(type)) {
dateformatString = "MMMM yyyy";
DateTimeFormatter simpleFormat = DateTimeFormatter.ofPattern(dateformatString);
name = simpleFormat.format(YearMonth.from(date));
} else if ("YEAR".equals(type)) {
name = String.valueOf(date.getYear());
}
}
}

View File

@@ -19,7 +19,7 @@ import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.text.ParsePosition;
import java.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -70,22 +70,22 @@ public class ClassicDSpaceLogConverter {
/**
* Date format (in) from the log line
*/
private final DateTimeFormatter dateFormatIn = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Date format out (for solr)
*/
private final DateTimeFormatter dateFormatOut = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
private final SimpleDateFormat dateFormatOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
/**
* Date format (in) from the log line for the UID
*/
private final DateTimeFormatter dateFormatInUID = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss,SSS");
private final SimpleDateFormat dateFormatInUID = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
/**
* Date format out (for uid)
*/
private final DateTimeFormatter dateFormatOutUID = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
private final SimpleDateFormat dateFormatOutUID = new SimpleDateFormat("yyyyMMddHHmmssSSS");
/**

View File

@@ -18,7 +18,8 @@ import java.net.InetAddress;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -237,7 +238,7 @@ public class StatisticsImporter {
action = parts[1];
id = parts[2];
// Date format (for solr)
date = DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(parts[3], Instant::from);
date = LocalDateTime.parse(parts[3]).toInstant(ZoneOffset.UTC);
user = parts[4];
ip = parts[5];

View File

@@ -12,7 +12,8 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import org.apache.logging.log4j.LogManager;
@@ -114,7 +115,7 @@ public class TabFileUsageEventListener
UsageEvent ue = (UsageEvent) event;
eventLog.append(dateFormat.format(Instant.now()))
eventLog.append(dateFormat.format(LocalDateTime.now(ZoneOffset.UTC)))
.append('\t').append(ue.getName()) // event type
.append('\t').append(Constants.typeText[ue.getObject().getType()])
.append('\t').append(ue.getObject().getID().toString())

View File

@@ -321,7 +321,7 @@ public class DateMathParser {
public LocalDateTime getNow() {
if (now == null) {
// fall back to current time if no request info set
now = LocalDateTime.now();
now = LocalDateTime.now(zone.toZoneId());
}
return now;
}
@@ -422,7 +422,7 @@ public class DateMathParser {
}
if (argv.length > 1) {
parsed = DateMathParser.parseMath(LocalDateTime.now(), argv[1]);
parsed = DateMathParser.parseMath(LocalDateTime.now(ZoneOffset.UTC), argv[1]);
System.out.format("Applied %s to explicit current time: %s%n",
argv[1], parsed.toString());
}

View File

@@ -20,7 +20,7 @@ import java.net.ConnectException;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -374,10 +374,10 @@ public class XOAI {
for (ResourcePolicy policy : policies) {
if ((policy.getGroup() != null) && (policy.getGroup().getName().equals("Anonymous"))) {
if (policy.getStartDate() != null) {
dates.add(policy.getStartDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
dates.add(policy.getStartDate().atStartOfDay(ZoneOffset.UTC).toInstant());
}
if (policy.getEndDate() != null) {
dates.add(policy.getEndDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
dates.add(policy.getEndDate().atStartOfDay(ZoneOffset.UTC).toInstant());
}
}
context.uncacheEntity(policy);
@@ -517,10 +517,10 @@ public class XOAI {
List<ResourcePolicy> policies = authorizeService.getPoliciesActionFilter(context, item, Constants.READ);
for (ResourcePolicy policy : policies) {
if ((policy.getGroup() != null) && (policy.getGroup().getName().equals("Anonymous"))) {
if (policy.getStartDate() != null && policy.getStartDate().isAfter(LocalDate.now())) {
if (policy.getStartDate() != null && policy.getStartDate().isAfter(LocalDate.now(ZoneOffset.UTC))) {
return true;
}
if (policy.getEndDate() != null && policy.getEndDate().isAfter(LocalDate.now())) {
if (policy.getEndDate() != null && policy.getEndDate().isAfter(LocalDate.now(ZoneOffset.UTC))) {
return true;
}
}

View File

@@ -9,6 +9,9 @@ package org.dspace.sword;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
@@ -132,7 +135,7 @@ public class SWORDService {
*/
public void message(String message) {
// build the processing message
String msg = dateFormat.format(Instant.now()) + " " + message + "; \n\n";
String msg = dateFormat.format(LocalDateTime.now(ZoneOffset.UTC)) + " " + message + "; \n\n";
// if this is a verbose deposit, then log it
if (this.verbose) {
@@ -166,7 +169,7 @@ public class SWORDService {
String fn = deposit.getFilename();
if (fn == null || "".equals(fn)) {
// use date in YYYY-MM-DD format
fn = "sword-" + DateTimeFormatter.ISO_LOCAL_DATE.format(Instant.now());
fn = "sword-" + DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now(ZoneOffset.UTC));
if (original) {
fn = fn + ".original";
}

View File

@@ -15,7 +15,6 @@ import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;
@@ -388,8 +387,7 @@ public class DepositServlet extends HttpServlet {
Title title = new Title();
title.setContent("ERROR");
sed.setTitle(title);
String utcformat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String serializeddate = DateTimeFormatter.ofPattern(utcformat).format(Instant.now());
String serializeddate = Instant.now().toString();
sed.setUpdated(serializeddate);
Summary sum = new Summary();
sum.setContent(summary);