jakarta.faces.convert.DateTimeConverter Maven / Gradle / Ivy
Show all versions of jakarta.faces Show documentation
/*
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package jakarta.faces.convert;
import static jakarta.faces.convert.MessageFactory.getLabel;
import static jakarta.faces.convert.MessageFactory.getMessage;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import jakarta.faces.component.PartialStateHolder;
import jakarta.faces.component.UIComponent;
import jakarta.faces.context.FacesContext;
/**
*
* {@link Converter} implementation for
* java.util.Date
values.
*
*
*
* The getAsObject()
method parses a String into a java.util.Date
, according to the following
* algorithm:
*
*
* - If the specified String is null, return a
null
. Otherwise, trim leading and trailing whitespace before
* proceeding.
* - If the specified String - after trimming - has a zero length, return
null
.
* - If the
locale
property is not null, use that Locale
for managing parsing. Otherwise, use the
* Locale
from the UIViewRoot
.
*
* - If a
pattern
has been specified, its syntax must conform the rules specified by
* java.text.SimpleDateFormat
or {@code
* java.time.format.DateTimeFormatter}. Which of these two formatters is used depends on the value of {@code type}. Such a
* pattern will be used to parse, and the type
, dateStyle
, and timeStyle
properties will
* be ignored, unless the value of {@code
* type} is one of the {@code java.time} specific values listed in {@link #setType}. In this case,
* {@code DateTimeFormatter.ofPattern(String, Locale)} must be called, passing the value of {@code pattern} as the first argument
* and the current {@code Locale} as the second argument, and this formatter must be used to parse the incoming
* value.
*
* - If a
pattern
has not been specified, parsing will be based on the type
property, which expects a
* date value, a time value, both, or one of several values specific to classes in
* {@code java.time} as listed in {@link #setType}. Any date and time values included will be parsed in accordance to the
* styles specified by dateStyle
and timeStyle
, respectively.
* - If a
timezone
has been specified, it must be passed to the underlying DateFormat
instance.
* Otherwise the "GMT" timezone is used.
* - In all cases, parsing must be non-lenient; the given string must strictly adhere to the parsing format.
*
*
*
* The getAsString()
method expects a value of type java.util.Date
(or a subclass), and creates a
* formatted String according to the following algorithm:
*
*
* - If the specified value is null, return a zero-length String.
* - If the specified value is a String, return it unmodified.
* - If the
locale
property is not null, use that Locale
for managing formatting. Otherwise, use the
* Locale
from the UIViewRoot
.
* - If a
timezone
has been specified, it must be passed to the underlying DateFormat
instance.
* Otherwise the "GMT" timezone is used.
*
* - If a
pattern
has been specified, its syntax must conform the rules specified by
* java.text.SimpleDateFormat
or {@code
* java.time.format.DateTimeFormatter}. Which of these two formatters is used depends on the value of {@code type}. Such a
* pattern will be used to format, and the type
, dateStyle
, and timeStyle
properties will
* be ignored, unless the value of {@code
* type} is one of the {@code java.time} specific values listed in {@link #setType}. In this case, {@code
* DateTimeFormatter.ofPattern(String, Locale)} must be called, passing the value of {@code pattern} as the first argument and
* the current {@code Locale} as the second argument, and this formatter must be used to format the outgoing value.
*
* - If a
pattern
has not been specified, formatting will be based on the type
property, which
* includes a date value, a time value, both or into the formatted String. Any date and time values included will be formatted in
* accordance to the styles specified by dateStyle
and timeStyle
, respectively.
*
*/
public class DateTimeConverter implements Converter, PartialStateHolder {
// ------------------------------------------------------ Manifest Constants
/**
*
* The standard converter id for this converter.
*
*/
public static final String CONVERTER_ID = "jakarta.faces.DateTime";
/**
*
* The message identifier of the {@link jakarta.faces.application.FacesMessage} to be created if the conversion to
* Date
fails. The message format string for this message may optionally include the following placeholders:
*
* {0}
replaced by the unconverted value.
* {1}
replaced by an example value.
* {2}
replaced by a String
whose value is the label of the input component that produced this
* message.
*
*/
public static final String DATE_ID = "jakarta.faces.converter.DateTimeConverter.DATE";
/**
*
* The message identifier of the {@link jakarta.faces.application.FacesMessage} to be created if the conversion to
* Time
fails. The message format string for this message may optionally include the following placeholders:
*
* {0}
replaced by the unconverted value.
* {1}
replaced by an example value.
* {2}
replaced by a String
whose value is the label of the input component that produced this
* message.
*
*/
public static final String TIME_ID = "jakarta.faces.converter.DateTimeConverter.TIME";
/**
*
* The message identifier of the {@link jakarta.faces.application.FacesMessage} to be created if the conversion to
* DateTime
fails. The message format string for this message may optionally include the following placeholders:
*
* {0}
replaced by the unconverted value.
* {1}
replaced by an example value.
* {2}
replaced by a String
whose value is the label of the input component that produced this
* message.
*
*/
public static final String DATETIME_ID = "jakarta.faces.converter.DateTimeConverter.DATETIME";
/**
*
* The message identifier of the {@link jakarta.faces.application.FacesMessage} to be created if the conversion of the
* DateTime
value to String
fails. The message format string for this message may optionally include
* the following placeholders:
*
* {0}
relaced by the unconverted value.
* {1}
replaced by a String
whose value is the label of the input component that produced this
* message.
*
*/
public static final String STRING_ID = "jakarta.faces.converter.STRING";
private static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone("GMT");
// ------------------------------------------------------ Instance Variables
private String dateStyle = "default";
private Locale locale;
private String pattern;
private String timeStyle = "default";
private TimeZone timeZone = DEFAULT_TIME_ZONE;
private String type = "date";
// -------------------------------------------------------------- Properties
/**
*
* Return the style to be used to format or parse dates. If not set, the default value, default
, is returned.
*
*
* @return the style
*/
public String getDateStyle() {
return dateStyle;
}
/**
*
* Set the style to be used to format or parse dates. Valid values are default
, short
,
* medium
, long
, and full
. An invalid value will cause a {@link ConverterException} when
* getAsObject()
or getAsString()
is called.
*
*
* @param dateStyle The new style code
*/
public void setDateStyle(String dateStyle) {
clearInitialState();
this.dateStyle = dateStyle;
}
/**
*
* Return the Locale
to be used when parsing or formatting dates and times. If not explicitly set, the
* Locale
stored in the {@link jakarta.faces.component.UIViewRoot} for the current request is returned.
*
*
* @return the {@code Locale}
*/
public Locale getLocale() {
if (locale == null) {
locale = getLocale(FacesContext.getCurrentInstance());
}
return locale;
}
/**
*
* Set the Locale
to be used when parsing or formatting dates and times. If set to null
, the
* Locale
stored in the {@link jakarta.faces.component.UIViewRoot} for the current request will be utilized.
*
*
* @param locale The new Locale
(or null
)
*/
public void setLocale(Locale locale) {
clearInitialState();
this.locale = locale;
}
/**
*
* Return the format pattern to be used when formatting and parsing dates and times.
*
*
* @return the pattern
*/
public String getPattern() {
return pattern;
}
/**
*
* Set the format pattern to be used when formatting and parsing dates and times. Valid values are those supported by
* java.text.SimpleDateFormat
. An invalid value will cause a {@link ConverterException} when
* getAsObject()
or getAsString()
is called.
*
*
* @param pattern The new format pattern
*/
public void setPattern(String pattern) {
clearInitialState();
this.pattern = pattern;
}
/**
*
* Return the style to be used to format or parse times. If not set, the default value, default
, is returned.
*
*
* @return the time style
*/
public String getTimeStyle() {
return timeStyle;
}
/**
*
* Set the style to be used to format or parse times. Valid values are default
, short
,
* medium
, long
, and full
. An invalid value will cause a {@link ConverterException} when
* getAsObject()
or getAsString()
is called.
*
*
* @param timeStyle The new style code
*/
public void setTimeStyle(String timeStyle) {
clearInitialState();
this.timeStyle = timeStyle;
}
/**
*
* Return the TimeZone
used to interpret a time value. If not explicitly set, the default time zone of
* GMT
returned.
*
*
* @return the {@code TimeZone}
*/
public TimeZone getTimeZone() {
return timeZone;
}
/**
*
* Set the TimeZone
used to interpret a time value.
*
*
* @param timeZone The new time zone
*/
public void setTimeZone(TimeZone timeZone) {
clearInitialState();
this.timeZone = timeZone;
}
/**
*
* Return the type of value to be formatted or parsed. If not explicitly set, the default type, date
is returned.
*
*
* @return the type
*/
public String getType() {
return type;
}
/**
*
* Set the type of value to be formatted or parsed. Valid values are both
,
* date
, time
{@code localDate}, {@code
* localDateTime}, {@code localTime}, {@code offsetTime}, {@code
* offsetDateTime}, or {@code zonedDateTime}. The values starting with "local", "offset" and "zoned" correspond to Java SE 8 Date
* Time API classes in package java.time
with the name derived by upper casing the first letter. For example,
* java.time.LocalDate
for the value "localDate"
. An invalid value will cause a
* {@link ConverterException} when getAsObject()
or getAsString()
is called.
*
*
* @param type The new date style
*/
public void setType(String type) {
clearInitialState();
this.type = type;
}
// ------------------------------------------------------- Converter Methods
/**
* @throws ConverterException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (context == null || component == null) {
throw new NullPointerException();
}
Object returnValue = null;
FormatWrapper parser = null;
try {
// If the specified value is null or zero-length, return null
if (value == null) {
return null;
}
value = value.trim();
if (value.length() < 1) {
return null;
}
// Identify the Locale to use for parsing
Locale locale = getLocale(context);
// Create and configure the parser to be used
parser = getDateFormat(locale);
if (timeZone != null) {
parser.setTimeZone(timeZone);
}
// Perform the requested parsing
returnValue = parser.parse(value);
} catch (ParseException | DateTimeParseException e) {
if (type != null) {
switch (type) {
case "date":
case "localDate":
throw new ConverterException(
getMessage(context, DATE_ID, value, parser.formatNow(), getLabel(context, component)),
e);
case "time":
case "localTime":
case "offsetTime":
throw new ConverterException(
getMessage(context, TIME_ID, value, parser.formatNow(), getLabel(context, component)),
e);
case "both":
case "localDateTime":
case "offsetDateTime":
case "zonedDateTime":
throw new ConverterException(getMessage(context, DATETIME_ID, value, parser.formatNow(),
getLabel(context, component)), e);
}
}
} catch (Exception e) {
throw new ConverterException(e);
}
return returnValue;
}
private static class FormatWrapper {
private final DateFormat dateFormat;
private final DateTimeFormatter dateTimeFormatter;
private final TemporalQuery