提交 02522d25 编写于 作者: S silent-snowman 提交者: Oleg Nenashev

[JENKINS-19887] - Allow time zone to be set on a per user basis (#4113)

* Implement user setting for timezone

* Apply timezone everywhere

* Revert to medium dateStyle

* Simplify and cleanup

* Add javadocs and fix file headers

* Revert auto-changes by IntelliJ

* Add nullable annotation

* Use better display names

* Add tests

* Log a warning when the user's time zone is not valid

* Add username to log statement

* Make suggested change

* Cleaner way of dealing with invalid timezone

* Update core/src/main/resources/hudson/model/TimeZoneProperty/config.jelly
Co-Authored-By: NMatt Sicker <boards@gmail.com>

* Update tests

* Update config.properties

* Update config.jelly

* Update Functions.java

* Update layout.jelly

* Update Functions.java

* Update TimeZoneProperty.java

* Update TimeZoneProperty.java

* Update config.jelly

* Update config.properties

* Update TimeZonePropertyTest.java

* Update TimeZoneProperty.java

* Update Functions.java
上级 e5ba39e3
......@@ -53,6 +53,7 @@ import hudson.model.PaneStatusProperties;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterDefinition.ParameterDescriptor;
import hudson.model.Run;
import hudson.model.TimeZoneProperty;
import hudson.model.TopLevelItem;
import hudson.model.User;
import hudson.model.View;
......@@ -117,6 +118,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.LogManager;
......@@ -676,7 +678,28 @@ public class Functions {
public static boolean isCollapsed(String paneId) {
return PaneStatusProperties.forCurrentUser().isCollapsed(paneId);
}
@Restricted(NoExternalUse.class)
public static boolean isUserTimeZoneOverride() {
return TimeZoneProperty.forCurrentUser() != null;
}
@CheckForNull
@Restricted(NoExternalUse.class)
public static String getUserTimeZone() {
return TimeZoneProperty.forCurrentUser();
}
@Restricted(NoExternalUse.class)
public static String getUserTimeZonePostfix() {
if (!isUserTimeZoneOverride()) {
return "";
}
TimeZone tz = TimeZone.getTimeZone(getUserTimeZone());
return tz.getDisplayName(tz.observesDaylightTime(), TimeZone.SHORT);
}
/**
* Finds the given object in the ancestor list and returns its URL.
* This is used to determine the "current" URL assigned to the given object,
......
package hudson.model;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.ListBoxModel.Option;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.TimeZone;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* A UserProperty that allows a user to specify a time zone for displaying time.
*/
@Restricted(NoExternalUse.class)
public class TimeZoneProperty extends UserProperty implements Saveable {
/**
* Time Zone ID defined by the user.
* {@code null} means that the time zone is not defined.
*/
@CheckForNull
private String timeZoneName;
private static final Logger LOGGER = Logger.getLogger(TimeZoneProperty.class.getName());
@DataBoundConstructor
public TimeZoneProperty(@CheckForNull String timeZoneName) {
this.timeZoneName = timeZoneName;
}
private TimeZoneProperty() {
this(null);
}
@Override
public void save() throws IOException {
user.save();
}
public void setTimeZoneName(@CheckForNull String timeZoneName) {
this.timeZoneName = timeZoneName;
}
@Extension
@Symbol("timezone")
public static class DescriptorImpl extends UserPropertyDescriptor {
@Override
public String getDisplayName() {
return Messages.TimeZoneProperty_DisplayName();
}
@Override
public UserProperty newInstance(User user) {
return new TimeZoneProperty();
}
@Override
public synchronized void load() {
super.load();
}
@Override
public synchronized void save() {
super.save();
}
@Override
public boolean isEnabled() {
return true;
}
public ListBoxModel doFillTimeZoneNameItems() {
String current = forCurrentUser();
ListBoxModel items = new ListBoxModel();
items.add(Messages.TimeZoneProperty_DisplayDefaultTimeZone(), "");
for (String id : TimeZone.getAvailableIDs()) {
if (id.equalsIgnoreCase(current)) {
items.add(new Option(id, id, true));
} else {
items.add(id);
}
}
return items;
}
}
@Nullable
public static String forCurrentUser() {
final User current = User.current();
if (current == null) {
return null;
}
TimeZoneProperty tzp = current.getProperty(TimeZoneProperty.class);
if(tzp.timeZoneName == null || tzp.timeZoneName.isEmpty()) {
return null;
}
TimeZone tz = TimeZone.getTimeZone(tzp.timeZoneName);
if (tz.getID() != tzp.timeZoneName) {
//TimeZone.getTimeZone returns GMT on invalid time zone so
//warn the user if the time zone returned is different from
//the one they specified.
LOGGER.log(Level.WARNING, "Invalid user time zone {0} for {1}", new Object[]{tzp.timeZoneName, current.getId()});
return null;
}
return tz.getID();
}
}
......@@ -394,3 +394,6 @@ Jenkins.IsRestarting=Jenkins is restarting
User.IllegalUsername="{0}" is prohibited as a username for security reasons.
User.IllegalFullname="{0}" is prohibited as a full name for security reasons.
TimeZoneProperty.DisplayName=User Defined Time Zone
TimeZoneProperty.DisplayDefaultTimeZone=Default
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
<f:entry field="timeZoneName" title="${%title}">
<f:select />
</f:entry>
</j:jelly>
# The MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
title=Time Zone
description=Specify user defined time zone for displaying time rather than system default.
......@@ -41,7 +41,7 @@ THE SOFTWARE.
</div>
<div class="pane build-details" time="${build.timestamp.time.time}">
<a class="tip model-link inside build-link" href="${link}" update-parent-class=".build-row">
<i:formatDate value="${build.timestamp.time}" type="both" dateStyle="medium" timeStyle="short" />
<i:formatDate value="${build.timestamp.time}" type="both" dateStyle="medium" timeStyle="short" /> ${h.getUserTimeZonePostfix()}
</a>
<j:if test="${build.building}">
<j:set target="${it.widget}" property="nextBuildNumberToFetch" value="${build.number}"/>
......
......@@ -69,6 +69,9 @@ THE SOFTWARE.
which I suspect can end up creating sessions for wrong resource types (such as static resources.)
-->
<j:if test="${h.isUserTimeZoneOverride()}">
<i:setTimeZone value="${h.getUserTimeZone()}" />
</j:if>
<j:if test="${attrs.type==null}">
<j:set var="layoutType" value="two-column"/>
</j:if>
......
package hudson.model;
import org.acegisecurity.context.SecurityContextHolder;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Test cases for TimeZoneProperty
*/
public class TimeZonePropertyTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void testEnsureTimeZoneIsNullByDefault() {
String timeZone = TimeZoneProperty.forCurrentUser();
assertNull(timeZone);
}
@Test
public void testEnsureInvalidTimeZoneDefaultsToNull() throws IOException {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
User user = User.get("John Smith", true, java.util.Collections.emptyMap());
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
TimeZoneProperty tzp = new TimeZoneProperty("InvalidTimeZoneName");
user.addProperty(tzp);
assertEquals(null, TimeZoneProperty.forCurrentUser());
}
@Test
public void testSetUserDefinedTimeZone() throws IOException {
String timeZone = TimeZone.getDefault().getID();
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
User user = User.get("John Smith", true, java.util.Collections.emptyMap());
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
assertEquals(null, TimeZoneProperty.forCurrentUser());
TimeZoneProperty tzp = new TimeZoneProperty(timeZone);
user.addProperty(tzp);
assertEquals(TimeZone.getDefault().getID(), TimeZoneProperty.forCurrentUser());
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册