You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractDateField.java 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Type;
  19. import java.text.SimpleDateFormat;
  20. import java.time.LocalDate;
  21. import java.time.ZoneId;
  22. import java.time.format.DateTimeFormatter;
  23. import java.time.temporal.Temporal;
  24. import java.time.temporal.TemporalAccessor;
  25. import java.time.temporal.TemporalAdjuster;
  26. import java.util.Calendar;
  27. import java.util.Collections;
  28. import java.util.Date;
  29. import java.util.HashMap;
  30. import java.util.Locale;
  31. import java.util.Map;
  32. import java.util.Map.Entry;
  33. import java.util.Objects;
  34. import java.util.Optional;
  35. import java.util.Set;
  36. import java.util.logging.Logger;
  37. import java.util.stream.Collectors;
  38. import java.util.stream.Stream;
  39. import com.googlecode.gentyref.GenericTypeReflector;
  40. import org.jsoup.nodes.Element;
  41. import com.vaadin.data.Result;
  42. import com.vaadin.data.ValidationResult;
  43. import com.vaadin.data.Validator;
  44. import com.vaadin.data.ValueContext;
  45. import com.vaadin.data.validator.RangeValidator;
  46. import com.vaadin.event.FieldEvents.BlurEvent;
  47. import com.vaadin.event.FieldEvents.BlurListener;
  48. import com.vaadin.event.FieldEvents.BlurNotifier;
  49. import com.vaadin.event.FieldEvents.FocusEvent;
  50. import com.vaadin.event.FieldEvents.FocusListener;
  51. import com.vaadin.event.FieldEvents.FocusNotifier;
  52. import com.vaadin.server.ErrorMessage;
  53. import com.vaadin.server.UserError;
  54. import com.vaadin.shared.Registration;
  55. import com.vaadin.shared.ui.datefield.AbstractDateFieldServerRpc;
  56. import com.vaadin.shared.ui.datefield.AbstractDateFieldState;
  57. import com.vaadin.shared.ui.datefield.AbstractDateFieldState.AccessibleElement;
  58. import com.vaadin.shared.ui.datefield.DateResolution;
  59. import com.vaadin.ui.declarative.DesignAttributeHandler;
  60. import com.vaadin.ui.declarative.DesignContext;
  61. import com.vaadin.util.TimeZoneUtil;
  62. import elemental.json.Json;
  63. /**
  64. * A date editor component with {@link LocalDate} as an input value.
  65. *
  66. * @author Vaadin Ltd
  67. *
  68. * @since 8.0
  69. *
  70. * @param <T>
  71. * type of date ({@code LocalDate} or {@code LocalDateTime}).
  72. * @param <R>
  73. * resolution enumeration type
  74. *
  75. */
  76. public abstract class AbstractDateField<T extends Temporal & TemporalAdjuster & Serializable & Comparable<? super T>, R extends Enum<R>>
  77. extends AbstractField<T> implements FocusNotifier, BlurNotifier {
  78. private static final DateTimeFormatter RANGE_FORMATTER = DateTimeFormatter
  79. .ofPattern("yyyy-MM-dd[ HH:mm:ss]", Locale.ENGLISH);
  80. private AbstractDateFieldServerRpc rpc = new AbstractDateFieldServerRpc() {
  81. @Override
  82. public void update(String newDateString,
  83. Map<String, Integer> resolutions) {
  84. valueUpdate(newDateString, resolutions);
  85. }
  86. @Override
  87. public void updateValueWithDelay(String newDateString,
  88. Map<String, Integer> resolutions) {
  89. valueUpdate(newDateString, resolutions);
  90. }
  91. private void valueUpdate(String newDateString,
  92. Map<String, Integer> resolutions) {
  93. Set<String> resolutionNames = getResolutions().map(Enum::name)
  94. .collect(Collectors.toSet());
  95. resolutionNames.retainAll(resolutions.keySet());
  96. if (!isReadOnly()
  97. && (!resolutionNames.isEmpty() || newDateString != null)) {
  98. // Old and new dates
  99. final T oldDate = getValue();
  100. T newDate;
  101. boolean hasChanges = false;
  102. if ("".equals(newDateString)) {
  103. newDate = null;
  104. } else {
  105. newDate = reconstructDateFromFields(resolutions, oldDate);
  106. }
  107. boolean parseErrorWasSet = currentErrorMessage != null;
  108. hasChanges |= !Objects.equals(dateString, newDateString)
  109. || !Objects.equals(oldDate, newDate)
  110. || parseErrorWasSet;
  111. if (hasChanges) {
  112. dateString = newDateString;
  113. currentErrorMessage = null;
  114. if (newDateString == null || newDateString.isEmpty()) {
  115. boolean valueChanged = setValue(newDate, true);
  116. if (!valueChanged && parseErrorWasSet) {
  117. doSetValue(newDate);
  118. }
  119. } else {
  120. // invalid date string
  121. if (resolutions.isEmpty()) {
  122. Result<T> parsedDate = handleUnparsableDateString(
  123. dateString);
  124. // If handleUnparsableDateString returns the same
  125. // date as current, force update state to display
  126. // correct representation
  127. parsedDate.ifOk(v -> {
  128. if (!setValue(v, true)
  129. && !isDifferentValue(v)) {
  130. updateDiffstate("resolutions",
  131. Json.createObject());
  132. doSetValue(v);
  133. }
  134. });
  135. if (parsedDate.isError()) {
  136. dateString = null;
  137. currentErrorMessage = parsedDate.getMessage()
  138. .orElse("Parsing error");
  139. if (!isDifferentValue(null)) {
  140. doSetValue(null);
  141. } else {
  142. setValue(null, true);
  143. }
  144. }
  145. } else {
  146. setValue(newDate, true);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. @Override
  153. public void focus() {
  154. fireEvent(new FocusEvent(AbstractDateField.this));
  155. }
  156. @Override
  157. public void blur() {
  158. fireEvent(new BlurEvent(AbstractDateField.this));
  159. }
  160. };
  161. /**
  162. * The default start year (inclusive) from which to calculate the
  163. * daylight-saving time zone transition dates.
  164. */
  165. private static final int DEFAULT_START_YEAR = 1980;
  166. /**
  167. * The default value of the number of future years from the current date for
  168. * which the daylight-saving time zone transition dates are calculated.
  169. */
  170. private static final int DEFAULT_YEARS_FROM_NOW = 20;
  171. /**
  172. * The optional user-supplied start year (inclusive) from which to calculate
  173. * the daylight-saving time zone transition dates.
  174. */
  175. private Integer startYear;
  176. /**
  177. * The optional user-supplied end year (inclusive) until which to calculate
  178. * the daylight-saving time zone transition dates.
  179. */
  180. private Integer endYear;
  181. /**
  182. * Value of the field.
  183. */
  184. private T value;
  185. /**
  186. * Default value of the field, displayed when nothing has been selected.
  187. *
  188. * @since 8.1.2
  189. */
  190. private T defaultValue;
  191. /**
  192. * Specified smallest modifiable unit for the date field.
  193. */
  194. private R resolution;
  195. private ZoneId zoneId;
  196. private String dateString = "";
  197. private String currentErrorMessage;
  198. private String defaultParseErrorMessage = "Date format not recognized";
  199. private String dateOutOfRangeMessage = "Date is out of allowed range";
  200. /* Constructors */
  201. /**
  202. * Constructs an empty {@code AbstractDateField} with no caption and
  203. * specified {@code resolution}.
  204. *
  205. * @param resolution
  206. * initial resolution for the field, not {@code null}
  207. */
  208. public AbstractDateField(R resolution) {
  209. registerRpc(rpc);
  210. setResolution(resolution);
  211. }
  212. /**
  213. * Constructs an empty {@code AbstractDateField} with caption.
  214. *
  215. * @param caption
  216. * the caption of the datefield
  217. * @param resolution
  218. * initial resolution for the field, not {@code null}
  219. */
  220. public AbstractDateField(String caption, R resolution) {
  221. this(resolution);
  222. setCaption(caption);
  223. }
  224. /**
  225. * Constructs a new {@code AbstractDateField} with the given caption and
  226. * initial text contents.
  227. *
  228. * @param caption
  229. * the caption {@code String} for the editor.
  230. * @param value
  231. * the date/time value.
  232. * @param resolution
  233. * initial resolution for the field, not {@code null}
  234. */
  235. public AbstractDateField(String caption, T value, R resolution) {
  236. this(caption, resolution);
  237. setValue(value);
  238. }
  239. /* Component basic features */
  240. @Override
  241. public void beforeClientResponse(boolean initial) {
  242. super.beforeClientResponse(initial);
  243. Locale locale = getLocale();
  244. getState().locale = locale == null ? null : locale.toString();
  245. }
  246. /**
  247. * Construct a date object from the individual field values received from
  248. * the client.
  249. *
  250. * @param resolutions
  251. * map of time unit (resolution) name and value, the key is the
  252. * resolution name e.g. "HOUR", "MINUTE", the value can be
  253. * {@code null}
  254. * @param oldDate
  255. * used as a fallback to get needed values if they are not
  256. * defined in the specified {@code resolutions}
  257. *
  258. * @return the date object built from the specified resolutions
  259. * @since 8.2
  260. */
  261. protected T reconstructDateFromFields(Map<String, Integer> resolutions,
  262. T oldDate) {
  263. Map<R, Integer> calendarFields = new HashMap<>();
  264. for (R resolution : getResolutionsHigherOrEqualTo(getResolution())) {
  265. // Only handle what the client is allowed to send. The same
  266. // resolutions that are painted
  267. String resolutionName = resolution.name();
  268. Integer newValue = resolutions.get(resolutionName);
  269. if (newValue == null) {
  270. newValue = getDatePart(oldDate, resolution);
  271. }
  272. calendarFields.put(resolution, newValue);
  273. }
  274. return buildDate(calendarFields);
  275. }
  276. /**
  277. * Sets the start range for this component. If the value is set before this
  278. * date (taking the resolution into account), the component will not
  279. * validate. If {@code startDate} is set to {@code null}, any value before
  280. * {@code endDate} will be accepted by the range
  281. * <p>
  282. * Note: Negative, i.e. BC dates are not supported.
  283. * <p>
  284. * Note: It's usually recommended to use only one of the following at the same
  285. * time: Range validator with Binder or DateField's setRangeStart check.
  286. *
  287. * @param startDate
  288. * - the allowed range's start date
  289. */
  290. public void setRangeStart(T startDate) {
  291. if (afterDate(startDate, convertFromDateString(getState().rangeEnd))) {
  292. throw new IllegalStateException(
  293. "startDate cannot be later than endDate");
  294. }
  295. getState().rangeStart = convertToDateString(startDate);
  296. }
  297. /**
  298. * Sets the current error message if the range validation fails.
  299. *
  300. * @param dateOutOfRangeMessage
  301. * - Localizable message which is shown when value (the date) is
  302. * set outside allowed range
  303. */
  304. public void setDateOutOfRangeMessage(String dateOutOfRangeMessage) {
  305. this.dateOutOfRangeMessage = dateOutOfRangeMessage;
  306. }
  307. /**
  308. * Returns current date-out-of-range error message.
  309. *
  310. * @see #setDateOutOfRangeMessage(String)
  311. * @return Current error message for dates out of range.
  312. */
  313. public String getDateOutOfRangeMessage() {
  314. return dateOutOfRangeMessage;
  315. }
  316. /**
  317. * Gets the resolution.
  318. *
  319. * @return the date/time field resolution
  320. */
  321. public R getResolution() {
  322. return resolution;
  323. }
  324. /**
  325. * Sets the resolution of the DateField.
  326. *
  327. * The default resolution is {@link DateResolution#DAY} since Vaadin 7.0.
  328. *
  329. * @param resolution
  330. * the resolution to set, not {@code null}
  331. */
  332. public void setResolution(R resolution) {
  333. this.resolution = resolution;
  334. updateResolutions();
  335. }
  336. /**
  337. * Sets the end range for this component. If the value is set after this
  338. * date (taking the resolution into account), the component will not
  339. * validate. If {@code endDate} is set to {@code null}, any value after
  340. * {@code startDate} will be accepted by the range.
  341. * <p>
  342. * Note: It's usually recommended to use only one of the following at the same
  343. * time: Range validator with Binder or DateField's setRangeEnd check.
  344. *
  345. * @param endDate
  346. * the allowed range's end date (inclusive, based on the current
  347. * resolution)
  348. */
  349. public void setRangeEnd(T endDate) {
  350. String date = convertToDateString(endDate);
  351. if (afterDate(convertFromDateString(getState().rangeStart), endDate)) {
  352. throw new IllegalStateException(
  353. "endDate cannot be earlier than startDate");
  354. }
  355. getState().rangeEnd = date;
  356. }
  357. /**
  358. * Returns the precise rangeStart used.
  359. *
  360. * @return the precise rangeStart used, may be {@code null}.
  361. */
  362. public T getRangeStart() {
  363. return convertFromDateString(getState(false).rangeStart);
  364. }
  365. /**
  366. * Parses string representaion of date range limit into date type
  367. *
  368. * @param temporalStr
  369. * the string representation
  370. * @return parsed value
  371. * @see AbstractDateFieldState#rangeStart
  372. * @see AbstractDateFieldState#rangeEnd
  373. * @since 8.4
  374. */
  375. protected T convertFromDateString(String temporalStr) {
  376. if (temporalStr == null) {
  377. return null;
  378. }
  379. return toType(RANGE_FORMATTER.parse(temporalStr));
  380. }
  381. /**
  382. * Converts a temporal value into field-specific data type.
  383. *
  384. * @param temporalAccessor
  385. * - source value
  386. * @return conversion result.
  387. * @since 8.4
  388. */
  389. protected abstract T toType(TemporalAccessor temporalAccessor);
  390. /**
  391. * Converts date range limit into string representation.
  392. *
  393. * @param temporal
  394. * the value
  395. * @return textual representation
  396. * @see AbstractDateFieldState#rangeStart
  397. * @see AbstractDateFieldState#rangeEnd
  398. * @since 8.4
  399. */
  400. protected String convertToDateString(T temporal) {
  401. if (temporal == null) {
  402. return null;
  403. }
  404. return RANGE_FORMATTER.format(temporal);
  405. }
  406. /**
  407. * Checks if {@code value} is after {@code base} or not.
  408. *
  409. * @param value
  410. * temporal value
  411. * @param base
  412. * temporal value to compare to
  413. * @return {@code true} if {@code value} is after {@code base},
  414. * {@code false} otherwise
  415. */
  416. protected boolean afterDate(T value, T base) {
  417. if (value == null || base == null) {
  418. return false;
  419. }
  420. return value.compareTo(base) > 0;
  421. }
  422. /**
  423. * Returns the precise rangeEnd used.
  424. *
  425. * @return the precise rangeEnd used, may be {@code null}.
  426. */
  427. public T getRangeEnd() {
  428. return convertFromDateString(getState(false).rangeEnd);
  429. }
  430. /**
  431. * Sets formatting used by some component implementations. See
  432. * {@link SimpleDateFormat} for format details.
  433. *
  434. * By default it is encouraged to used default formatting defined by Locale,
  435. * but due some JVM bugs it is sometimes necessary to use this method to
  436. * override formatting. See Vaadin issue #2200.
  437. *
  438. * @param dateFormat
  439. * the dateFormat to set, can be {@code null}
  440. *
  441. * @see com.vaadin.ui.AbstractComponent#setLocale(Locale))
  442. */
  443. public void setDateFormat(String dateFormat) {
  444. getState().format = dateFormat;
  445. }
  446. /**
  447. * Returns a format string used to format date value on client side or
  448. * {@code null} if default formatting from {@link Component#getLocale()} is
  449. * used.
  450. *
  451. * @return the dateFormat
  452. */
  453. public String getDateFormat() {
  454. return getState(false).format;
  455. }
  456. /**
  457. * Sets the {@link ZoneId}, which is used when {@code z} is included inside
  458. * the {@link #setDateFormat(String)} .
  459. *
  460. * @param zoneId
  461. * the zone id
  462. * @since 8.2
  463. */
  464. public void setZoneId(ZoneId zoneId) {
  465. if (zoneId != this.zoneId
  466. || (zoneId != null && !zoneId.equals(this.zoneId))) {
  467. updateTimeZoneJSON(zoneId, getLocale(), getStartYear(),
  468. getEndYear());
  469. }
  470. this.zoneId = zoneId;
  471. }
  472. private void updateTimeZoneJSON(ZoneId zoneId, Locale locale, int startYear,
  473. int endYear) {
  474. String timeZoneJSON;
  475. if (zoneId != null && locale != null) {
  476. timeZoneJSON = TimeZoneUtil.toJSON(zoneId, locale, startYear,
  477. endYear);
  478. } else {
  479. timeZoneJSON = null;
  480. }
  481. getState().timeZoneJSON = timeZoneJSON;
  482. }
  483. /**
  484. * Sets {@link startYear} and {@link endYear}: the start and end years (both
  485. * inclusive) between which to calculate the daylight-saving time zone
  486. * transition dates. Both parameters are used when '{@code z}' is included
  487. * inside the {@link #setDateFormat(String)}, they would have no effect
  488. * otherwise. Specifically, these parameters determine the range of years in
  489. * which zone names are are adjusted to show the daylight saving names.
  490. *
  491. * If no values are provided, by default {@link startYear} is set to
  492. * {@value #DEFAULT_START_YEAR}, and {@link endYear} is set to
  493. * {@value #DEFAULT_YEARS_FROM_NOW} years into the future from the current
  494. * date.
  495. *
  496. * @param startYear
  497. * the start year of DST transitions
  498. * @param endYear
  499. * the end year of DST transitions
  500. * @since 8.11
  501. */
  502. public void setDaylightSavingTimeRange(int startYear, int endYear) {
  503. if (startYear > endYear) {
  504. throw new IllegalArgumentException(
  505. "The start year from which to begin calculating the "
  506. + "daylight-saving time zone transition dates must"
  507. + " be less than or equal to the end year.\n"
  508. + startYear + " is greater than " + endYear);
  509. }
  510. if (this.startYear == null || this.endYear == null
  511. || startYear != this.startYear || endYear != this.endYear) {
  512. updateTimeZoneJSON(getZoneId(), getLocale(), startYear, endYear);
  513. }
  514. this.startYear = startYear;
  515. this.endYear = endYear;
  516. }
  517. private int getStartYear() {
  518. if (startYear == null) {
  519. return DEFAULT_START_YEAR;
  520. } else {
  521. return startYear;
  522. }
  523. }
  524. private int getEndYear() {
  525. if (endYear == null) {
  526. return LocalDate.now().getYear() + DEFAULT_YEARS_FROM_NOW;
  527. } else {
  528. return endYear;
  529. }
  530. }
  531. @Override
  532. public void setLocale(Locale locale) {
  533. Locale oldLocale = getLocale();
  534. if (locale != oldLocale
  535. || (locale != null && !locale.equals(oldLocale))) {
  536. updateTimeZoneJSON(getZoneId(), locale, getStartYear(),
  537. getEndYear());
  538. }
  539. super.setLocale(locale);
  540. }
  541. private void updateResolutions() {
  542. final T currentDate = getValue();
  543. Map<String, Integer> resolutions = getState().resolutions;
  544. resolutions.clear();
  545. // Only paint variables for the resolution and up, e.g. Resolution DAY
  546. // paints DAY,MONTH,YEAR
  547. for (R resolution : getResolutionsHigherOrEqualTo(getResolution())) {
  548. String resolutionName = resolution.name();
  549. Integer value = getValuePart(currentDate, resolution);
  550. resolutions.put(resolutionName, value);
  551. Integer defaultValuePart = getValuePart(defaultValue, resolution);
  552. resolutions.put("default-" + resolutionName, defaultValuePart);
  553. }
  554. updateDiffstate("resolutions", Json.createObject());
  555. }
  556. private Integer getValuePart(T date, R resolution) {
  557. if (date == null) {
  558. return null;
  559. }
  560. return getDatePart(date, resolution);
  561. }
  562. /**
  563. * Returns the {@link ZoneId}, which is used when {@code z} is included
  564. * inside the {@link #setDateFormat(String)}.
  565. *
  566. * @return the zoneId
  567. * @since 8.2
  568. */
  569. public ZoneId getZoneId() {
  570. return zoneId;
  571. }
  572. /**
  573. * Specifies whether or not date/time interpretation in component is to be
  574. * lenient.
  575. *
  576. * @see Calendar#setLenient(boolean)
  577. * @see #isLenient()
  578. *
  579. * @param lenient
  580. * true if the lenient mode is to be turned on; false if it is to
  581. * be turned off.
  582. */
  583. public void setLenient(boolean lenient) {
  584. getState().lenient = lenient;
  585. }
  586. /**
  587. * Returns whether date/time interpretation is lenient.
  588. *
  589. * @see #setLenient(boolean)
  590. *
  591. * @return {@code true} if the interpretation mode of this calendar is
  592. * lenient; {@code false} otherwise.
  593. */
  594. public boolean isLenient() {
  595. return getState(false).lenient;
  596. }
  597. @Override
  598. public T getValue() {
  599. return value;
  600. }
  601. /**
  602. * Returns the current default value.
  603. *
  604. * @see #setDefaultValue(Temporal)
  605. * @return the default value
  606. * @since 8.1.2
  607. */
  608. public T getDefaultValue() {
  609. return defaultValue;
  610. }
  611. /**
  612. * Sets the default value for the field. The default value is the starting
  613. * point for the date field when nothing has been selected yet. If no
  614. * default value is set, current date/time is used.
  615. *
  616. * @param defaultValue
  617. * the default value, may be {@code null}
  618. * @since 8.1.2
  619. */
  620. public void setDefaultValue(T defaultValue) {
  621. this.defaultValue = defaultValue;
  622. updateResolutions();
  623. }
  624. /**
  625. * Sets the value of this object. If the new value is not equal to
  626. * {@code getValue()}, fires a {@link ValueChangeEvent} .
  627. *
  628. * @param value
  629. * the new value, may be {@code null}
  630. * @throws IllegalArgumentException
  631. * if the value is not within range bounds
  632. */
  633. @Override
  634. public void setValue(T value) {
  635. RangeValidator<T> validator = getRangeValidator();
  636. ValidationResult result = validator.apply(value,
  637. new ValueContext(this, this));
  638. if (result.isError()) {
  639. throw new IllegalArgumentException(
  640. "value is not within acceptable range");
  641. } else {
  642. currentErrorMessage = null;
  643. /*
  644. * First handle special case when the client side component has a date
  645. * string but value is null (e.g. unparsable date string typed in by the
  646. * user). No value changes should happen, but we need to do some
  647. * internal housekeeping.
  648. */
  649. if (value == null && !getState(false).parsable) {
  650. /*
  651. * Side-effects of doSetValue clears possible previous strings and
  652. * flags about invalid input.
  653. */
  654. doSetValue(null);
  655. markAsDirty();
  656. return;
  657. }
  658. super.setValue(value);
  659. }
  660. }
  661. /**
  662. * Checks whether ISO 8601 week numbers are shown in the date selector.
  663. *
  664. * @return true if week numbers are shown, false otherwise.
  665. */
  666. public boolean isShowISOWeekNumbers() {
  667. return getState(false).showISOWeekNumbers;
  668. }
  669. /**
  670. * Sets the visibility of ISO 8601 week numbers in the date selector. ISO
  671. * 8601 defines that a week always starts with a Monday so the week numbers
  672. * are only shown if this is the case.
  673. *
  674. * @param showWeekNumbers
  675. * true if week numbers should be shown, false otherwise.
  676. */
  677. public void setShowISOWeekNumbers(boolean showWeekNumbers) {
  678. getState().showISOWeekNumbers = showWeekNumbers;
  679. }
  680. /**
  681. * Return the error message that is shown if the user inputted value can't
  682. * be parsed into a Date object. If
  683. * {@link #handleUnparsableDateString(String)} is overridden and it throws a
  684. * custom exception, the message returned by
  685. * {@link Exception#getLocalizedMessage()} will be used instead of the value
  686. * returned by this method.
  687. *
  688. * @see #setParseErrorMessage(String)
  689. *
  690. * @return the error message that the DateField uses when it can't parse the
  691. * textual input from user to a Date object
  692. */
  693. public String getParseErrorMessage() {
  694. return defaultParseErrorMessage;
  695. }
  696. /**
  697. * Sets the default error message used if the DateField cannot parse the
  698. * text input by user to a Date field. Note that if the
  699. * {@link #handleUnparsableDateString(String)} method is overridden, the
  700. * localized message from its exception is used.
  701. *
  702. * @param parsingErrorMessage
  703. * the default parsing error message
  704. *
  705. * @see #getParseErrorMessage()
  706. * @see #handleUnparsableDateString(String)
  707. */
  708. public void setParseErrorMessage(String parsingErrorMessage) {
  709. defaultParseErrorMessage = parsingErrorMessage;
  710. }
  711. @Override
  712. public Registration addFocusListener(FocusListener listener) {
  713. return addListener(FocusEvent.EVENT_ID, FocusEvent.class, listener,
  714. FocusListener.focusMethod);
  715. }
  716. @Override
  717. public Registration addBlurListener(BlurListener listener) {
  718. return addListener(BlurEvent.EVENT_ID, BlurEvent.class, listener,
  719. BlurListener.blurMethod);
  720. }
  721. @Override
  722. @SuppressWarnings("unchecked")
  723. public void readDesign(Element design, DesignContext designContext) {
  724. super.readDesign(design, designContext);
  725. if (design.hasAttr("value") && !design.attr("value").isEmpty()) {
  726. Type dateType = GenericTypeReflector.getTypeParameter(getClass(),
  727. AbstractDateField.class.getTypeParameters()[0]);
  728. if (dateType instanceof Class<?>) {
  729. Class<?> clazz = (Class<?>) dateType;
  730. T date = (T) DesignAttributeHandler.getFormatter()
  731. .parse(design.attr("value"), clazz);
  732. // formatting will return null if it cannot parse the string
  733. if (date == null) {
  734. Logger.getLogger(AbstractDateField.class.getName())
  735. .info("cannot parse " + design.attr("value")
  736. + " as date");
  737. }
  738. doSetValue(date);
  739. } else {
  740. throw new RuntimeException("Cannot detect resoluton type "
  741. + Optional.ofNullable(dateType).map(Type::getTypeName)
  742. .orElse(null));
  743. }
  744. }
  745. }
  746. /**
  747. * Formats date according to the components locale.
  748. *
  749. * @param value
  750. * the date or {@code null}
  751. * @return textual representation of the date or empty string for
  752. * {@code null}
  753. * @since 8.1.1
  754. */
  755. protected abstract String formatDate(T value);
  756. @Override
  757. public void writeDesign(Element design, DesignContext designContext) {
  758. super.writeDesign(design, designContext);
  759. if (getValue() != null) {
  760. design.attr("value",
  761. DesignAttributeHandler.getFormatter().format(getValue()));
  762. }
  763. }
  764. /**
  765. * This method is called to handle a non-empty date string from the client
  766. * if the client could not parse it as a Date.
  767. *
  768. * By default, an error result is returned whose error message is
  769. * {@link #getParseErrorMessage()}.
  770. *
  771. * This can be overridden to handle conversions, to return a result with
  772. * {@code null} value (equivalent to empty input) or to return a custom
  773. * error.
  774. *
  775. * @param dateString
  776. * date string to handle
  777. * @return result that contains parsed Date as a value or an error
  778. */
  779. protected Result<T> handleUnparsableDateString(String dateString) {
  780. return Result.error(getParseErrorMessage());
  781. }
  782. @Override
  783. protected AbstractDateFieldState getState() {
  784. return (AbstractDateFieldState) super.getState();
  785. }
  786. @Override
  787. protected AbstractDateFieldState getState(boolean markAsDirty) {
  788. return (AbstractDateFieldState) super.getState(markAsDirty);
  789. }
  790. @Override
  791. protected void doSetValue(T value) {
  792. // Also set the internal dateString
  793. this.value = value;
  794. if (value == null) {
  795. value = getEmptyValue();
  796. }
  797. dateString = formatDate(value);
  798. // TODO move range check to internal validator?
  799. RangeValidator<T> validator = getRangeValidator();
  800. ValidationResult result = validator.apply(value,
  801. new ValueContext(this, this));
  802. if (result.isError()) {
  803. currentErrorMessage = getDateOutOfRangeMessage();
  804. }
  805. getState().parsable = currentErrorMessage == null;
  806. ErrorMessage errorMessage;
  807. if (currentErrorMessage == null) {
  808. errorMessage = null;
  809. } else {
  810. errorMessage = new UserError(currentErrorMessage);
  811. }
  812. setComponentError(errorMessage);
  813. updateResolutions();
  814. }
  815. /**
  816. * Returns a date integer value part for the given {@code date} for the
  817. * given {@code resolution}.
  818. *
  819. * @param date
  820. * the given date, can be {@code null}
  821. * @param resolution
  822. * the resolution to extract a value from the date by, not
  823. * {@code null}
  824. * @return the integer value part of the date by the given resolution
  825. */
  826. protected abstract int getDatePart(T date, R resolution);
  827. /**
  828. * Builds date by the given {@code resolutionValues} which is a map whose
  829. * keys are resolution and integer values.
  830. * <p>
  831. * This is the opposite to {@link #getDatePart(Temporal, Enum)}.
  832. *
  833. * @param resolutionValues
  834. * date values to construct a date
  835. * @return date built from the given map of date values
  836. */
  837. protected abstract T buildDate(Map<R, Integer> resolutionValues);
  838. /**
  839. * Returns a custom date range validator which is applicable for the type
  840. * {@code T}.
  841. *
  842. * @return the date range validator
  843. */
  844. protected abstract RangeValidator<T> getRangeValidator();
  845. /**
  846. * Converts {@link Date} to date type {@code T}.
  847. *
  848. * @param date
  849. * a date to convert
  850. * @return object of type {@code T} representing the {@code date}
  851. */
  852. protected abstract T convertFromDate(Date date);
  853. /**
  854. * Converts the object of type {@code T} to {@link Date}.
  855. * <p>
  856. * This is the opposite to {@link #convertFromDate(Date)}.
  857. *
  858. * @param date
  859. * the date of type {@code T}
  860. * @return converted date of type {@code Date}
  861. */
  862. protected abstract Date convertToDate(T date);
  863. @SuppressWarnings("unchecked")
  864. private Stream<R> getResolutions() {
  865. Type resolutionType = GenericTypeReflector.getTypeParameter(getClass(),
  866. AbstractDateField.class.getTypeParameters()[1]);
  867. if (resolutionType instanceof Class<?>) {
  868. Class<?> clazz = (Class<?>) resolutionType;
  869. return Stream.of(clazz.getEnumConstants())
  870. .map(object -> (R) object);
  871. }
  872. throw new RuntimeException("Cannot detect resoluton type "
  873. + Optional.ofNullable(resolutionType).map(Type::getTypeName)
  874. .orElse(null));
  875. }
  876. private Iterable<R> getResolutionsHigherOrEqualTo(R resoution) {
  877. return getResolutions().skip(resolution.ordinal())
  878. .collect(Collectors.toList());
  879. }
  880. @Override
  881. public Validator<T> getDefaultValidator() {
  882. return new Validator<T>() {
  883. @Override
  884. public ValidationResult apply(T value, ValueContext context) {
  885. // currentErrorMessage contains two type of messages, one is
  886. // DateOutOfRangeMessage and the other one is the ParseError
  887. if (currentErrorMessage != null) {
  888. if (currentErrorMessage
  889. .equals(getDateOutOfRangeMessage())) {
  890. // if the currentErrorMessage is DateOutOfRangeMessage,
  891. // then need to double check whether the error message
  892. // has been updated, that is because of #11276.
  893. ValidationResult validationResult = getRangeValidator()
  894. .apply(value, context);
  895. if (validationResult.isError()) {
  896. return ValidationResult.error(currentErrorMessage);
  897. }
  898. } else {
  899. // if the current Error is parsing error, pass it to the
  900. // ValidationResult
  901. return ValidationResult.error(currentErrorMessage);
  902. }
  903. }
  904. // Pass to range validator.
  905. return getRangeValidator().apply(value, context);
  906. }
  907. };
  908. }
  909. /**
  910. * <p>
  911. * Sets a custom style name for the given date's calendar cell. Setting the
  912. * style name will override any previous style names that have been set for
  913. * that date, but can contain several actual style names separated by space.
  914. * Setting the custom style name {@code null} will only remove the previous
  915. * custom style name.
  916. * </p>
  917. * <p>
  918. * This logic is entirely separate from {@link #setStyleName(String)}
  919. * </p>
  920. * <p>
  921. * Usage examples: <br>
  922. * {@code setDateStyle(LocalDate.now(), "teststyle");} <br>
  923. * {@code setDateStyle(LocalDate.now(), "teststyle1 teststyle2");}
  924. * </p>
  925. *
  926. * @param date
  927. * which date cell to modify, not {@code null}
  928. * @param styleName
  929. * the custom style name(s) for given date, {@code null} to clear
  930. * custom style name(s)
  931. *
  932. * @since 8.3
  933. */
  934. public void setDateStyle(LocalDate date, String styleName) {
  935. Objects.requireNonNull(date, "Date cannot be null");
  936. if (styleName != null) {
  937. getState().dateStyles.put(date.toString(), styleName);
  938. } else {
  939. getState().dateStyles.remove(date.toString());
  940. }
  941. }
  942. /**
  943. * Returns the custom style name that corresponds with the given date's
  944. * calendar cell.
  945. *
  946. * @param date
  947. * which date cell's custom style name(s) to return, not
  948. * {@code null}
  949. * @return the corresponding style name(s), if any, {@code null} otherwise
  950. *
  951. * @see #setDateStyle(LocalDate, String)
  952. * @since 8.3
  953. */
  954. public String getDateStyle(LocalDate date) {
  955. Objects.requireNonNull(date, "Date cannot be null");
  956. return getState(false).dateStyles.get(date.toString());
  957. }
  958. /**
  959. * Returns a map from dates to custom style names in each date's calendar
  960. * cell.
  961. *
  962. * @return unmodifiable map from dates to custom style names in each date's
  963. * calendar cell
  964. *
  965. * @see #setDateStyle(LocalDate, String)
  966. * @since 8.3
  967. */
  968. public Map<LocalDate, String> getDateStyles() {
  969. HashMap<LocalDate, String> hashMap = new HashMap<>();
  970. for (Entry<String, String> entry : getState(false).dateStyles
  971. .entrySet()) {
  972. hashMap.put(LocalDate.parse(entry.getKey()), entry.getValue());
  973. }
  974. return Collections.unmodifiableMap(hashMap);
  975. }
  976. /**
  977. * Sets the assistive label for a calendar navigation element. This sets the
  978. * {@code aria-label} attribute for the element which is used by screen
  979. * reading software.
  980. *
  981. * @param element
  982. * the element for which to set the label. Not {@code null}.
  983. * @param label
  984. * the assistive label to set
  985. * @since 8.4
  986. */
  987. public void setAssistiveLabel(AccessibleElement element, String label) {
  988. Objects.requireNonNull(element, "Element cannot be null");
  989. getState().assistiveLabels.put(element, label);
  990. }
  991. /**
  992. * Gets the assistive label of a calendar navigation element.
  993. *
  994. * @param element
  995. * the element of which to get the assistive label
  996. * @since 8.4
  997. */
  998. public void getAssistiveLabel(AccessibleElement element) {
  999. getState(false).assistiveLabels.get(element);
  1000. }
  1001. }