Skip to content
This repository has been archived by the owner on Jan 8, 2020. It is now read-only.

Commit

Permalink
TemplateDateFormat.isTimeZoneBound support + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ddekany committed Aug 31, 2015
1 parent 8b72f8b commit de5152e
Show file tree
Hide file tree
Showing 8 changed files with 209 additions and 9 deletions.
7 changes: 5 additions & 2 deletions src/main/java/freemarker/core/Environment.java
Original file line number Diff line number Diff line change
Expand Up @@ -845,7 +845,10 @@ public void setTimeZone(TimeZone timeZone) {
if (!timeZone.equals(prevTimeZone)) {
if (cachedTempDateFormatArray != null) {
for (int i = 0; i < CACHED_TDFS_SQL_D_T_TZ_OFFS; i++) {
cachedTempDateFormatArray[i] = null;
TemplateDateFormat f = cachedTempDateFormatArray[i];
if (f != null && f.isTimeZoneBound()) {
cachedTempDateFormatArray[i] = null;
}
}
}
if (cachedTempDateFormatsByFmtStrArray != null) {
Expand Down Expand Up @@ -1444,7 +1447,7 @@ private TemplateDateFormat getTemplateDateFormat(
}
return format;
} catch (InvalidFormatStringException e) {
throw new _TemplateModelException(e.getCause(),
throw new _TemplateModelException(e,
(formatStringCfgSettingName == null
? (Object) "Malformed date/time format string: "
: new Object[] {
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/freemarker/core/ISOLikeTemplateDateFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,11 @@ public final boolean isLocaleBound() {
return false;
}

@Override
public boolean isTimeZoneBound() {
return true;
}

/**
* Always returns {@code null} (there's no markup format).
*/
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/freemarker/core/JavaTemplateDateFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ public boolean isLocaleBound() {
return true;
}

@Override
public boolean isTimeZoneBound() {
return true;
}

/**
* Always returns {@code null} (there's no markup format).
*/
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/freemarker/core/TemplateDateFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,7 @@ public <MO extends TemplateMarkupOutputModel> boolean format(TemplateDateModel d
/**
* Tells if this formatter should be re-created if the time zone changes. Currently always {@code true}.
*/
public final boolean isTimeZoneBound() {
return true;
}
public abstract boolean isTimeZoneBound();

/**
* Utility method to extract the {@link Date} from an {@link TemplateDateModel}, and throw
Expand Down
92 changes: 91 additions & 1 deletion src/test/java/freemarker/core/DateFormatTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@
*/
package freemarker.core;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;
Expand All @@ -36,9 +40,11 @@ public void setup() {
Configuration cfg = getConfiguration();
cfg.setIncompatibleImprovements(Configuration.VERSION_2_3_24);
cfg.setLocale(Locale.US);
cfg.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));

cfg.setCustomDateFormats(ImmutableMap.of(
"epoch", EpochMillisTemplateDateFormatFactory.INSTANCE));
"epoch", EpochMillisTemplateDateFormatFactory.INSTANCE,
"loc", LocAndTZSensitiveTemplateDateFormatFactory.INSTANCE));
}

@Test
Expand All @@ -54,6 +60,59 @@ public void testCustomFormat() throws Exception {
+ "${d} ${d?string} <#setting locale='de_DE'>${d}",
"123456789 123456789 123456789");
}

@Test
public void testLocaleChange() throws Exception {
addToDataModel("d", new Date(123456789));
assertOutput(
"${d?string.@loc} ${d?string.@loc} "
+ "<#setting locale='de_DE'>"
+ "${d?string.@loc} ${d?string.@loc} "
+ "<#setting locale='en_US'>"
+ "${d?string.@loc} ${d?string.@loc}",
"123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 "
+ "123456789@de_DE:GMT+01:00 123456789@de_DE:GMT+01:00 "
+ "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00");

getConfiguration().setDateTimeFormat("@loc");
assertOutput(
"<#assign d = d?datetime>"
+ "${d} ${d?string} "
+ "<#setting locale='de_DE'>"
+ "${d} ${d?string} "
+ "<#setting locale='en_US'>"
+ "${d} ${d?string}",
"123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 "
+ "123456789@de_DE:GMT+01:00 123456789@de_DE:GMT+01:00 "
+ "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00");
}

@Test
public void testTimeZoneChange() throws Exception {
addToDataModel("d", new Date(123456789));
getConfiguration().setDateTimeFormat("iso");
assertOutput(
"${d?string.@loc} ${d?string.@loc} ${d?datetime?isoLocal} "
+ "<#setting timeZone='GMT+02:00'>"
+ "${d?string.@loc} ${d?string.@loc} ${d?datetime?isoLocal} "
+ "<#setting timeZone='GMT+01:00'>"
+ "${d?string.@loc} ${d?string.@loc} ${d?datetime?isoLocal}",
"123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 1970-01-02T11:17:36+01:00 "
+ "123456789@en_US:GMT+02:00 123456789@en_US:GMT+02:00 1970-01-02T12:17:36+02:00 "
+ "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 1970-01-02T11:17:36+01:00");

getConfiguration().setDateTimeFormat("@loc");
assertOutput(
"<#assign d = d?datetime>"
+ "${d} ${d?string} "
+ "<#setting timeZone='GMT+02:00'>"
+ "${d} ${d?string} "
+ "<#setting timeZone='GMT+01:00'>"
+ "${d} ${d?string}",
"123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 "
+ "123456789@en_US:GMT+02:00 123456789@en_US:GMT+02:00 "
+ "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00");
}

@Test
public void testWrongFormatStrings() throws Exception {
Expand All @@ -64,6 +123,37 @@ public void testWrongFormatStrings() throws Exception {
assertErrorContains("${.now?string('x2')}", "\"x2\"", "'x'");
}

@Test
public void testUnknownCustomFormat() throws Exception {
{
getConfiguration().setDateTimeFormat("@noSuchFormat");
Throwable exc = assertErrorContains(
"${.now}",
"\"@noSuchFormat\"", "\"noSuchFormat\"", "\"datetime_format\"");
assertThat(exc.getCause(), instanceOf(UndefinedCustomFormatException.class));

}
{
getConfiguration().setDateFormat("@noSuchFormatD");
assertErrorContains(
"${.now?date}",
"\"@noSuchFormatD\"", "\"noSuchFormatD\"", "\"date_format\"");
}
{
getConfiguration().setTimeFormat("@noSuchFormatT");
assertErrorContains(
"${.now?time}",
"\"@noSuchFormatT\"", "\"noSuchFormatT\"", "\"time_format\"");
}

{
getConfiguration().setDateTimeFormat("");
Throwable exc = assertErrorContains("${.now?string('@noSuchFormat2')}",
"\"@noSuchFormat2\"", "\"noSuchFormat2\"");
assertThat(exc.getCause(), instanceOf(UndefinedCustomFormatException.class));
}
}

@Test
public void testNullInNumberModel() throws Exception {
addToDataModel("n", new MutableTemplateDateModel());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ public boolean isLocaleBound() {
return false;
}

@Override
public boolean isTimeZoneBound() {
return false;
}

@Override
public <MO extends TemplateMarkupOutputModel> MO format(TemplateDateModel dateModel,
MarkupOutputFormat<MO> outputFormat) throws UnformattableNumberException, TemplateModelException {
Expand All @@ -77,8 +82,6 @@ public Date parse(String s) throws ParseException {
public String getDescription() {
return "millis since the epoch";
}



}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package freemarker.core;

import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang.NotImplementedException;

import freemarker.template.TemplateDateModel;
import freemarker.template.TemplateModelException;

public class LocAndTZSensitiveTemplateDateFormatFactory extends TemplateDateFormatFactory {

public static final LocAndTZSensitiveTemplateDateFormatFactory INSTANCE = new LocAndTZSensitiveTemplateDateFormatFactory();

private LocAndTZSensitiveTemplateDateFormatFactory() {
// Defined to decrease visibility
}

@Override
public TemplateDateFormat get(int dateType, boolean zonelessInput, String params, Locale locale, TimeZone timeZone,
Environment env) throws TemplateModelException, UnknownDateTypeFormattingUnsupportedException,
InvalidFormatParametersException {
TemplateNumberFormatUtil.checkHasNoParameters(params);
return new LocAndTZSensitiveTemplateDateFormat(locale, timeZone);
}

private static class LocAndTZSensitiveTemplateDateFormat extends TemplateDateFormat {

private final Locale locale;
private final TimeZone timeZone;

public LocAndTZSensitiveTemplateDateFormat(Locale locale, TimeZone timeZone) {
this.locale = locale;
this.timeZone = timeZone;
}

@Override
public String format(TemplateDateModel dateModel)
throws UnformattableDateException, TemplateModelException {
return String.valueOf(getNonNullDate(dateModel).getTime() + "@" + locale + ":" + timeZone.getID());
}

@Override
public boolean isLocaleBound() {
return true;
}

@Override
public boolean isTimeZoneBound() {
return true;
}

@Override
public <MO extends TemplateMarkupOutputModel> MO format(TemplateDateModel dateModel,
MarkupOutputFormat<MO> outputFormat) throws UnformattableNumberException, TemplateModelException {
throw new NotImplementedException();
}

@Override
public Date parse(String s) throws ParseException {
try {
int atIdx = s.indexOf("@");
if (atIdx == -1) {
throw new ParseException("Missing @", 0);
}
return new Date(Long.parseLong(s.substring(0, atIdx)));
} catch (NumberFormatException e) {
throw new ParseException("Malformed long", 0);
}
}

@Override
public String getDescription() {
return "millis since the epoch";
}

}

}
2 changes: 1 addition & 1 deletion src/test/java/freemarker/core/NumberFormatTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void setup() {
}

@Test
public void testUnknownNumberFormat() throws Exception {
public void testUnknownCustomFormat() throws Exception {
{
getConfiguration().setNumberFormat("@noSuchFormat");
Throwable exc = assertErrorContains("${1}", "\"@noSuchFormat\"", "\"noSuchFormat\"");
Expand Down

0 comments on commit de5152e

Please sign in to comment.