Util: Consolidate and standardize date/time formatting (ticket #2016)

This commit is contained in:
zzz
2019-08-30 18:38:12 +00:00
parent 96d8385f49
commit a6e3621c06
25 changed files with 101 additions and 159 deletions

View File

@ -7,13 +7,11 @@ import java.io.Serializable;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -1803,11 +1801,8 @@ public class I2PSnarkServlet extends BasicServlet {
out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total)); out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total));
out.write("</div></div></div>"); out.write("</div></div></div>");
} else if (remaining == 0) { } else if (remaining == 0) {
// needs locale configured for automatic translation
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm, EEE dd MMM yyyy");
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
long[] dates = _manager.getSavedAddedAndCompleted(snark); long[] dates = _manager.getSavedAddedAndCompleted(snark);
String date = fmt.format(new Date(dates[1])); String date = DataHelper.formatTime(dates[1]);
out.write("<div class=\"percentBarComplete\" title=\""); out.write("<div class=\"percentBarComplete\" title=\"");
out.write(_t("Completed") + ": " + date + "\">"); out.write(_t("Completed") + ": " + date + "\">");
out.write(formatSize(total)); // 3GB out.write(formatSize(total)); // 3GB
@ -3105,11 +3100,8 @@ public class I2PSnarkServlet extends BasicServlet {
.append("</td></tr>\n"); .append("</td></tr>\n");
} }
long dat = meta.getCreationDate(); long dat = meta.getCreationDate();
// needs locale configured for automatic translation
SimpleDateFormat fmt = new SimpleDateFormat("EEEE dd MMMM yyyy HH:mm");
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
if (dat > 0) { if (dat > 0) {
String date = fmt.format(new Date(dat)); String date = DataHelper.formatTime(dat);
buf.append("<tr><td>"); buf.append("<tr><td>");
toThemeImg(buf, "details"); toThemeImg(buf, "details");
buf.append("</td><td><b>") buf.append("</td><td><b>")
@ -3130,7 +3122,7 @@ public class I2PSnarkServlet extends BasicServlet {
} }
long[] dates = _manager.getSavedAddedAndCompleted(snark); long[] dates = _manager.getSavedAddedAndCompleted(snark);
if (dates[0] > 0) { if (dates[0] > 0) {
String date = fmt.format(new Date(dates[0])); String date = DataHelper.formatTime(dates[0]);
buf.append("<tr><td>"); buf.append("<tr><td>");
toThemeImg(buf, "details"); toThemeImg(buf, "details");
buf.append("</td><td><b>") buf.append("</td><td><b>")
@ -3139,7 +3131,7 @@ public class I2PSnarkServlet extends BasicServlet {
.append("</td></tr>\n"); .append("</td></tr>\n");
} }
if (dates[1] > 0) { if (dates[1] > 0) {
String date = fmt.format(new Date(dates[1])); String date = DataHelper.formatTime(dates[1]);
buf.append("<tr><td>"); buf.append("<tr><td>");
toThemeImg(buf, "details"); toThemeImg(buf, "details");
buf.append("</td><td><b>") buf.append("</td><td><b>")
@ -3150,7 +3142,7 @@ public class I2PSnarkServlet extends BasicServlet {
if (storage != null) { if (storage != null) {
dat = storage.getActivity(); dat = storage.getActivity();
if (dat > 0) { if (dat > 0) {
String date = fmt.format(new Date(dat)); String date = DataHelper.formatTime(dat);
buf.append("<tr><td>"); buf.append("<tr><td>");
toThemeImg(buf, "details"); toThemeImg(buf, "details");
buf.append("</td><td><b>") buf.append("</td><td><b>")
@ -3451,8 +3443,6 @@ public class I2PSnarkServlet extends BasicServlet {
.append("</A></td></tr>\n"); .append("</A></td></tr>\n");
//DateFormat dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
// DateFormat.MEDIUM);
boolean showSaveButton = false; boolean showSaveButton = false;
boolean rowEven = true; boolean rowEven = true;
boolean inOrder = storage != null && storage.getInOrder(); boolean inOrder = storage != null && storage.getInOrder();
@ -3553,7 +3543,6 @@ public class I2PSnarkServlet extends BasicServlet {
if (!item.isDirectory()) if (!item.isDirectory())
buf.append(formatSize(length)); buf.append(formatSize(length));
buf.append("</td><td class=\"snarkFileStatus\">"); buf.append("</td><td class=\"snarkFileStatus\">");
//buf.append(dfmt.format(new Date(item.lastModified())));
buf.append(status); buf.append(status);
buf.append("</td>"); buf.append("</td>");
if (showPriority) { if (showPriority) {
@ -3740,8 +3729,6 @@ public class I2PSnarkServlet extends BasicServlet {
// existing ratings / comments table // existing ratings / comments table
int ccount = 0; int ccount = 0;
if (iter != null) { if (iter != null) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
buf.append("<table class=\"snarkComments\">"); buf.append("<table class=\"snarkComments\">");
while (iter.hasNext()) { while (iter.hasNext()) {
@ -3766,7 +3753,7 @@ public class I2PSnarkServlet extends BasicServlet {
} }
} }
} }
buf.append("</td><td class=\"commentDate\">").append(fmt.format(new Date(c.getTime()))); buf.append("</td><td class=\"commentDate\">").append(DataHelper.formatTime(c.getTime()));
buf.append("</td><td class=\"commentText\">"); buf.append("</td><td class=\"commentText\">");
if (esc) { if (esc) {
if (c.getText() != null) { if (c.getText() != null) {

View File

@ -1,8 +1,6 @@
package net.i2p.i2ptunnel; package net.i2p.i2ptunnel;
import java.text.DateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -38,7 +36,6 @@ class ConnThrottler {
private long _totalThrottleUntil; private long _totalThrottleUntil;
private final String _action; private final String _action;
private final Log _log; private final Log _log;
private final DateFormat _fmt;
private final SimpleTimer2.TimedEvent _cleaner; private final SimpleTimer2.TimedEvent _cleaner;
private boolean _isRunning; private boolean _isRunning;
@ -58,9 +55,6 @@ class ConnThrottler {
_peers = new HashMap<Hash, Record>(4); _peers = new HashMap<Hash, Record>(4);
_action = action; _action = action;
_log = log; _log = log;
// for logging
_fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
_fmt.setTimeZone(SystemVersion.getSystemTimeZone());
_cleaner = new Cleaner(); _cleaner = new Cleaner();
} }
@ -124,7 +118,7 @@ class ConnThrottler {
long now = Clock.getInstance().now(); long now = Clock.getInstance().now();
if (rec.countSince(now - _checkPeriod) > _max) { if (rec.countSince(now - _checkPeriod) > _max) {
long until = now + _throttlePeriod; long until = now + _throttlePeriod;
String date = _fmt.format(new Date(until)); String date = DataHelper.formatTime(until);
_log.logAlways(Log.WARN, "Throttling " + _action + " until " + date + _log.logAlways(Log.WARN, "Throttling " + _action + " until " + date +
" after exceeding max of " + _max + " after exceeding max of " + _max +
" in " + DataHelper.formatDuration(_checkPeriod) + " in " + DataHelper.formatDuration(_checkPeriod) +
@ -139,7 +133,7 @@ class ConnThrottler {
if (_totalMax > 0 && ++_currentTotal > _totalMax) { if (_totalMax > 0 && ++_currentTotal > _totalMax) {
if (_totalThrottleUntil == 0) { if (_totalThrottleUntil == 0) {
_totalThrottleUntil = Clock.getInstance().now() + _totalThrottlePeriod; _totalThrottleUntil = Clock.getInstance().now() + _totalThrottlePeriod;
String date = _fmt.format(new Date(_totalThrottleUntil)); String date = DataHelper.formatTime(_totalThrottleUntil);
_log.logAlways(Log.WARN, "*** Throttling " + _action + " from ALL peers until " + date + _log.logAlways(Log.WARN, "*** Throttling " + _action + " from ALL peers until " + date +
" after exceeding max of " + _max + " after exceeding max of " + _max +
" in " + DataHelper.formatDuration(_checkPeriod)); " in " + DataHelper.formatDuration(_checkPeriod));

View File

@ -248,17 +248,26 @@ public class NewsManager implements ClientApp {
int colon = newsContent.indexOf(": "); int colon = newsContent.indexOf(": ");
if (colon > 0 && colon <= 10) { if (colon > 0 && colon <= 10) {
// Parse the format we wrote it out in, in NewsFetcher.outputOldNewsXML() // Parse the format we wrote it out in, in NewsFetcher.outputOldNewsXML()
// Doesn't work if the date has a : in it, but SHORT hopefully does not // Doesn't work if the date has a : in it, but SHORT and MEDIUM hopefully do not
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT); // Was originally SHORT, switched to MEDIUM in 0.9.43
DateFormat fmt = DateFormat.getDateInstance(DateFormat.MEDIUM);
// the router sets the JVM time zone to UTC but saves the original here so we can get it // the router sets the JVM time zone to UTC but saves the original here so we can get it
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context)); fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
try { try {
Date date = fmt.parse(newsContent.substring(0, colon)); Date date = fmt.parse(newsContent.substring(0, colon));
entry.updated = date.getTime(); entry.updated = date.getTime();
newsContent = newsContent.substring(colon + 2);
} catch (ParseException pe) { } catch (ParseException pe) {
// can't find date, will be zero // try SHORT
try {
fmt = DateFormat.getDateInstance(DateFormat.SHORT);
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
Date date = fmt.parse(newsContent.substring(0, colon));
entry.updated = date.getTime();
} catch (ParseException pe2) {
// can't find date, will be zero
}
} }
newsContent = newsContent.substring(colon + 2);
} }
} }
int end = newsContent.indexOf("</h3>"); int end = newsContent.indexOf("</h3>");

View File

@ -4,7 +4,6 @@ import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigInteger; import java.math.BigInteger;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.DateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
@ -391,9 +390,7 @@ public class Analysis extends JobImpl implements RouterApp {
if (threshold < MIN_BLOCK_POINTS) if (threshold < MIN_BLOCK_POINTS)
threshold = MIN_BLOCK_POINTS; threshold = MIN_BLOCK_POINTS;
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {}
DateFormat dfmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); String day = DataHelper.formatTime(now);
dfmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
String day = dfmt.format(now);
for (Map.Entry<Hash, Points> e : points.entrySet()) { for (Map.Entry<Hash, Points> e : points.entrySet()) {
double p = e.getValue().getPoints(); double p = e.getValue().getPoints();
if (p >= threshold) { if (p >= threshold) {

View File

@ -12,7 +12,6 @@ import java.io.Writer;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.text.DateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
@ -635,8 +634,6 @@ class NewsFetcher extends UpdateRunner {
} }
Blocklist bl = _context.blocklist(); Blocklist bl = _context.blocklist();
Banlist ban = _context.banlist(); Banlist ban = _context.banlist();
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
String reason = "Blocklist feed " + new Date(ble.updated); String reason = "Blocklist feed " + new Date(ble.updated);
int banned = 0; int banned = 0;
for (Iterator<String> iter = ble.entries.iterator(); iter.hasNext(); ) { for (Iterator<String> iter = ble.entries.iterator(); iter.hasNext(); ) {
@ -764,16 +761,13 @@ class NewsFetcher extends UpdateRunner {
out.write("-->\n"); out.write("-->\n");
if (entries == null) if (entries == null)
return; return;
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
// the router sets the JVM time zone to UTC but saves the original here so we can get it
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
for (NewsEntry e : entries) { for (NewsEntry e : entries) {
if (e.title == null || e.content == null) if (e.title == null || e.content == null)
continue; continue;
Date date = new Date(e.updated); out.write("<!-- Entry Date: " + e.updated + " -->\n");
out.write("<!-- Entry Date: " + date + " -->\n");
out.write("<h3>"); out.write("<h3>");
out.write(fmt.format(date)); // Warning - update NewsHandler.parseNews() if you change the format
out.write(DataHelper.formatDate(e.updated));
out.write(": "); out.write(": ");
out.write(e.title); out.write(e.title);
out.write("</h3>\n"); out.write("</h3>\n");

View File

@ -65,7 +65,7 @@ public class NewsFeedHelper extends HelperBase {
} }
} }
if (!entries.isEmpty()) { if (!entries.isEmpty()) {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat fmt = DateFormat.getDateInstance(DateFormat.MEDIUM);
// the router sets the JVM time zone to UTC but saves the original here so we can get it // the router sets the JVM time zone to UTC but saves the original here so we can get it
fmt.setTimeZone(SystemVersion.getSystemTimeZone(ctx)); fmt.setTimeZone(SystemVersion.getSystemTimeZone(ctx));
int i = 0; int i = 0;

View File

@ -4,8 +4,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.i2p.data.DataHelper; import net.i2p.data.DataHelper;
import net.i2p.router.RouterContext; import net.i2p.router.RouterContext;
@ -201,7 +199,7 @@ public class NewsHelper extends ContentHelper {
/** /**
* Convert long date stamp to * Convert long date stamp to
* '07-Jul 21:09 UTC' with month name in the system locale * date/time in the system locale, local time zone
* @return null if ver = null * @return null if ver = null
* @since 0.9.4 moved from NewsFetcher * @since 0.9.4 moved from NewsFetcher
*/ */
@ -209,7 +207,7 @@ public class NewsHelper extends ContentHelper {
if (ver != null) { if (ver != null) {
try { try {
long modtime = Long.parseLong(ver); long modtime = Long.parseLong(ver);
return (new SimpleDateFormat("dd-MMM HH:mm")).format(new Date(modtime)) + " UTC"; return DataHelper.formatTime(modtime);
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {}
} }
return null; return null;

View File

@ -1,11 +1,9 @@
package net.i2p.router.web.helpers; package net.i2p.router.web.helpers;
import java.text.Collator; import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Properties; import java.util.Properties;
@ -289,7 +287,7 @@ public class ConfigClientsHelper extends HelperBase {
ms = Long.parseLong(s); ms = Long.parseLong(s);
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {}
if (ms > 0) { if (ms > 0) {
String date = (new SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date(ms)); String date = DataHelper.formatTime(ms);
desc.append("<tr><td><b>") desc.append("<tr><td><b>")
.append(_t("Date")).append("</b></td><td>").append(date); .append(_t("Date")).append("</b></td><td>").append(date);
} }

View File

@ -2,12 +2,9 @@ package net.i2p.router.web.helpers;
import java.io.IOException; import java.io.IOException;
import java.text.Collator; import java.text.Collator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -187,17 +184,13 @@ public class EventLogHelper extends FormHandler {
} }
buf.append("</th></tr>"); buf.append("</th></tr>");
SimpleDateFormat fmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
// the router sets the JVM time zone to UTC but saves the original here so we can get it
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
List<Map.Entry<Long, String>> entries = new ArrayList<Map.Entry<Long, String>>(events.entrySet()); List<Map.Entry<Long, String>> entries = new ArrayList<Map.Entry<Long, String>>(events.entrySet());
Collections.reverse(entries); Collections.reverse(entries);
for (Map.Entry<Long, String> e : entries) { for (Map.Entry<Long, String> e : entries) {
long time = e.getKey().longValue(); long time = e.getKey().longValue();
String event = e.getValue(); String event = e.getValue();
buf.append("<tr><td>"); buf.append("<tr><td>");
buf.append(fmt.format(new Date(time))); buf.append(DataHelper.formatTime(time));
buf.append("</td><td>"); buf.append("</td><td>");
if (isAll) { if (isAll) {
String[] s = DataHelper.split(event, " ", 2); String[] s = DataHelper.split(event, " ", 2);

View File

@ -3,9 +3,7 @@ package net.i2p.router.web.helpers;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.text.DateFormat;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -972,9 +970,6 @@ class SummaryBarRenderer {
entries = nmgr.getEntries(); entries = nmgr.getEntries();
} }
if (!entries.isEmpty()) { if (!entries.isEmpty()) {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
// the router sets the JVM time zone to UTC but saves the original here so we can get it
fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
int i = 0; int i = 0;
// show a min of 1, max of 3, none older than 60 days over min // show a min of 1, max of 3, none older than 60 days over min
// Except, if news fetching is disabled, min is 0 and oldest is 7 days. // Except, if news fetching is disabled, min is 0 and oldest is 7 days.
@ -1003,9 +998,8 @@ class SummaryBarRenderer {
.append(consoleNonce) .append(consoleNonce)
.append("\""); .append("\"");
if (entry.updated > 0) { if (entry.updated > 0) {
Date date = new Date(entry.updated);
buf.append(" title=\"") buf.append(" title=\"")
.append(_t("Published")).append(": ").append(fmt.format(date)).append("\""); .append(_t("Published")).append(": ").append(DataHelper.formatDate(entry.updated)).append("\"");
} }
buf.append(">"); buf.append(">");
buf.append(entry.title) buf.append(entry.title)

View File

@ -64,7 +64,6 @@ public class SybilRenderer {
private final RouterContext _context; private final RouterContext _context;
private final Log _log; private final Log _log;
private final DecimalFormat fmt = new DecimalFormat("#0.00"); private final DecimalFormat fmt = new DecimalFormat("#0.00");
private final DateFormat dfmt;
private static final int PAIRMAX = Analysis.PAIRMAX; private static final int PAIRMAX = Analysis.PAIRMAX;
private static final int MAX = Analysis.MAX; private static final int MAX = Analysis.MAX;
@ -76,8 +75,6 @@ public class SybilRenderer {
public SybilRenderer(RouterContext ctx) { public SybilRenderer(RouterContext ctx) {
_context = ctx; _context = ctx;
_log = ctx.logManager().getLog(SybilRenderer.class); _log = ctx.logManager().getLog(SybilRenderer.class);
dfmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
dfmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
} }
/** /**
@ -209,13 +206,13 @@ public class SybilRenderer {
points = ps.load(date); points = ps.load(date);
} catch (IOException ioe) { } catch (IOException ioe) {
_log.error("loading stored analysis for date: " + date, ioe); _log.error("loading stored analysis for date: " + date, ioe);
out.write("<b>Failed to load analysis for " + dfmt.format(new Date(date)) + "</b>: " + out.write("<b>Failed to load analysis for " + DataHelper.formatTime(date) + "</b>: " +
DataHelper.escapeHTML(ioe.toString())); DataHelper.escapeHTML(ioe.toString()));
return; return;
} }
if (points.isEmpty()) { if (points.isEmpty()) {
_log.error("empty stored analysis or bad file format for date: " + date); _log.error("empty stored analysis or bad file format for date: " + date);
out.write("<b>Corrupt analysis file for " + dfmt.format(new Date(date)) + "</b>"); out.write("<b>Corrupt analysis file for " + DataHelper.formatTime(date) + "</b>");
} else { } else {
renderThreatsHTML(out, buf, date, points); renderThreatsHTML(out, buf, date, points);
} }
@ -266,7 +263,7 @@ public class SybilRenderer {
buf.append(" selected=\"selected\""); buf.append(" selected=\"selected\"");
first = false; first = false;
} }
buf.append('>').append(dfmt.format(new Date(date.longValue()))).append("</option>\n"); buf.append('>').append(DataHelper.formatTime(date.longValue())).append("</option>\n");
} }
buf.append("</select>\n" + buf.append("</select>\n" +
"<input type=\"submit\" name=\"action\" class=\"go\" value=\"Review analysis\" />" + "<input type=\"submit\" name=\"action\" class=\"go\" value=\"Review analysis\" />" +
@ -366,7 +363,7 @@ public class SybilRenderer {
buf.append("<div id=\"sybils_summary\">\n" + buf.append("<div id=\"sybils_summary\">\n" +
"<b>Average closest floodfill distance:</b> ").append(fmt.format(avgMinDist)).append("<br>\n" + "<b>Average closest floodfill distance:</b> ").append(fmt.format(avgMinDist)).append("<br>\n" +
"<b>Routing Data:</b> \"").append(DataHelper.getUTF8(_context.routerKeyGenerator().getModData())) "<b>Routing Data:</b> \"").append(DataHelper.getUTF8(_context.routerKeyGenerator().getModData()))
.append("\" <b>Last Changed:</b> ").append(dfmt.format(new Date(_context.routerKeyGenerator().getLastChanged()))).append("<br>\n" + .append("\" <b>Last Changed:</b> ").append(DataHelper.formatTime(_context.routerKeyGenerator().getLastChanged())).append("<br>\n" +
"<b>Next Routing Data:</b> \"").append(DataHelper.getUTF8(_context.routerKeyGenerator().getNextModData())) "<b>Next Routing Data:</b> \"").append(DataHelper.getUTF8(_context.routerKeyGenerator().getNextModData()))
.append("\" <b>Rotates in:</b> ").append(DataHelper.formatDuration(_context.routerKeyGenerator().getTimeTillMidnight())).append("\n" + .append("\" <b>Rotates in:</b> ").append(DataHelper.formatDuration(_context.routerKeyGenerator().getTimeTillMidnight())).append("\n" +
"</div>\n"); "</div>\n");
@ -509,7 +506,7 @@ public class SybilRenderer {
List<Hash> warns = new ArrayList<Hash>(points.keySet()); List<Hash> warns = new ArrayList<Hash>(points.keySet());
Collections.sort(warns, new PointsComparator(points)); Collections.sort(warns, new PointsComparator(points));
ReasonComparator rcomp = new ReasonComparator(); ReasonComparator rcomp = new ReasonComparator();
buf.append("<h3 id=\"threats\" class=\"sybils\">Routers with Most Threat Points as of " + dfmt.format(new Date(date)) + "</h3>"); buf.append("<h3 id=\"threats\" class=\"sybils\">Routers with Most Threat Points as of " + DataHelper.formatTime(date) + "</h3>");
for (Hash h : warns) { for (Hash h : warns) {
Points pp = points.get(h); Points pp = points.get(h);
double p = pp.getPoints(); double p = pp.getPoints();

View File

@ -279,7 +279,7 @@ public class AddressBean
String d = getProp(key); String d = getProp(key);
if (d.length() > 0) { if (d.length() > 0) {
try { try {
d = FormatDate.format(Long.parseLong(d)); d = DataHelper.formatTime(Long.parseLong(d));
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {}
} }
return d; return d;

View File

@ -1,29 +0,0 @@
package i2p.susi.dns;
import java.util.Date;
import java.text.DateFormat;
import net.i2p.util.SystemVersion;
/**
* Format a date in local time zone
* @since 0.8.7
*/
public abstract class FormatDate
{
private static final DateFormat _dateFormat;
static {
DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
// the router sets the JVM time zone to UTC but saves the original here so we can get it
fmt.setTimeZone(SystemVersion.getSystemTimeZone());
_dateFormat = fmt;
}
public static String format(long date)
{
synchronized(_dateFormat) {
return _dateFormat.format(new Date(date));
}
}
}

View File

@ -386,12 +386,10 @@ class Mail {
private static final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private static final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private static final DateFormat localDateFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); private static final DateFormat localDateFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
private static final DateFormat longLocalDateFormatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
static { static {
// the router sets the JVM time zone to UTC but saves the original here so we can get it // the router sets the JVM time zone to UTC but saves the original here so we can get it
TimeZone tz = SystemVersion.getSystemTimeZone(); TimeZone tz = SystemVersion.getSystemTimeZone();
localDateFormatter.setTimeZone(tz); localDateFormatter.setTimeZone(tz);
longLocalDateFormatter.setTimeZone(tz);
} }
/** /**
@ -403,8 +401,8 @@ class Mail {
synchronized(dateFormatter) { synchronized(dateFormatter) {
formattedDate = dateFormatter.format( date ); formattedDate = dateFormatter.format( date );
localFormattedDate = localDateFormatter.format( date ); localFormattedDate = localDateFormatter.format( date );
quotedDate = longLocalDateFormatter.format(date);
} }
quotedDate = DataHelper.formatTime(dateLong);
} }
/** /**

View File

@ -26,6 +26,7 @@ import java.io.PrintWriter;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -107,6 +108,17 @@ public class DataHelper {
private static final Pattern ILLEGAL_KEY = Pattern.compile("[#=\r\n;]"); private static final Pattern ILLEGAL_KEY = Pattern.compile("[#=\r\n;]");
private static final Pattern ILLEGAL_VALUE = Pattern.compile("[#\r\n]"); private static final Pattern ILLEGAL_VALUE = Pattern.compile("[#\r\n]");
/**
* The default formatting for date/time, current locale, local time zone
* @since 0.9.43
*/
private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat TIME_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
static {
DATE_FORMAT.setTimeZone(SystemVersion.getSystemTimeZone());
TIME_FORMAT.setTimeZone(SystemVersion.getSystemTimeZone());
}
/** Read a mapping from the stream, as defined by the I2P data structure spec, /** Read a mapping from the stream, as defined by the I2P data structure spec,
* and store it into a Properties object. * and store it into a Properties object.
* *
@ -1608,6 +1620,34 @@ public class DataHelper {
default: return bytes + space; default: return bytes + space;
} }
} }
/**
* The default formatting for date, current locale, local time zone.
* Warning - NOT UTC!
* Examples:
* en: Aug 30, 2019
* de: 30.08.2019
* @since 0.9.43
*/
public static String formatDate(long now) {
synchronized(DATE_FORMAT) {
return DATE_FORMAT.format(new Date(now));
}
}
/**
* The default formatting for date/time, current locale, local time zone.
* Warning - NOT UTC!
* Examples:
* en: Aug 30, 2019 12:38 PM
* de: 30.08.2019 12:38
* @since 0.9.43
*/
public static String formatTime(long now) {
synchronized(TIME_FORMAT) {
return TIME_FORMAT.format(new Date(now));
}
}
/** /**
* Strip out any HTML (simply removing any less than / greater than symbols) * Strip out any HTML (simply removing any less than / greater than symbols)

View File

@ -5,13 +5,12 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import net.i2p.I2PAppContext; import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import net.i2p.util.I2PThread; import net.i2p.util.I2PThread;
import net.i2p.util.Log; import net.i2p.util.Log;
@ -125,7 +124,6 @@ public class BufferedStatLog implements StatLog {
} }
private class StatLogWriter implements Runnable { private class StatLogWriter implements Runnable {
private final SimpleDateFormat _fmt = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");
public void run() { public void run() {
int writeStart = -1; int writeStart = -1;
int writeEnd = -1; int writeEnd = -1;
@ -162,10 +160,7 @@ public class BufferedStatLog implements StatLog {
int cur = start; int cur = start;
while (cur != end) { while (cur != end) {
//if (shouldLog(_events[cur].getStat())) { //if (shouldLog(_events[cur].getStat())) {
String when = null; String when = DataHelper.formatTime(_events[cur].getTime());
synchronized (_fmt) {
when = _fmt.format(new Date(_events[cur].getTime()));
}
_out.write(when); _out.write(when);
_out.write(" "); _out.write(" ");
if (_events[cur].getScope() == null) if (_events[cur].getScope() == null)

View File

@ -503,7 +503,7 @@ public class LogManager implements Flushable {
return true; return true;
try { try {
SimpleDateFormat fmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); SimpleDateFormat fmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
if (!format.equals("")) if (!format.equals(""))
fmt.applyPattern(format); fmt.applyPattern(format);
// the router sets the JVM time zone to UTC but saves the original here so we can get it // the router sets the JVM time zone to UTC but saves the original here so we can get it
@ -722,9 +722,13 @@ public class LogManager implements Flushable {
_format = fmt; _format = fmt;
} }
/**
* Any usage of returned formatter must be synchronized!
*/
public SimpleDateFormat getDateFormat() { public SimpleDateFormat getDateFormat() {
return _dateFormat; return _dateFormat;
} }
public String getDateFormatPattern() { public String getDateFormatPattern() {
return _dateFormatPattern; return _dateFormatPattern;
} }

View File

@ -12,6 +12,7 @@ package net.i2p.util;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import net.i2p.I2PAppContext; import net.i2p.I2PAppContext;
@ -86,7 +87,11 @@ class LogRecordFormatter {
} }
public static String getWhen(LogManager manager, LogRecord logRecord) { public static String getWhen(LogManager manager, LogRecord logRecord) {
return manager.getDateFormat().format(new Date(logRecord.getDate())); SimpleDateFormat fmt = manager.getDateFormat();
Date d = new Date(logRecord.getDate());
synchronized(fmt) {
return fmt.format(d);
}
} }
/** don't translate */ /** don't translate */

View File

@ -2,7 +2,6 @@ package net.i2p.util;
import java.io.IOException; import java.io.IOException;
import java.net.Socket; import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
/** /**
@ -75,19 +74,16 @@ public class SocketTimeout extends SimpleTimer2.TimedEvent {
public void setTimeoutCommand(Runnable job) { _command = job; } public void setTimeoutCommand(Runnable job) { _command = job; }
private static final SimpleDateFormat _fmt = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS");
private static String ts(long when) { synchronized (_fmt) { return _fmt.format(new Date(when)); } }
@Override @Override
public String toString() { public String toString() {
StringBuilder buf = new StringBuilder(); StringBuilder buf = new StringBuilder();
buf.append("SocketTimeout started on "); buf.append("SocketTimeout started on ");
buf.append(ts(_startTime)); buf.append(new Date(_startTime));
buf.append(" idle for "); buf.append(" idle for ");
buf.append(System.currentTimeMillis() - _lastActivity); buf.append(System.currentTimeMillis() - _lastActivity);
buf.append("ms "); buf.append("ms ");
if (_totalTimeoutTime > 0) if (_totalTimeoutTime > 0)
buf.append("total timeout at ").append(ts(_totalTimeoutTime)); buf.append("total timeout at ").append(new Date(_totalTimeoutTime));
buf.append("cancelled? ").append(_cancelled); buf.append("cancelled? ").append(_cancelled);
return buf.toString(); return buf.toString();
} }

View File

@ -136,7 +136,7 @@ wrapper.app.parameter.1=net.i2p.router.Router
#******************************************************************** #********************************************************************
# Enables Debug output from the Wrapper. # Enables Debug output from the Wrapper.
# wrapper.debug=TRUE # wrapper.debug=TRUE
# Format of output for the console. (See docs for formats) # Format of output for the console. See below or https://wrapper.tanukisoftware.com/doc/english/prop-logfile-format.html
wrapper.console.format=PM wrapper.console.format=PM
# Log Level for console output. (See docs for log levels) # Log Level for console output. (See docs for log levels)

View File

@ -67,7 +67,7 @@ public class DatabaseInfo {
public static final int NETSPEED_EDITION_REV1 = 32; public static final int NETSPEED_EDITION_REV1 = 32;
public static final int NETSPEED_EDITION_REV1_V6 = 33; public static final int NETSPEED_EDITION_REV1_V6 = 33;
private static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
private String info; private String info;

View File

@ -3,7 +3,6 @@ package net.i2p.router;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Queue; import java.util.Queue;
@ -52,13 +51,9 @@ public class MessageHistory {
public final static String PROP_MESSAGE_HISTORY_FILENAME = "router.historyFilename"; public final static String PROP_MESSAGE_HISTORY_FILENAME = "router.historyFilename";
public final static String DEFAULT_MESSAGE_HISTORY_FILENAME = "messageHistory.txt"; public final static String DEFAULT_MESSAGE_HISTORY_FILENAME = "messageHistory.txt";
private final SimpleDateFormat _fmt;
public MessageHistory(RouterContext context) { public MessageHistory(RouterContext context) {
_context = context; _context = context;
_log = context.logManager().getLog(getClass()); _log = context.logManager().getLog(getClass());
_fmt = new SimpleDateFormat("yy/MM/dd.HH:mm:ss.SSS");
_fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
_unwrittenEntries = new LinkedBlockingQueue<String>(); _unwrittenEntries = new LinkedBlockingQueue<String>();
_reinitializeJob = new ReinitializeJob(); _reinitializeJob = new ReinitializeJob();
_writeJob = new WriteJob(); _writeJob = new WriteJob();
@ -601,9 +596,7 @@ public class MessageHistory {
} }
private final String getTime(long when) { private final String getTime(long when) {
synchronized (_fmt) { return DataHelper.formatTime(when);
return _fmt.format(new Date(when));
}
} }
/** /**

View File

@ -8,7 +8,6 @@ package net.i2p.router;
* *
*/ */
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
@ -417,18 +416,10 @@ public class OutNetMessage implements CDPQEntry {
else else
buf.append(0); buf.append(0);
buf.append("ms: \t").append(name); buf.append("ms: \t").append(name);
buf.append('=').append(formatDate(when.longValue())); buf.append('=').append(new Date(when.longValue()));
buf.append("]\n"); buf.append("]\n");
lastWhen = when.longValue(); lastWhen = when.longValue();
} }
} }
} }
private final static SimpleDateFormat _fmt = new SimpleDateFormat("HH:mm:ss.SSS");
private final static String formatDate(long when) {
Date d = new Date(when);
synchronized (_fmt) {
return _fmt.format(d);
}
}
} }

View File

@ -1,5 +1,7 @@
package net.i2p.router.tunnel; package net.i2p.router.tunnel;
import java.util.Date;
import net.i2p.data.DataHelper; import net.i2p.data.DataHelper;
import net.i2p.data.Hash; import net.i2p.data.Hash;
import net.i2p.data.SessionKey; import net.i2p.data.SessionKey;
@ -188,7 +190,7 @@ public class HopConfig {
buf.append(DataHelper.fromLong(_sendTunnelId, 0, 4)); buf.append(DataHelper.fromLong(_sendTunnelId, 0, 4));
} }
buf.append(" exp. ").append(TunnelCreatorConfig.format(_expiration)); buf.append(" exp. ").append(new Date(_expiration));
int messagesProcessed = getProcessedMessagesCount(); int messagesProcessed = getProcessedMessagesCount();
if (messagesProcessed > 0) if (messagesProcessed > 0)
buf.append(" used ").append(messagesProcessed).append("KB"); buf.append(" used ").append(messagesProcessed).append("KB");

View File

@ -1,9 +1,7 @@
package net.i2p.router.tunnel; package net.i2p.router.tunnel;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Properties; import java.util.Properties;
import net.i2p.data.Base64; import net.i2p.data.Base64;
@ -43,7 +41,6 @@ public abstract class TunnelCreatorConfig implements TunnelInfo {
private long _peakThroughputLastCoallesce = System.currentTimeMillis(); private long _peakThroughputLastCoallesce = System.currentTimeMillis();
// Make configurable? - but can't easily get to pool options from here // Make configurable? - but can't easily get to pool options from here
private static final int MAX_CONSECUTIVE_TEST_FAILURES = 3; private static final int MAX_CONSECUTIVE_TEST_FAILURES = 3;
private static final SimpleDateFormat _fmt = new SimpleDateFormat("HH:mm:ss", Locale.UK);
/** /**
* For exploratory only (null destination) * For exploratory only (null destination)
@ -269,7 +266,7 @@ public abstract class TunnelCreatorConfig implements TunnelInfo {
buf.append("-->"); buf.append("-->");
} }
buf.append(" exp. ").append(getExpirationString()); buf.append(" exp. ").append(new Date(_expiration));
if (_replyMessageId > 0) if (_replyMessageId > 0)
buf.append(" replyMsgID ").append(_replyMessageId); buf.append(" replyMsgID ").append(_replyMessageId);
if (_messagesProcessed > 0) if (_messagesProcessed > 0)
@ -279,15 +276,4 @@ public abstract class TunnelCreatorConfig implements TunnelInfo {
buf.append(" with ").append(_failures).append(" failures"); buf.append(" with ").append(_failures).append(" failures");
return buf.toString(); return buf.toString();
} }
private String getExpirationString() {
return format(_expiration);
}
static String format(long date) {
Date d = new Date(date);
synchronized (_fmt) {
return _fmt.format(d);
}
}
} }