Implemented a TimeZone setting

TimeZone setting accepts 'GMT+2', 'GMT-05:30', 'UTC' and 'server'

Accidentally discovered a bug where first boot used UTC when default was
supposed to be server timezone. The bug was fixed by removing
PlanConfig#getTimeZone calls in different constructors.

Affects issues:
- Close #718
This commit is contained in:
Rsl1122 2019-12-07 13:00:07 +02:00
parent a50576e6e9
commit 10411c0626
15 changed files with 205 additions and 46 deletions

View File

@ -20,7 +20,6 @@ import com.djrapitops.plan.delivery.formatting.Formatter;
import com.djrapitops.plan.settings.config.PlanConfig;
import com.djrapitops.plan.settings.config.paths.FormatSettings;
import com.djrapitops.plan.settings.config.paths.PluginSettings;
import com.djrapitops.plan.settings.config.paths.TimeSettings;
import com.djrapitops.plan.settings.locale.Locale;
import com.djrapitops.plan.settings.locale.lang.GenericLang;
@ -47,13 +46,12 @@ public abstract class DateFormatter implements Formatter<Long> {
public abstract String apply(Long value);
protected String format(long epochMs, String format) {
boolean useServerTime = config.isTrue(TimeSettings.USE_SERVER_TIME);
String localeSetting = config.get(PluginSettings.LOCALE);
java.util.Locale usedLocale = "default".equalsIgnoreCase(localeSetting)
? java.util.Locale.ENGLISH
: java.util.Locale.forLanguageTag(localeSetting);
SimpleDateFormat dateFormat = new SimpleDateFormat(format, usedLocale);
TimeZone timeZone = useServerTime ? TimeZone.getDefault() : TimeZone.getTimeZone("GMT");
TimeZone timeZone = config.getTimeZone();
dateFormat.setTimeZone(timeZone);
return dateFormat.format(epochMs);
}
@ -65,8 +63,7 @@ public abstract class DateFormatter implements Formatter<Long> {
protected String replaceRecentDays(long epochMs, String format, String pattern) {
long now = System.currentTimeMillis();
boolean useServerTime = config.isTrue(TimeSettings.USE_SERVER_TIME);
TimeZone timeZone = useServerTime ? TimeZone.getDefault() : TimeZone.getTimeZone("GMT");
TimeZone timeZone = config.getTimeZone();
int offset = timeZone.getOffset(epochMs);
// Time since Start of day: UTC + Timezone % 24 hours

View File

@ -37,7 +37,10 @@ import com.djrapitops.plan.storage.database.queries.objects.UserInfoQueries;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
@ -54,7 +57,6 @@ public class OnlineActivityOverviewJSONCreator implements ServerTabJSONCreator<M
private final Formatter<Long> timeAmountFormatter;
private final Formatter<Double> decimalFormatter;
private final Formatter<Double> percentageFormatter;
private final TimeZone timeZone;
@Inject
public OnlineActivityOverviewJSONCreator(
@ -68,7 +70,6 @@ public class OnlineActivityOverviewJSONCreator implements ServerTabJSONCreator<M
timeAmountFormatter = formatters.timeAmount();
decimalFormatter = formatters.decimals();
percentageFormatter = formatters.percentage();
this.timeZone = config.getTimeZone();
}
public Map<String, Object> createJSONAsMap(UUID serverUUID) {
@ -85,7 +86,7 @@ public class OnlineActivityOverviewJSONCreator implements ServerTabJSONCreator<M
long weekAgo = now - TimeUnit.DAYS.toMillis(7L);
long halfMonthAgo = now - TimeUnit.DAYS.toMillis(15L);
long monthAgo = now - TimeUnit.DAYS.toMillis(30L);
int timeZoneOffset = timeZone.getOffset(now);
int timeZoneOffset = config.getTimeZone().getOffset(now);
Long playThreshold = config.get(TimeSettings.ACTIVE_PLAY_THRESHOLD);
Map<String, Object> numbers = new HashMap<>();

View File

@ -39,7 +39,10 @@ import com.djrapitops.plan.storage.database.queries.objects.TPSQueries;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
@ -60,7 +63,6 @@ public class ServerOverviewJSONCreator implements ServerTabJSONCreator<Map<Strin
private final Formatter<Double> decimals;
private final Formatter<Double> percentage;
private final Formatter<DateHolder> year;
private final TimeZone timeZone;
@Inject
public ServerOverviewJSONCreator(
@ -80,7 +82,6 @@ public class ServerOverviewJSONCreator implements ServerTabJSONCreator<Map<Strin
timeAmount = formatters.timeAmount();
decimals = formatters.decimals();
percentage = formatters.percentage();
this.timeZone = config.getTimeZone();
}
public Map<String, Object> createJSONAsMap(UUID serverUUID) {
@ -99,7 +100,7 @@ public class ServerOverviewJSONCreator implements ServerTabJSONCreator<Map<Strin
Map<String, Object> sevenDays = new HashMap<>();
sevenDays.put("unique_players", db.query(PlayerCountQueries.uniquePlayerCount(weekAgo, now, serverUUID)));
sevenDays.put("unique_players_day", db.query(PlayerCountQueries.averageUniquePlayerCount(weekAgo, now, timeZone.getOffset(now), serverUUID)));
sevenDays.put("unique_players_day", db.query(PlayerCountQueries.averageUniquePlayerCount(weekAgo, now, config.getTimeZone().getOffset(now), serverUUID)));
int new7d = db.query(PlayerCountQueries.newPlayerCount(weekAgo, now, serverUUID));
int retained7d = db.query(PlayerCountQueries.retainedPlayerCount(weekAgo, now, serverUUID));

View File

@ -61,7 +61,6 @@ public class GraphJSONCreator {
private final Theme theme;
private final DBSystem dbSystem;
private final Graphs graphs;
private final TimeZone timeZone;
@Inject
public GraphJSONCreator(
@ -74,7 +73,6 @@ public class GraphJSONCreator {
this.theme = theme;
this.dbSystem = dbSystem;
this.graphs = graphs;
this.timeZone = config.getTimeZone();
}
public String performanceGraphJSON(UUID serverUUID) {
@ -111,11 +109,12 @@ public class GraphJSONCreator {
LineGraphFactory lineGraphs = graphs.line();
long now = System.currentTimeMillis();
long halfYearAgo = now - TimeUnit.DAYS.toMillis(180L);
int timeZoneOffset = config.getTimeZone().getOffset(now);
NavigableMap<Long, Integer> uniquePerDay = db.query(
PlayerCountQueries.uniquePlayerCounts(halfYearAgo, now, timeZone.getOffset(now), serverUUID)
PlayerCountQueries.uniquePlayerCounts(halfYearAgo, now, timeZoneOffset, serverUUID)
);
NavigableMap<Long, Integer> newPerDay = db.query(
PlayerCountQueries.newPlayerCounts(halfYearAgo, now, timeZone.getOffset(now), serverUUID)
PlayerCountQueries.newPlayerCounts(halfYearAgo, now, timeZoneOffset, serverUUID)
);
return "{\"uniquePlayers\":" +
@ -134,11 +133,12 @@ public class GraphJSONCreator {
LineGraphFactory lineGraphs = graphs.line();
long now = System.currentTimeMillis();
long halfYearAgo = now - TimeUnit.DAYS.toMillis(180L);
int timeZoneOffset = config.getTimeZone().getOffset(now);
NavigableMap<Long, Integer> uniquePerDay = db.query(
PlayerCountQueries.uniquePlayerCounts(halfYearAgo, now, timeZone.getOffset(now))
PlayerCountQueries.uniquePlayerCounts(halfYearAgo, now, timeZoneOffset)
);
NavigableMap<Long, Integer> newPerDay = db.query(
PlayerCountQueries.newPlayerCounts(halfYearAgo, now, timeZone.getOffset(now))
PlayerCountQueries.newPlayerCounts(halfYearAgo, now, timeZoneOffset)
);
return "{\"uniquePlayers\":" +
@ -156,17 +156,18 @@ public class GraphJSONCreator {
Database db = dbSystem.getDatabase();
long now = System.currentTimeMillis();
long twoYearsAgo = now - TimeUnit.DAYS.toMillis(730L);
int timeZoneOffset = config.getTimeZone().getOffset(now);
NavigableMap<Long, Integer> uniquePerDay = db.query(
PlayerCountQueries.uniquePlayerCounts(twoYearsAgo, now, timeZone.getOffset(now), serverUUID)
PlayerCountQueries.uniquePlayerCounts(twoYearsAgo, now, timeZoneOffset, serverUUID)
);
NavigableMap<Long, Integer> newPerDay = db.query(
PlayerCountQueries.newPlayerCounts(twoYearsAgo, now, timeZone.getOffset(now), serverUUID)
PlayerCountQueries.newPlayerCounts(twoYearsAgo, now, timeZoneOffset, serverUUID)
);
NavigableMap<Long, Long> playtimePerDay = db.query(
SessionQueries.playtimePerDay(twoYearsAgo, now, timeZone.getOffset(now), serverUUID)
SessionQueries.playtimePerDay(twoYearsAgo, now, timeZoneOffset, serverUUID)
);
NavigableMap<Long, Integer> sessionsPerDay = db.query(
SessionQueries.sessionCountPerDay(twoYearsAgo, now, timeZone.getOffset(now), serverUUID)
SessionQueries.sessionCountPerDay(twoYearsAgo, now, timeZoneOffset, serverUUID)
);
return "{\"data\":" +
graphs.calendar().serverCalendar(

View File

@ -89,9 +89,9 @@ public class ServerPage implements Page {
placeholders.put("serverName", server.getIdentifiableName());
placeholders.put("serverDisplayName", server.getName());
DataContainer constants = new RawDataContainer();
constants.putRawData(AnalysisKeys.TIME_ZONE, config.getTimeZoneOffsetHours());
placeholders.put("timeZone", config.getTimeZoneOffsetHours());
DataContainer constants = new RawDataContainer();
// TODO Move these graph settings to the graph requests instead of placeholders
constants.putRawData(AnalysisKeys.FIRST_DAY, 1);
constants.putRawData(AnalysisKeys.TPS_MEDIUM, config.get(DisplaySettings.GRAPH_TPS_THRESHOLD_MED));
@ -112,7 +112,6 @@ public class ServerPage implements Page {
constants.putRawData(AnalysisKeys.MIN_PING_COLOR, theme.getValue(ThemeVal.GRAPH_MIN_PING));
placeholders.addAllPlaceholdersFrom(constants,
TIME_ZONE,
FIRST_DAY, TPS_MEDIUM, TPS_HIGH,
DISK_MEDIUM, DISK_HIGH,
PLAYERS_MAX, PLAYERS_ONLINE, PLAYERS_TOTAL,

View File

@ -19,6 +19,8 @@ package com.djrapitops.plan.settings;
import com.djrapitops.plan.SubSystem;
import com.djrapitops.plan.exceptions.EnableException;
import com.djrapitops.plan.settings.config.PlanConfig;
import com.djrapitops.plan.settings.config.TimeZoneUtility;
import com.djrapitops.plan.settings.config.paths.FormatSettings;
import com.djrapitops.plan.settings.config.paths.PluginSettings;
import com.djrapitops.plan.settings.theme.Theme;
import com.djrapitops.plan.storage.file.PlanFiles;
@ -30,9 +32,7 @@ import com.djrapitops.plugin.utilities.Verify;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.*;
/**
* System for Config and other user customizable options.
@ -83,6 +83,8 @@ public abstract class ConfigSystem implements SubSystem {
if (logger.getDebugLogger() instanceof CombineDebugLogger) {
setDebugMode();
}
checkWrongTimeZone();
} catch (IOException e) {
errorHandler.log(L.ERROR, this.getClass(), e);
throw new EnableException("Failed to save default config: " + e.getMessage(), e);
@ -90,6 +92,14 @@ public abstract class ConfigSystem implements SubSystem {
theme.enable();
}
public void checkWrongTimeZone() {
String timeZone = config.getString(FormatSettings.TIMEZONE);
Optional<TimeZone> foundTZ = TimeZoneUtility.parseTimeZone(timeZone);
if (!foundTZ.isPresent()) {
logger.warn("Config: " + FormatSettings.TIMEZONE.getPath() + " has invalid value '" + timeZone + "', using GMT+0");
}
}
private void setDebugMode() {
CombineDebugLogger debugLogger = (CombineDebugLogger) logger.getDebugLogger();

View File

@ -16,7 +16,7 @@
*/
package com.djrapitops.plan.settings.config;
import com.djrapitops.plan.settings.config.paths.TimeSettings;
import com.djrapitops.plan.settings.config.paths.FormatSettings;
import com.djrapitops.plan.settings.config.paths.key.Setting;
import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.utilities.Verify;
@ -25,8 +25,10 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.time.ZoneId;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
@ -56,15 +58,6 @@ public class PlanConfig extends Config {
extensionSettings = new ExtensionSettings(this);
}
public int getTimeZoneOffsetHours() {
if (isTrue(TimeSettings.USE_SERVER_TIME)) {
int offset = TimeZone.getDefault().getOffset(System.currentTimeMillis());
int hourMs = (int) TimeUnit.HOURS.toMillis(1L);
return -offset / hourMs;
}
return 0; // UTC
}
public <T> T get(Setting<T> setting) {
T value = setting.getValueFrom(this);
Verify.isTrue(setting.isValid(value), () -> new IllegalStateException(
@ -121,7 +114,15 @@ public class PlanConfig extends Config {
}
public TimeZone getTimeZone() {
return get(TimeSettings.USE_SERVER_TIME) ? TimeZone.getDefault() : TimeZone.getTimeZone("GMT");
String timeZone = getString(FormatSettings.TIMEZONE);
Optional<TimeZone> foundTZ = TimeZoneUtility.parseTimeZone(timeZone);
return foundTZ.orElse(TimeZone.getTimeZone(ZoneId.of("UTC")));
}
public int getTimeZoneOffsetHours() {
int offset = getTimeZone().getOffset(System.currentTimeMillis());
int hourMs = (int) TimeUnit.HOURS.toMillis(1L);
return -offset / hourMs;
}
public ExtensionSettings getExtensionSettings() {

View File

@ -0,0 +1,42 @@
/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.settings.config;
import java.time.DateTimeException;
import java.time.ZoneId;
import java.util.Optional;
import java.util.TimeZone;
/**
* Utility for getting a {@link java.util.TimeZone} from Plan {@link com.djrapitops.plan.settings.config.paths.FormatSettings#TIMEZONE} value.
*
* @author Rsl1122
*/
public class TimeZoneUtility {
public static Optional<TimeZone> parseTimeZone(String value) {
if ("server".equalsIgnoreCase(value)) return Optional.of(TimeZone.getDefault());
try {
ZoneId zoneId = ZoneId.of(value);
return Optional.of(TimeZone.getTimeZone(zoneId));
} catch (DateTimeException notFound) {
return Optional.empty();
}
}
}

View File

@ -125,4 +125,36 @@ public interface ConfigChange {
return "Removed Comment from " + path;
}
}
class BooleanToString implements ConfigChange {
private final String oldPath;
private final String newPath;
private final String valueIfTrue;
private final String valueIfFalse;
public BooleanToString(String oldPath, String newPath, String valueIfTrue, String valueIfFalse) {
this.oldPath = oldPath;
this.newPath = newPath;
this.valueIfTrue = valueIfTrue;
this.valueIfFalse = valueIfFalse;
}
@Override
public boolean hasBeenApplied(Config config) {
Optional<ConfigNode> oldNode = config.getNode(oldPath);
return !oldNode.isPresent();
}
@Override
public void apply(Config config) {
boolean oldValue = config.getBoolean(oldPath);
config.set(newPath, oldValue ? valueIfTrue : valueIfFalse);
config.removeNode(oldPath);
}
@Override
public String getAppliedMessage() {
return "Moved " + oldPath + " to " + newPath + " and turned Boolean to String.";
}
}
}

View File

@ -17,6 +17,7 @@
package com.djrapitops.plan.settings.config.changes;
import com.djrapitops.plan.settings.config.Config;
import com.djrapitops.plan.settings.config.paths.FormatSettings;
import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler;
@ -139,6 +140,7 @@ public class ConfigUpdater {
new ConfigChange.Moved("Plugins.BuyCraft", "Plugins.Buycraft"),
new ConfigChange.Moved("Plugin.Configuration.Allow_bungeecord_to_manage_settings", "Plugin.Configuration.Allow_proxy_to_manage_settings"),
new ConfigChange.RemovedComment("Webserver.Disable_Webserver"),
new ConfigChange.BooleanToString("Time.Use_server_timezone", FormatSettings.TIMEZONE.getPath(), "server", "UTC"),
};
}

View File

@ -33,6 +33,7 @@ public class FormatSettings {
public static final Setting<String> DATE_FULL = new StringSetting("Formatting.Dates.Full");
public static final Setting<String> DATE_NO_SECONDS = new StringSetting("Formatting.Dates.NoSeconds");
public static final Setting<String> DATE_CLOCK = new StringSetting("Formatting.Dates.JustClock");
public static final Setting<String> TIMEZONE = new StringSetting("Formatting.Dates.TimeZone");
public static final Setting<String> YEAR = new StringSetting("Formatting.Time_amount.Year");
public static final Setting<String> YEARS = new StringSetting("Formatting.Time_amount.Years");
public static final Setting<String> MONTH = new StringSetting("Formatting.Time_amount.Month");

View File

@ -16,7 +16,6 @@
*/
package com.djrapitops.plan.settings.config.paths;
import com.djrapitops.plan.settings.config.paths.key.BooleanSetting;
import com.djrapitops.plan.settings.config.paths.key.Setting;
import com.djrapitops.plan.settings.config.paths.key.TimeSetting;
@ -27,7 +26,6 @@ import com.djrapitops.plan.settings.config.paths.key.TimeSetting;
*/
public class TimeSettings {
public static final Setting<Boolean> USE_SERVER_TIME = new BooleanSetting("Time.Use_server_timezone");
public static final Setting<Long> PING_SERVER_ENABLE_DELAY = new TimeSetting("Time.Delays.Ping_server_enable_delay");
public static final Setting<Long> PING_PLAYER_LOGIN_DELAY = new TimeSetting("Time.Delays.Ping_player_join_delay");
public static final Setting<Long> DB_TRANSACTION_FINISH_WAIT_DELAY = new TimeSetting("Time.Delays.Wait_for_DB_Transactions_on_disable");

View File

@ -60,8 +60,6 @@ Data_gathering:
# Supported time units: MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS
# -----------------------------------------------------
Time:
# UTC used if false. Only affects Timestamps and graphs.
Use_server_timezone: true
Delays:
Ping_server_enable_delay: 300
Unit: SECONDS
@ -146,6 +144,9 @@ Formatting:
Full: 'MMM d YYYY, HH:mm:ss'
NoSeconds: 'MMM d YYYY, HH:mm'
JustClock: 'HH:mm:ss'
# TimeZone Option uses format 'GMT+2' or 'GMT-04:30'
# Other valid options are 'server' and 'UTC'
TimeZone: 'server'
# -----------------------------------------------------
# World aliases can be used to rename worlds and to combine multiple worlds into a group.
# -----------------------------------------------------

View File

@ -65,8 +65,6 @@ Data_gathering:
# Supported time units: MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS
# -----------------------------------------------------
Time:
# UTC used if false. Only affects Timestamps and graphs.
Use_server_timezone: true
Delays:
Ping_server_enable_delay: 300
Unit: SECONDS
@ -151,6 +149,9 @@ Formatting:
Full: 'MMM d YYYY, HH:mm:ss'
NoSeconds: 'MMM d YYYY, HH:mm'
JustClock: HH:mm:ss
# TimeZone Option uses format 'GMT+2' or 'GMT-04:30'
# Other valid options are 'server' and 'UTC'
TimeZone: 'server'
# -----------------------------------------------------
# World aliases can be used to rename worlds and to combine multiple worlds into a group.
# -----------------------------------------------------

View File

@ -0,0 +1,72 @@
/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.settings.config;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import java.time.ZoneId;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Sanity Test for different timezones.
*
* @author Rsl1122
*/
@RunWith(JUnitPlatform.class)
class TimeZoneUtilityTest {
@Test
void utcIsValidZoneID() {
ZoneId zone = ZoneId.of("UTC");
assertNotNull(zone);
}
@Test
void gmtPlusIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT+3");
assertNotNull(zone);
}
@Test
void gmtMinusIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT-3");
assertNotNull(zone);
}
@Test
void gmtPlusMinutesIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT+03:30");
assertNotNull(zone);
}
@Test
void gmtMinusMinutesIsValidZoneID() {
ZoneId zone = ZoneId.of("GMT-03:30");
assertNotNull(zone);
}
@Test
void serverReturnsServerTimeZone() {
assertEquals(TimeZone.getDefault(), TimeZoneUtility.parseTimeZone("server"));
}
}