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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. /*
  2. * Copyright 2000-2014 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.Method;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.Iterator;
  23. import java.util.LinkedList;
  24. import java.util.List;
  25. import java.util.Locale;
  26. import java.util.logging.Logger;
  27. import org.jsoup.nodes.Attributes;
  28. import org.jsoup.nodes.Element;
  29. import com.vaadin.data.Buffered;
  30. import com.vaadin.data.Property;
  31. import com.vaadin.data.Validatable;
  32. import com.vaadin.data.Validator;
  33. import com.vaadin.data.Validator.InvalidValueException;
  34. import com.vaadin.data.util.LegacyPropertyHelper;
  35. import com.vaadin.data.util.converter.Converter;
  36. import com.vaadin.data.util.converter.Converter.ConversionException;
  37. import com.vaadin.data.util.converter.ConverterUtil;
  38. import com.vaadin.event.Action;
  39. import com.vaadin.event.ShortcutAction;
  40. import com.vaadin.event.ShortcutListener;
  41. import com.vaadin.server.AbstractErrorMessage;
  42. import com.vaadin.server.CompositeErrorMessage;
  43. import com.vaadin.server.ErrorMessage;
  44. import com.vaadin.shared.AbstractFieldState;
  45. import com.vaadin.shared.util.SharedUtil;
  46. import com.vaadin.ui.declarative.DesignAttributeHandler;
  47. import com.vaadin.ui.declarative.DesignContext;
  48. /**
  49. * <p>
  50. * Abstract field component for implementing buffered property editors. The
  51. * field may hold an internal value, or it may be connected to any data source
  52. * that implements the {@link com.vaadin.data.Property}interface.
  53. * <code>AbstractField</code> implements that interface itself, too, so
  54. * accessing the Property value represented by it is straightforward.
  55. * </p>
  56. *
  57. * <p>
  58. * AbstractField also provides the {@link com.vaadin.data.Buffered} interface
  59. * for buffering the data source value. By default the Field is in write
  60. * through-mode and {@link #setWriteThrough(boolean)}should be called to enable
  61. * buffering.
  62. * </p>
  63. *
  64. * <p>
  65. * The class also supports {@link com.vaadin.data.Validator validators} to make
  66. * sure the value contained in the field is valid.
  67. * </p>
  68. *
  69. * @author Vaadin Ltd.
  70. * @since 3.0
  71. */
  72. @SuppressWarnings("serial")
  73. public abstract class AbstractField<T> extends AbstractComponent implements
  74. Field<T>, Property.ReadOnlyStatusChangeListener,
  75. Property.ReadOnlyStatusChangeNotifier, Action.ShortcutNotifier {
  76. /* Private members */
  77. /**
  78. * Value of the abstract field.
  79. */
  80. private T value;
  81. /**
  82. * A converter used to convert from the data model type to the field type
  83. * and vice versa.
  84. */
  85. private Converter<T, Object> converter = null;
  86. /**
  87. * Connected data-source.
  88. */
  89. private Property<?> dataSource = null;
  90. /**
  91. * The list of validators.
  92. */
  93. private LinkedList<Validator> validators = null;
  94. /**
  95. * True if field is in buffered mode, false otherwise
  96. */
  97. private boolean buffered;
  98. /**
  99. * Flag to indicate that the field is currently committing its value to the
  100. * datasource.
  101. */
  102. private boolean committingValueToDataSource = false;
  103. /**
  104. * Current source exception.
  105. */
  106. private Buffered.SourceException currentBufferedSourceException = null;
  107. /**
  108. * Are the invalid values allowed in fields ?
  109. */
  110. private boolean invalidAllowed = true;
  111. /**
  112. * Are the invalid values committed ?
  113. */
  114. private boolean invalidCommitted = false;
  115. /**
  116. * The error message for the exception that is thrown when the field is
  117. * required but empty.
  118. */
  119. private String requiredError = "";
  120. /**
  121. * The error message that is shown when the field value cannot be converted.
  122. */
  123. private String conversionError = "Could not convert value to {0}";
  124. /**
  125. * Is automatic validation enabled.
  126. */
  127. private boolean validationVisible = true;
  128. private boolean valueWasModifiedByDataSourceDuringCommit;
  129. /**
  130. * Whether this field is currently registered as listening to events from
  131. * its data source.
  132. *
  133. * @see #setPropertyDataSource(Property)
  134. * @see #addPropertyListeners()
  135. * @see #removePropertyListeners()
  136. */
  137. private boolean isListeningToPropertyEvents = false;
  138. /**
  139. * The locale used when setting the value.
  140. */
  141. private Locale valueLocale = null;
  142. /* Component basics */
  143. /*
  144. * Paints the field. Don't add a JavaDoc comment here, we use the default
  145. * documentation from the implemented interface.
  146. */
  147. /**
  148. * Returns true if the error indicator be hidden when painting the component
  149. * even when there are errors.
  150. *
  151. * This is a mostly internal method, but can be overridden in subclasses
  152. * e.g. if the error indicator should also be shown for empty fields in some
  153. * cases.
  154. *
  155. * @return true to hide the error indicator, false to use the normal logic
  156. * to show it when there are errors
  157. */
  158. protected boolean shouldHideErrors() {
  159. // getErrorMessage() can still return something else than null based on
  160. // validation etc.
  161. return isRequired() && isEmpty() && getComponentError() == null;
  162. }
  163. /**
  164. * Returns the type of the Field. The methods <code>getValue</code> and
  165. * <code>setValue</code> must be compatible with this type: one must be able
  166. * to safely cast the value returned from <code>getValue</code> to the given
  167. * type and pass any variable assignable to this type as an argument to
  168. * <code>setValue</code>.
  169. *
  170. * @return the type of the Field
  171. */
  172. @Override
  173. public abstract Class<? extends T> getType();
  174. /**
  175. * The abstract field is read only also if the data source is in read only
  176. * mode.
  177. */
  178. @Override
  179. public boolean isReadOnly() {
  180. return super.isReadOnly()
  181. || (dataSource != null && dataSource.isReadOnly());
  182. }
  183. /**
  184. * Changes the readonly state and throw read-only status change events.
  185. *
  186. * @see com.vaadin.ui.Component#setReadOnly(boolean)
  187. */
  188. @Override
  189. public void setReadOnly(boolean readOnly) {
  190. super.setReadOnly(readOnly);
  191. fireReadOnlyStatusChange();
  192. }
  193. /**
  194. * Tests if the invalid data is committed to datasource.
  195. *
  196. * @see com.vaadin.data.BufferedValidatable#isInvalidCommitted()
  197. */
  198. @Override
  199. public boolean isInvalidCommitted() {
  200. return invalidCommitted;
  201. }
  202. /**
  203. * Sets if the invalid data should be committed to datasource.
  204. *
  205. * @see com.vaadin.data.BufferedValidatable#setInvalidCommitted(boolean)
  206. */
  207. @Override
  208. public void setInvalidCommitted(boolean isCommitted) {
  209. invalidCommitted = isCommitted;
  210. }
  211. /*
  212. * Saves the current value to the data source Don't add a JavaDoc comment
  213. * here, we use the default documentation from the implemented interface.
  214. */
  215. @Override
  216. public void commit() throws Buffered.SourceException, InvalidValueException {
  217. if (dataSource != null && !dataSource.isReadOnly()) {
  218. if ((isInvalidCommitted() || isValid())) {
  219. try {
  220. // Commits the value to datasource.
  221. valueWasModifiedByDataSourceDuringCommit = false;
  222. committingValueToDataSource = true;
  223. getPropertyDataSource().setValue(getConvertedValue());
  224. } catch (final Throwable e) {
  225. // Sets the buffering state.
  226. SourceException sourceException = new Buffered.SourceException(
  227. this, e);
  228. setCurrentBufferedSourceException(sourceException);
  229. // Throws the source exception.
  230. throw sourceException;
  231. } finally {
  232. committingValueToDataSource = false;
  233. }
  234. } else {
  235. /*
  236. * An invalid value and we don't allow them, throw the exception
  237. */
  238. validate();
  239. }
  240. }
  241. // The abstract field is not modified anymore
  242. if (isModified()) {
  243. setModified(false);
  244. }
  245. // If successful, remove set the buffering state to be ok
  246. if (getCurrentBufferedSourceException() != null) {
  247. setCurrentBufferedSourceException(null);
  248. }
  249. if (valueWasModifiedByDataSourceDuringCommit) {
  250. valueWasModifiedByDataSourceDuringCommit = false;
  251. fireValueChange(false);
  252. }
  253. }
  254. /*
  255. * Updates the value from the data source. Don't add a JavaDoc comment here,
  256. * we use the default documentation from the implemented interface.
  257. */
  258. @Override
  259. public void discard() throws Buffered.SourceException {
  260. updateValueFromDataSource();
  261. }
  262. /**
  263. * Gets the value from the data source. This is only here because of clarity
  264. * in the code that handles both the data model value and the field value.
  265. *
  266. * @return The value of the property data source
  267. */
  268. private Object getDataSourceValue() {
  269. return dataSource.getValue();
  270. }
  271. /**
  272. * Returns the field value. This is always identical to {@link #getValue()}
  273. * and only here because of clarity in the code that handles both the data
  274. * model value and the field value.
  275. *
  276. * @return The value of the field
  277. */
  278. private T getFieldValue() {
  279. // Give the value from abstract buffers if the field if possible
  280. if (dataSource == null || isBuffered() || isModified()) {
  281. return getInternalValue();
  282. }
  283. // There is no buffered value so use whatever the data model provides
  284. return convertFromModel(getDataSourceValue());
  285. }
  286. /*
  287. * Has the field been modified since the last commit()? Don't add a JavaDoc
  288. * comment here, we use the default documentation from the implemented
  289. * interface.
  290. */
  291. @Override
  292. public boolean isModified() {
  293. return getState(false).modified;
  294. }
  295. private void setModified(boolean modified) {
  296. getState().modified = modified;
  297. }
  298. /**
  299. * Sets the buffered mode of this Field.
  300. * <p>
  301. * When the field is in buffered mode, changes will not be committed to the
  302. * property data source until {@link #commit()} is called.
  303. * </p>
  304. * <p>
  305. * Setting buffered mode from true to false will commit any pending changes.
  306. * </p>
  307. * <p>
  308. *
  309. * </p>
  310. *
  311. * @since 7.0.0
  312. * @param buffered
  313. * true if buffered mode should be turned on, false otherwise
  314. */
  315. @Override
  316. public void setBuffered(boolean buffered) {
  317. if (this.buffered == buffered) {
  318. return;
  319. }
  320. this.buffered = buffered;
  321. if (!buffered) {
  322. commit();
  323. }
  324. }
  325. /**
  326. * Checks the buffered mode of this Field.
  327. *
  328. * @return true if buffered mode is on, false otherwise
  329. */
  330. @Override
  331. public boolean isBuffered() {
  332. return buffered;
  333. }
  334. /**
  335. * Returns a string representation of this object. The returned string
  336. * representation depends on if the legacy Property toString mode is enabled
  337. * or disabled.
  338. * <p>
  339. * If legacy Property toString mode is enabled, returns the value of this
  340. * <code>Field</code> converted to a String.
  341. * </p>
  342. * <p>
  343. * If legacy Property toString mode is disabled, the string representation
  344. * has no special meaning
  345. * </p>
  346. *
  347. * @see LegacyPropertyHelper#isLegacyToStringEnabled()
  348. *
  349. * @return A string representation of the value value stored in the Property
  350. * or a string representation of the Property object.
  351. * @deprecated As of 7.0. Use {@link #getValue()} to get the value of the
  352. * field, {@link #getConvertedValue()} to get the field value
  353. * converted to the data model type or
  354. * {@link #getPropertyDataSource()} .getValue() to get the value
  355. * of the data source.
  356. */
  357. @Deprecated
  358. @Override
  359. public String toString() {
  360. if (!LegacyPropertyHelper.isLegacyToStringEnabled()) {
  361. return super.toString();
  362. } else {
  363. return LegacyPropertyHelper.legacyPropertyToString(this);
  364. }
  365. }
  366. /* Property interface implementation */
  367. /**
  368. * Gets the current value of the field.
  369. *
  370. * <p>
  371. * This is the visible, modified and possible invalid value the user have
  372. * entered to the field.
  373. * </p>
  374. *
  375. * <p>
  376. * Note that the object returned is compatible with getType(). For example,
  377. * if the type is String, this returns Strings even when the underlying
  378. * datasource is of some other type. In order to access the converted value,
  379. * use {@link #getConvertedValue()} and to access the value of the property
  380. * data source, use {@link Property#getValue()} for the property data
  381. * source.
  382. * </p>
  383. *
  384. * <p>
  385. * Since Vaadin 7.0, no implicit conversions between other data types and
  386. * String are performed, but a converter is used if set.
  387. * </p>
  388. *
  389. * @return the current value of the field.
  390. */
  391. @Override
  392. public T getValue() {
  393. return getFieldValue();
  394. }
  395. /**
  396. * Sets the value of the field.
  397. *
  398. * @param newFieldValue
  399. * the New value of the field.
  400. * @throws Property.ReadOnlyException
  401. */
  402. @Override
  403. public void setValue(T newFieldValue) throws Property.ReadOnlyException,
  404. Converter.ConversionException {
  405. setValue(newFieldValue, false);
  406. }
  407. /**
  408. * Sets the value of the field.
  409. *
  410. * @param newFieldValue
  411. * the New value of the field.
  412. * @param repaintIsNotNeeded
  413. * True iff caller is sure that repaint is not needed.
  414. * @throws Property.ReadOnlyException
  415. * @throws Converter.ConversionException
  416. * @throws InvalidValueException
  417. */
  418. protected void setValue(T newFieldValue, boolean repaintIsNotNeeded) {
  419. setValue(newFieldValue, repaintIsNotNeeded, false);
  420. }
  421. /**
  422. * Sets the value of the field.
  423. *
  424. * @since 7.5.7
  425. * @param newFieldValue
  426. * the New value of the field.
  427. * @param repaintIsNotNeeded
  428. * True iff caller is sure that repaint is not needed.
  429. * @param ignoreReadOnly
  430. * True iff if the read-only check should be ignored
  431. * @throws Property.ReadOnlyException
  432. * @throws Converter.ConversionException
  433. * @throws InvalidValueException
  434. */
  435. protected void setValue(T newFieldValue, boolean repaintIsNotNeeded,
  436. boolean ignoreReadOnly) throws Property.ReadOnlyException,
  437. Converter.ConversionException, InvalidValueException {
  438. if (!SharedUtil.equals(newFieldValue, getInternalValue())) {
  439. // Read only fields can not be changed
  440. if (!ignoreReadOnly && isReadOnly()) {
  441. throw new Property.ReadOnlyException();
  442. }
  443. try {
  444. T doubleConvertedFieldValue = convertFromModel(convertToModel(newFieldValue));
  445. if (!SharedUtil
  446. .equals(newFieldValue, doubleConvertedFieldValue)) {
  447. newFieldValue = doubleConvertedFieldValue;
  448. repaintIsNotNeeded = false;
  449. }
  450. } catch (Throwable t) {
  451. // Ignore exceptions in the conversion at this stage. Any
  452. // conversion error will be handled later by validate().
  453. }
  454. // Repaint is needed even when the client thinks that it knows the
  455. // new state if validity of the component may change
  456. if (repaintIsNotNeeded
  457. && (isRequired() || hasValidators() || getConverter() != null)) {
  458. repaintIsNotNeeded = false;
  459. }
  460. if (!isInvalidAllowed()) {
  461. /*
  462. * If invalid values are not allowed the value must be validated
  463. * before it is set. If validation fails, the
  464. * InvalidValueException is thrown and the internal value is not
  465. * updated.
  466. */
  467. validate(newFieldValue);
  468. }
  469. // Changes the value
  470. setInternalValue(newFieldValue);
  471. setModified(dataSource != null);
  472. valueWasModifiedByDataSourceDuringCommit = false;
  473. // In not buffering, try to commit
  474. if (!isBuffered() && dataSource != null
  475. && (isInvalidCommitted() || isValid())) {
  476. try {
  477. // Commits the value to datasource
  478. committingValueToDataSource = true;
  479. getPropertyDataSource().setValue(
  480. convertToModel(newFieldValue));
  481. // The buffer is now unmodified
  482. setModified(false);
  483. } catch (final Throwable e) {
  484. // Sets the buffering state
  485. currentBufferedSourceException = new Buffered.SourceException(
  486. this, e);
  487. markAsDirty();
  488. // Throws the source exception
  489. throw currentBufferedSourceException;
  490. } finally {
  491. committingValueToDataSource = false;
  492. }
  493. }
  494. // If successful, remove set the buffering state to be ok
  495. if (getCurrentBufferedSourceException() != null) {
  496. setCurrentBufferedSourceException(null);
  497. }
  498. if (valueWasModifiedByDataSourceDuringCommit) {
  499. /*
  500. * Value was modified by datasource. Force repaint even if
  501. * repaint was not requested.
  502. */
  503. valueWasModifiedByDataSourceDuringCommit = repaintIsNotNeeded = false;
  504. }
  505. // Fires the value change
  506. fireValueChange(repaintIsNotNeeded);
  507. }
  508. }
  509. @Deprecated
  510. static boolean equals(Object value1, Object value2) {
  511. return SharedUtil.equals(value1, value2);
  512. }
  513. /* External data source */
  514. /**
  515. * Gets the current data source of the field, if any.
  516. *
  517. * @return the current data source as a Property, or <code>null</code> if
  518. * none defined.
  519. */
  520. @Override
  521. public Property getPropertyDataSource() {
  522. return dataSource;
  523. }
  524. /**
  525. * <p>
  526. * Sets the specified Property as the data source for the field. All
  527. * uncommitted changes are replaced with a value from the new data source.
  528. * </p>
  529. *
  530. * <p>
  531. * If the datasource has any validators, the same validators are added to
  532. * the field. Because the default behavior of the field is to allow invalid
  533. * values, but not to allow committing them, this only adds visual error
  534. * messages to fields and do not allow committing them as long as the value
  535. * is invalid. After the value is valid, the error message is not shown and
  536. * the commit can be done normally.
  537. * </p>
  538. *
  539. * <p>
  540. * If the data source implements
  541. * {@link com.vaadin.data.Property.ValueChangeNotifier} and/or
  542. * {@link com.vaadin.data.Property.ReadOnlyStatusChangeNotifier}, the field
  543. * registers itself as a listener and updates itself according to the events
  544. * it receives. To avoid memory leaks caused by references to a field no
  545. * longer in use, the listener registrations are removed on
  546. * {@link AbstractField#detach() detach} and re-added on
  547. * {@link AbstractField#attach() attach}.
  548. * </p>
  549. *
  550. * <p>
  551. * Note: before 6.5 we actually called discard() method in the beginning of
  552. * the method. This was removed to simplify implementation, avoid excess
  553. * calls to backing property and to avoid odd value change events that were
  554. * previously fired (developer expects 0-1 value change events if this
  555. * method is called). Some complex field implementations might now need to
  556. * override this method to do housekeeping similar to discard().
  557. * </p>
  558. *
  559. * @param newDataSource
  560. * the new data source Property.
  561. */
  562. @Override
  563. public void setPropertyDataSource(Property newDataSource) {
  564. // Saves the old value
  565. final Object oldValue = getInternalValue();
  566. // Stop listening to the old data source
  567. removePropertyListeners();
  568. // Sets the new data source
  569. dataSource = newDataSource;
  570. getState().propertyReadOnly = dataSource == null ? false : dataSource
  571. .isReadOnly();
  572. // Check if the current converter is compatible.
  573. if (newDataSource != null
  574. && !ConverterUtil.canConverterPossiblyHandle(getConverter(),
  575. getType(), newDataSource.getType())) {
  576. // There is no converter set or there is no way the current
  577. // converter can be compatible.
  578. setConverter(newDataSource.getType());
  579. }
  580. // Gets the value from source. This requires that a valid converter has
  581. // been set.
  582. try {
  583. if (dataSource != null) {
  584. T fieldValue = convertFromModel(getDataSourceValue());
  585. setInternalValue(fieldValue);
  586. }
  587. setModified(false);
  588. if (getCurrentBufferedSourceException() != null) {
  589. setCurrentBufferedSourceException(null);
  590. }
  591. } catch (final Throwable e) {
  592. setCurrentBufferedSourceException(new Buffered.SourceException(
  593. this, e));
  594. setModified(true);
  595. throw getCurrentBufferedSourceException();
  596. }
  597. // Listen to new data source if possible
  598. addPropertyListeners();
  599. // Copy the validators from the data source
  600. if (dataSource instanceof Validatable) {
  601. final Collection<Validator> validators = ((Validatable) dataSource)
  602. .getValidators();
  603. if (validators != null) {
  604. for (final Iterator<Validator> i = validators.iterator(); i
  605. .hasNext();) {
  606. addValidator(i.next());
  607. }
  608. }
  609. }
  610. // Fires value change if the value has changed
  611. T value = getInternalValue();
  612. if ((value != oldValue)
  613. && ((value != null && !value.equals(oldValue)) || value == null)) {
  614. fireValueChange(false);
  615. }
  616. }
  617. /**
  618. * Retrieves a converter for the field from the converter factory defined
  619. * for the application. Clears the converter if no application reference is
  620. * available or if the factory returns null.
  621. *
  622. * @param datamodelType
  623. * The type of the data model that we want to be able to convert
  624. * from
  625. */
  626. public void setConverter(Class<?> datamodelType) {
  627. Converter<T, ?> c = (Converter<T, ?>) ConverterUtil.getConverter(
  628. getType(), datamodelType, getSession());
  629. setConverter(c);
  630. }
  631. /**
  632. * Convert the given value from the data source type to the UI type.
  633. *
  634. * @param newValue
  635. * The data source value to convert.
  636. * @return The converted value that is compatible with the UI type or the
  637. * original value if its type is compatible and no converter is set.
  638. * @throws Converter.ConversionException
  639. * if there is no converter and the type is not compatible with
  640. * the data source type.
  641. */
  642. private T convertFromModel(Object newValue) {
  643. return convertFromModel(newValue, getLocale());
  644. }
  645. /**
  646. * Convert the given value from the data source type to the UI type.
  647. *
  648. * @param newValue
  649. * The data source value to convert.
  650. * @return The converted value that is compatible with the UI type or the
  651. * original value if its type is compatible and no converter is set.
  652. * @throws Converter.ConversionException
  653. * if there is no converter and the type is not compatible with
  654. * the data source type.
  655. */
  656. private T convertFromModel(Object newValue, Locale locale) {
  657. return ConverterUtil.convertFromModel(newValue, getType(),
  658. getConverter(), locale);
  659. }
  660. /**
  661. * Convert the given value from the UI type to the data source type.
  662. *
  663. * @param fieldValue
  664. * The value to convert. Typically returned by
  665. * {@link #getFieldValue()}
  666. * @return The converted value that is compatible with the data source type.
  667. * @throws Converter.ConversionException
  668. * if there is no converter and the type is not compatible with
  669. * the data source type.
  670. */
  671. private Object convertToModel(T fieldValue)
  672. throws Converter.ConversionException {
  673. return convertToModel(fieldValue, getLocale());
  674. }
  675. /**
  676. * Convert the given value from the UI type to the data source type.
  677. *
  678. * @param fieldValue
  679. * The value to convert. Typically returned by
  680. * {@link #getFieldValue()}
  681. * @param locale
  682. * The locale to use for the conversion
  683. * @return The converted value that is compatible with the data source type.
  684. * @throws Converter.ConversionException
  685. * if there is no converter and the type is not compatible with
  686. * the data source type.
  687. */
  688. private Object convertToModel(T fieldValue, Locale locale)
  689. throws Converter.ConversionException {
  690. Class<?> modelType = getModelType();
  691. try {
  692. return ConverterUtil.convertToModel(fieldValue,
  693. (Class<Object>) modelType, getConverter(), locale);
  694. } catch (ConversionException e) {
  695. throw new ConversionException(getConversionError(modelType, e), e);
  696. }
  697. }
  698. /**
  699. * Retrieves the type of the currently used data model. If the field has no
  700. * data source then the model type of the converter is used.
  701. *
  702. * @since 7.1
  703. * @return The type of the currently used data model or null if no data
  704. * source or converter is set.
  705. */
  706. protected Class<?> getModelType() {
  707. Property<?> pd = getPropertyDataSource();
  708. if (pd != null) {
  709. return pd.getType();
  710. } else if (getConverter() != null) {
  711. return getConverter().getModelType();
  712. }
  713. return null;
  714. }
  715. /**
  716. * Returns the conversion error with {0} replaced by the data source type
  717. * and {1} replaced by the exception (localized) message.
  718. *
  719. * @since 7.1
  720. * @param dataSourceType
  721. * the type of the data source
  722. * @param e
  723. * a conversion exception which can provide additional
  724. * information
  725. * @return The value conversion error string with parameters replaced.
  726. */
  727. protected String getConversionError(Class<?> dataSourceType,
  728. ConversionException e) {
  729. String conversionError = getConversionError();
  730. if (conversionError != null) {
  731. if (dataSourceType != null) {
  732. conversionError = conversionError.replace("{0}",
  733. dataSourceType.getSimpleName());
  734. }
  735. if (e != null) {
  736. conversionError = conversionError.replace("{1}",
  737. e.getLocalizedMessage());
  738. }
  739. }
  740. return conversionError;
  741. }
  742. /**
  743. * Returns the current value (as returned by {@link #getValue()}) converted
  744. * to the data source type.
  745. * <p>
  746. * This returns the same as {@link AbstractField#getValue()} if no converter
  747. * has been set. The value is not necessarily the same as the data source
  748. * value e.g. if the field is in buffered mode and has been modified.
  749. * </p>
  750. *
  751. * @return The converted value that is compatible with the data source type
  752. */
  753. public Object getConvertedValue() {
  754. return convertToModel(getFieldValue());
  755. }
  756. /**
  757. * Sets the value of the field using a value of the data source type. The
  758. * value given is converted to the field type and then assigned to the
  759. * field. This will update the property data source in the same way as when
  760. * {@link #setValue(Object)} is called.
  761. *
  762. * @param value
  763. * The value to set. Must be the same type as the data source.
  764. */
  765. public void setConvertedValue(Object value) {
  766. setValue(convertFromModel(value));
  767. }
  768. /* Validation */
  769. /**
  770. * Adds a new validator for the field's value. All validators added to a
  771. * field are checked each time the its value changes.
  772. *
  773. * @param validator
  774. * the new validator to be added.
  775. */
  776. @Override
  777. public void addValidator(Validator validator) {
  778. if (validators == null) {
  779. validators = new LinkedList<Validator>();
  780. }
  781. validators.add(validator);
  782. markAsDirty();
  783. }
  784. /**
  785. * Gets the validators of the field.
  786. *
  787. * @return An unmodifiable collection that holds all validators for the
  788. * field.
  789. */
  790. @Override
  791. public Collection<Validator> getValidators() {
  792. if (validators == null) {
  793. return Collections.emptyList();
  794. } else {
  795. return Collections.unmodifiableCollection(validators);
  796. }
  797. }
  798. private boolean hasValidators() {
  799. return validators != null && !validators.isEmpty();
  800. }
  801. /**
  802. * Removes the validator from the field.
  803. *
  804. * @param validator
  805. * the validator to remove.
  806. */
  807. @Override
  808. public void removeValidator(Validator validator) {
  809. if (validators != null) {
  810. validators.remove(validator);
  811. }
  812. markAsDirty();
  813. }
  814. /**
  815. * Removes all validators from the field.
  816. */
  817. @Override
  818. public void removeAllValidators() {
  819. if (validators != null) {
  820. validators.clear();
  821. }
  822. markAsDirty();
  823. }
  824. /**
  825. * Tests the current value against registered validators if the field is not
  826. * empty. If the field is empty it is considered valid if it is not required
  827. * and invalid otherwise. Validators are never checked for empty fields.
  828. *
  829. * In most cases, {@link #validate()} should be used instead of
  830. * {@link #isValid()} to also get the error message.
  831. *
  832. * @return <code>true</code> if all registered validators claim that the
  833. * current value is valid or if the field is empty and not required,
  834. * <code>false</code> otherwise.
  835. */
  836. @Override
  837. public boolean isValid() {
  838. try {
  839. validate();
  840. return true;
  841. } catch (InvalidValueException e) {
  842. return false;
  843. }
  844. }
  845. /**
  846. * Checks the validity of the Field.
  847. *
  848. * A field is invalid if it is set as required (using
  849. * {@link #setRequired(boolean)} and is empty, if one or several of the
  850. * validators added to the field indicate it is invalid or if the value
  851. * cannot be converted provided a converter has been set.
  852. *
  853. * The "required" validation is a built-in validation feature. If the field
  854. * is required and empty this method throws an EmptyValueException with the
  855. * error message set using {@link #setRequiredError(String)}.
  856. *
  857. * @see com.vaadin.data.Validatable#validate()
  858. */
  859. @Override
  860. public void validate() throws Validator.InvalidValueException {
  861. if (isRequired() && isEmpty()) {
  862. throw new Validator.EmptyValueException(requiredError);
  863. }
  864. validate(getFieldValue());
  865. }
  866. /**
  867. * Validates that the given value pass the validators for the field.
  868. * <p>
  869. * This method does not check the requiredness of the field.
  870. *
  871. * @param fieldValue
  872. * The value to check
  873. * @throws Validator.InvalidValueException
  874. * if one or several validators fail
  875. */
  876. protected void validate(T fieldValue)
  877. throws Validator.InvalidValueException {
  878. Object valueToValidate = fieldValue;
  879. // If there is a converter we start by converting the value as we want
  880. // to validate the converted value
  881. if (getConverter() != null) {
  882. try {
  883. valueToValidate = getConverter().convertToModel(fieldValue,
  884. getModelType(), getLocale());
  885. } catch (ConversionException e) {
  886. throw new InvalidValueException(getConversionError(
  887. getConverter().getModelType(), e));
  888. }
  889. }
  890. List<InvalidValueException> validationExceptions = new ArrayList<InvalidValueException>();
  891. if (validators != null) {
  892. // Gets all the validation errors
  893. for (Validator v : validators) {
  894. try {
  895. v.validate(valueToValidate);
  896. } catch (final Validator.InvalidValueException e) {
  897. validationExceptions.add(e);
  898. }
  899. }
  900. }
  901. // If there were no errors
  902. if (validationExceptions.isEmpty()) {
  903. return;
  904. }
  905. // If only one error occurred, throw it forwards
  906. if (validationExceptions.size() == 1) {
  907. throw validationExceptions.get(0);
  908. }
  909. InvalidValueException[] exceptionArray = validationExceptions
  910. .toArray(new InvalidValueException[validationExceptions.size()]);
  911. // Create a composite validator and include all exceptions
  912. throw new Validator.InvalidValueException(null, exceptionArray);
  913. }
  914. /**
  915. * Fields allow invalid values by default. In most cases this is wanted,
  916. * because the field otherwise visually forget the user input immediately.
  917. *
  918. * @return true iff the invalid values are allowed.
  919. * @see com.vaadin.data.Validatable#isInvalidAllowed()
  920. */
  921. @Override
  922. public boolean isInvalidAllowed() {
  923. return invalidAllowed;
  924. }
  925. /**
  926. * Fields allow invalid values by default. In most cases this is wanted,
  927. * because the field otherwise visually forget the user input immediately.
  928. * <p>
  929. * In common setting where the user wants to assure the correctness of the
  930. * datasource, but allow temporarily invalid contents in the field, the user
  931. * should add the validators to datasource, that should not allow invalid
  932. * values. The validators are automatically copied to the field when the
  933. * datasource is set.
  934. * </p>
  935. *
  936. * @see com.vaadin.data.Validatable#setInvalidAllowed(boolean)
  937. */
  938. @Override
  939. public void setInvalidAllowed(boolean invalidAllowed)
  940. throws UnsupportedOperationException {
  941. this.invalidAllowed = invalidAllowed;
  942. }
  943. /**
  944. * Error messages shown by the fields are composites of the error message
  945. * thrown by the superclasses (that is the component error message),
  946. * validation errors and buffered source errors.
  947. *
  948. * @see com.vaadin.ui.AbstractComponent#getErrorMessage()
  949. */
  950. @Override
  951. public ErrorMessage getErrorMessage() {
  952. /*
  953. * Check validation errors only if automatic validation is enabled.
  954. * Empty, required fields will generate a validation error containing
  955. * the requiredError string. For these fields the exclamation mark will
  956. * be hidden but the error must still be sent to the client.
  957. */
  958. Validator.InvalidValueException validationError = null;
  959. if (isValidationVisible()) {
  960. try {
  961. validate();
  962. } catch (Validator.InvalidValueException e) {
  963. if (!e.isInvisible()) {
  964. validationError = e;
  965. }
  966. }
  967. }
  968. // Check if there are any systems errors
  969. final ErrorMessage superError = super.getErrorMessage();
  970. // Return if there are no errors at all
  971. if (superError == null && validationError == null
  972. && getCurrentBufferedSourceException() == null) {
  973. return null;
  974. }
  975. // Throw combination of the error types
  976. return new CompositeErrorMessage(
  977. new ErrorMessage[] {
  978. superError,
  979. AbstractErrorMessage
  980. .getErrorMessageForException(validationError),
  981. AbstractErrorMessage
  982. .getErrorMessageForException(getCurrentBufferedSourceException()) });
  983. }
  984. /* Value change events */
  985. private static final Method VALUE_CHANGE_METHOD;
  986. static {
  987. try {
  988. VALUE_CHANGE_METHOD = Property.ValueChangeListener.class
  989. .getDeclaredMethod("valueChange",
  990. new Class[] { Property.ValueChangeEvent.class });
  991. } catch (final java.lang.NoSuchMethodException e) {
  992. // This should never happen
  993. throw new java.lang.RuntimeException(
  994. "Internal error finding methods in AbstractField");
  995. }
  996. }
  997. /*
  998. * Adds a value change listener for the field. Don't add a JavaDoc comment
  999. * here, we use the default documentation from the implemented interface.
  1000. */
  1001. @Override
  1002. public void addValueChangeListener(Property.ValueChangeListener listener) {
  1003. addListener(AbstractField.ValueChangeEvent.class, listener,
  1004. VALUE_CHANGE_METHOD);
  1005. // ensure "automatic immediate handling" works
  1006. markAsDirty();
  1007. }
  1008. /**
  1009. * @deprecated As of 7.0, replaced by
  1010. * {@link #addValueChangeListener(com.vaadin.data.Property.ValueChangeListener)}
  1011. **/
  1012. @Override
  1013. @Deprecated
  1014. public void addListener(Property.ValueChangeListener listener) {
  1015. addValueChangeListener(listener);
  1016. }
  1017. /*
  1018. * Removes a value change listener from the field. Don't add a JavaDoc
  1019. * comment here, we use the default documentation from the implemented
  1020. * interface.
  1021. */
  1022. @Override
  1023. public void removeValueChangeListener(Property.ValueChangeListener listener) {
  1024. removeListener(AbstractField.ValueChangeEvent.class, listener,
  1025. VALUE_CHANGE_METHOD);
  1026. // ensure "automatic immediate handling" works
  1027. markAsDirty();
  1028. }
  1029. /**
  1030. * @deprecated As of 7.0, replaced by
  1031. * {@link #removeValueChangeListener(com.vaadin.data.Property.ValueChangeListener)}
  1032. **/
  1033. @Override
  1034. @Deprecated
  1035. public void removeListener(Property.ValueChangeListener listener) {
  1036. removeValueChangeListener(listener);
  1037. }
  1038. /**
  1039. * Emits the value change event. The value contained in the field is
  1040. * validated before the event is created.
  1041. */
  1042. protected void fireValueChange(boolean repaintIsNotNeeded) {
  1043. fireEvent(new AbstractField.ValueChangeEvent(this));
  1044. if (!repaintIsNotNeeded) {
  1045. markAsDirty();
  1046. }
  1047. }
  1048. /* Read-only status change events */
  1049. private static final Method READ_ONLY_STATUS_CHANGE_METHOD;
  1050. static {
  1051. try {
  1052. READ_ONLY_STATUS_CHANGE_METHOD = Property.ReadOnlyStatusChangeListener.class
  1053. .getDeclaredMethod(
  1054. "readOnlyStatusChange",
  1055. new Class[] { Property.ReadOnlyStatusChangeEvent.class });
  1056. } catch (final java.lang.NoSuchMethodException e) {
  1057. // This should never happen
  1058. throw new java.lang.RuntimeException(
  1059. "Internal error finding methods in AbstractField");
  1060. }
  1061. }
  1062. /**
  1063. * React to read only status changes of the property by requesting a
  1064. * repaint.
  1065. *
  1066. * @see Property.ReadOnlyStatusChangeListener
  1067. */
  1068. @Override
  1069. public void readOnlyStatusChange(Property.ReadOnlyStatusChangeEvent event) {
  1070. getState().propertyReadOnly = event.getProperty().isReadOnly();
  1071. }
  1072. /**
  1073. * An <code>Event</code> object specifying the Property whose read-only
  1074. * status has changed.
  1075. *
  1076. * @author Vaadin Ltd.
  1077. * @since 3.0
  1078. */
  1079. public static class ReadOnlyStatusChangeEvent extends Component.Event
  1080. implements Property.ReadOnlyStatusChangeEvent, Serializable {
  1081. /**
  1082. * New instance of text change event.
  1083. *
  1084. * @param source
  1085. * the Source of the event.
  1086. */
  1087. public ReadOnlyStatusChangeEvent(AbstractField source) {
  1088. super(source);
  1089. }
  1090. /**
  1091. * Property where the event occurred.
  1092. *
  1093. * @return the Source of the event.
  1094. */
  1095. @Override
  1096. public Property getProperty() {
  1097. return (Property) getSource();
  1098. }
  1099. }
  1100. /*
  1101. * Adds a read-only status change listener for the field. Don't add a
  1102. * JavaDoc comment here, we use the default documentation from the
  1103. * implemented interface.
  1104. */
  1105. @Override
  1106. public void addReadOnlyStatusChangeListener(
  1107. Property.ReadOnlyStatusChangeListener listener) {
  1108. addListener(Property.ReadOnlyStatusChangeEvent.class, listener,
  1109. READ_ONLY_STATUS_CHANGE_METHOD);
  1110. }
  1111. /**
  1112. * @deprecated As of 7.0, replaced by
  1113. * {@link #addReadOnlyStatusChangeListener(com.vaadin.data.Property.ReadOnlyStatusChangeListener)}
  1114. **/
  1115. @Override
  1116. @Deprecated
  1117. public void addListener(Property.ReadOnlyStatusChangeListener listener) {
  1118. addReadOnlyStatusChangeListener(listener);
  1119. }
  1120. /*
  1121. * Removes a read-only status change listener from the field. Don't add a
  1122. * JavaDoc comment here, we use the default documentation from the
  1123. * implemented interface.
  1124. */
  1125. @Override
  1126. public void removeReadOnlyStatusChangeListener(
  1127. Property.ReadOnlyStatusChangeListener listener) {
  1128. removeListener(Property.ReadOnlyStatusChangeEvent.class, listener,
  1129. READ_ONLY_STATUS_CHANGE_METHOD);
  1130. }
  1131. /**
  1132. * @deprecated As of 7.0, replaced by
  1133. * {@link #removeReadOnlyStatusChangeListener(com.vaadin.data.Property.ReadOnlyStatusChangeListener)}
  1134. **/
  1135. @Override
  1136. @Deprecated
  1137. public void removeListener(Property.ReadOnlyStatusChangeListener listener) {
  1138. removeReadOnlyStatusChangeListener(listener);
  1139. }
  1140. /**
  1141. * Emits the read-only status change event. The value contained in the field
  1142. * is validated before the event is created.
  1143. */
  1144. protected void fireReadOnlyStatusChange() {
  1145. fireEvent(new AbstractField.ReadOnlyStatusChangeEvent(this));
  1146. }
  1147. /**
  1148. * This method listens to data source value changes and passes the changes
  1149. * forwards.
  1150. *
  1151. * Changes are not forwarded to the listeners of the field during internal
  1152. * operations of the field to avoid duplicate notifications.
  1153. *
  1154. * @param event
  1155. * the value change event telling the data source contents have
  1156. * changed.
  1157. */
  1158. @Override
  1159. public void valueChange(Property.ValueChangeEvent event) {
  1160. if (!isBuffered()) {
  1161. if (committingValueToDataSource) {
  1162. boolean propertyNotifiesOfTheBufferedValue = SharedUtil.equals(
  1163. event.getProperty().getValue(), getInternalValue());
  1164. if (!propertyNotifiesOfTheBufferedValue) {
  1165. /*
  1166. * Property (or chained property like PropertyFormatter) now
  1167. * reports different value than the one the field has just
  1168. * committed to it. In this case we respect the property
  1169. * value.
  1170. *
  1171. * Still, we don't fire value change yet, but instead
  1172. * postpone it until "commit" is done. See setValue(Object,
  1173. * boolean) and commit().
  1174. */
  1175. readValueFromProperty(event);
  1176. valueWasModifiedByDataSourceDuringCommit = true;
  1177. }
  1178. } else if (!isModified()) {
  1179. readValueFromProperty(event);
  1180. fireValueChange(false);
  1181. }
  1182. }
  1183. }
  1184. private void readValueFromProperty(Property.ValueChangeEvent event) {
  1185. setInternalValue(convertFromModel(event.getProperty().getValue()));
  1186. }
  1187. /**
  1188. * {@inheritDoc}
  1189. */
  1190. @Override
  1191. public void focus() {
  1192. super.focus();
  1193. }
  1194. /*
  1195. * (non-Javadoc)
  1196. *
  1197. * @see com.vaadin.ui.Component.Focusable#getTabIndex()
  1198. */
  1199. @Override
  1200. public int getTabIndex() {
  1201. return getState(false).tabIndex;
  1202. }
  1203. /*
  1204. * (non-Javadoc)
  1205. *
  1206. * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
  1207. */
  1208. @Override
  1209. public void setTabIndex(int tabIndex) {
  1210. getState().tabIndex = tabIndex;
  1211. }
  1212. /**
  1213. * Returns the internal field value, which might not match the data source
  1214. * value e.g. if the field has been modified and is not in write-through
  1215. * mode.
  1216. *
  1217. * This method can be overridden by subclasses together with
  1218. * {@link #setInternalValue(Object)} to compute internal field value at
  1219. * runtime. When doing so, typically also {@link #isModified()} needs to be
  1220. * overridden and care should be taken in the management of the empty state
  1221. * and buffering support.
  1222. *
  1223. * @return internal field value
  1224. */
  1225. protected T getInternalValue() {
  1226. return value;
  1227. }
  1228. /**
  1229. * Sets the internal field value. This is purely used by AbstractField to
  1230. * change the internal Field value. It does not trigger valuechange events.
  1231. * It can be overridden by the inheriting classes to update all dependent
  1232. * variables.
  1233. *
  1234. * Subclasses can also override {@link #getInternalValue()} if necessary.
  1235. *
  1236. * @param newValue
  1237. * the new value to be set.
  1238. */
  1239. protected void setInternalValue(T newValue) {
  1240. value = newValue;
  1241. valueLocale = getLocale();
  1242. if (validators != null && !validators.isEmpty()) {
  1243. markAsDirty();
  1244. }
  1245. }
  1246. /**
  1247. * Notifies the component that it is connected to an application.
  1248. *
  1249. * @see com.vaadin.ui.Component#attach()
  1250. */
  1251. @Override
  1252. public void attach() {
  1253. super.attach();
  1254. localeMightHaveChanged();
  1255. if (!isListeningToPropertyEvents) {
  1256. addPropertyListeners();
  1257. if (!isModified() && !isBuffered()) {
  1258. // Update value from data source
  1259. updateValueFromDataSource();
  1260. }
  1261. }
  1262. }
  1263. @Override
  1264. public void setLocale(Locale locale) {
  1265. super.setLocale(locale);
  1266. localeMightHaveChanged();
  1267. }
  1268. private void localeMightHaveChanged() {
  1269. if (!SharedUtil.equals(valueLocale, getLocale())) {
  1270. // The locale HAS actually changed
  1271. if (dataSource != null && !isModified()) {
  1272. // When we have a data source and the internal value is directly
  1273. // read from that we want to update the value
  1274. T newInternalValue = convertFromModel(getPropertyDataSource()
  1275. .getValue());
  1276. if (!SharedUtil.equals(newInternalValue, getInternalValue())) {
  1277. setInternalValue(newInternalValue);
  1278. fireValueChange(false);
  1279. }
  1280. } else if (dataSource == null && converter != null) {
  1281. /*
  1282. * No data source but a converter has been set. The same issues
  1283. * as above but we cannot use propertyDataSource. Convert the
  1284. * current value back to a model value using the old locale and
  1285. * then convert back using the new locale. If this does not
  1286. * match the field value we need to set the converted value
  1287. * again.
  1288. */
  1289. Object convertedValue = convertToModel(getInternalValue(),
  1290. valueLocale);
  1291. T newinternalValue = convertFromModel(convertedValue);
  1292. if (!SharedUtil.equals(getInternalValue(), newinternalValue)) {
  1293. setInternalValue(newinternalValue);
  1294. fireValueChange(false);
  1295. }
  1296. }
  1297. }
  1298. }
  1299. @Override
  1300. public void detach() {
  1301. super.detach();
  1302. // Stop listening to data source events on detach to avoid a potential
  1303. // memory leak. See #6155.
  1304. removePropertyListeners();
  1305. }
  1306. /**
  1307. * Is this field required. Required fields must filled by the user.
  1308. *
  1309. * If the field is required, it is visually indicated in the user interface.
  1310. * Furthermore, setting field to be required implicitly adds "non-empty"
  1311. * validator and thus isValid() == false or any isEmpty() fields. In those
  1312. * cases validation errors are not painted as it is obvious that the user
  1313. * must fill in the required fields.
  1314. *
  1315. * On the other hand, for the non-required fields isValid() == true if the
  1316. * field isEmpty() regardless of any attached validators.
  1317. *
  1318. *
  1319. * @return <code>true</code> if the field is required, otherwise
  1320. * <code>false</code>.
  1321. */
  1322. @Override
  1323. public boolean isRequired() {
  1324. return getState(false).required;
  1325. }
  1326. /**
  1327. * Sets the field required. Required fields must filled by the user.
  1328. *
  1329. * If the field is required, it is visually indicated in the user interface.
  1330. * Furthermore, setting field to be required implicitly adds "non-empty"
  1331. * validator and thus isValid() == false or any isEmpty() fields. In those
  1332. * cases validation errors are not painted as it is obvious that the user
  1333. * must fill in the required fields.
  1334. *
  1335. * On the other hand, for the non-required fields isValid() == true if the
  1336. * field isEmpty() regardless of any attached validators.
  1337. *
  1338. * @param required
  1339. * Is the field required.
  1340. */
  1341. @Override
  1342. public void setRequired(boolean required) {
  1343. getState().required = required;
  1344. }
  1345. /**
  1346. * Set the error that is show if this field is required, but empty. When
  1347. * setting requiredMessage to be "" or null, no error pop-up or exclamation
  1348. * mark is shown for a empty required field. This faults to "". Even in
  1349. * those cases isValid() returns false for empty required fields.
  1350. *
  1351. * @param requiredMessage
  1352. * Message to be shown when this field is required, but empty.
  1353. */
  1354. @Override
  1355. public void setRequiredError(String requiredMessage) {
  1356. requiredError = requiredMessage;
  1357. markAsDirty();
  1358. }
  1359. @Override
  1360. public String getRequiredError() {
  1361. return requiredError;
  1362. }
  1363. /**
  1364. * Gets the error that is shown if the field value cannot be converted to
  1365. * the data source type.
  1366. *
  1367. * @return The error that is shown if conversion of the field value fails
  1368. */
  1369. public String getConversionError() {
  1370. return conversionError;
  1371. }
  1372. /**
  1373. * Sets the error that is shown if the field value cannot be converted to
  1374. * the data source type. If {0} is present in the message, it will be
  1375. * replaced by the simple name of the data source type. If {1} is present in
  1376. * the message, it will be replaced by the ConversionException message.
  1377. *
  1378. * @param valueConversionError
  1379. * Message to be shown when conversion of the value fails
  1380. */
  1381. public void setConversionError(String valueConversionError) {
  1382. this.conversionError = valueConversionError;
  1383. markAsDirty();
  1384. }
  1385. @Override
  1386. public boolean isEmpty() {
  1387. return (getFieldValue() == null);
  1388. }
  1389. @Override
  1390. public void clear() {
  1391. setValue(null);
  1392. }
  1393. /**
  1394. * Is automatic, visible validation enabled?
  1395. *
  1396. * If automatic validation is enabled, any validators connected to this
  1397. * component are evaluated while painting the component and potential error
  1398. * messages are sent to client. If the automatic validation is turned off,
  1399. * isValid() and validate() methods still work, but one must show the
  1400. * validation in their own code.
  1401. *
  1402. * @return True, if automatic validation is enabled.
  1403. */
  1404. public boolean isValidationVisible() {
  1405. return validationVisible;
  1406. }
  1407. /**
  1408. * Enable or disable automatic, visible validation.
  1409. *
  1410. * If automatic validation is enabled, any validators connected to this
  1411. * component are evaluated while painting the component and potential error
  1412. * messages are sent to client. If the automatic validation is turned off,
  1413. * isValid() and validate() methods still work, but one must show the
  1414. * validation in their own code.
  1415. *
  1416. * @param validateAutomatically
  1417. * True, if automatic validation is enabled.
  1418. */
  1419. public void setValidationVisible(boolean validateAutomatically) {
  1420. if (validationVisible != validateAutomatically) {
  1421. markAsDirty();
  1422. validationVisible = validateAutomatically;
  1423. }
  1424. }
  1425. /**
  1426. * Sets the current buffered source exception.
  1427. *
  1428. * @param currentBufferedSourceException
  1429. */
  1430. public void setCurrentBufferedSourceException(
  1431. Buffered.SourceException currentBufferedSourceException) {
  1432. this.currentBufferedSourceException = currentBufferedSourceException;
  1433. markAsDirty();
  1434. }
  1435. /**
  1436. * Gets the current buffered source exception.
  1437. *
  1438. * @return The current source exception
  1439. */
  1440. protected Buffered.SourceException getCurrentBufferedSourceException() {
  1441. return currentBufferedSourceException;
  1442. }
  1443. /**
  1444. * A ready-made {@link ShortcutListener} that focuses the given
  1445. * {@link Focusable} (usually a {@link Field}) when the keyboard shortcut is
  1446. * invoked.
  1447. *
  1448. */
  1449. public static class FocusShortcut extends ShortcutListener {
  1450. protected Focusable focusable;
  1451. /**
  1452. * Creates a keyboard shortcut for focusing the given {@link Focusable}
  1453. * using the shorthand notation defined in {@link ShortcutAction}.
  1454. *
  1455. * @param focusable
  1456. * to focused when the shortcut is invoked
  1457. * @param shorthandCaption
  1458. * caption with keycode and modifiers indicated
  1459. */
  1460. public FocusShortcut(Focusable focusable, String shorthandCaption) {
  1461. super(shorthandCaption);
  1462. this.focusable = focusable;
  1463. }
  1464. /**
  1465. * Creates a keyboard shortcut for focusing the given {@link Focusable}.
  1466. *
  1467. * @param focusable
  1468. * to focused when the shortcut is invoked
  1469. * @param keyCode
  1470. * keycode that invokes the shortcut
  1471. * @param modifiers
  1472. * modifiers required to invoke the shortcut
  1473. */
  1474. public FocusShortcut(Focusable focusable, int keyCode, int... modifiers) {
  1475. super(null, keyCode, modifiers);
  1476. this.focusable = focusable;
  1477. }
  1478. /**
  1479. * Creates a keyboard shortcut for focusing the given {@link Focusable}.
  1480. *
  1481. * @param focusable
  1482. * to focused when the shortcut is invoked
  1483. * @param keyCode
  1484. * keycode that invokes the shortcut
  1485. */
  1486. public FocusShortcut(Focusable focusable, int keyCode) {
  1487. this(focusable, keyCode, null);
  1488. }
  1489. @Override
  1490. public void handleAction(Object sender, Object target) {
  1491. focusable.focus();
  1492. }
  1493. }
  1494. private void updateValueFromDataSource() {
  1495. if (dataSource != null) {
  1496. // Gets the correct value from datasource
  1497. T newFieldValue;
  1498. try {
  1499. // Discards buffer by overwriting from datasource
  1500. newFieldValue = convertFromModel(getDataSourceValue());
  1501. // If successful, remove set the buffering state to be ok
  1502. if (getCurrentBufferedSourceException() != null) {
  1503. setCurrentBufferedSourceException(null);
  1504. }
  1505. } catch (final Throwable e) {
  1506. // FIXME: What should really be done here if conversion fails?
  1507. // Sets the buffering state
  1508. currentBufferedSourceException = new Buffered.SourceException(
  1509. this, e);
  1510. markAsDirty();
  1511. // Throws the source exception
  1512. throw currentBufferedSourceException;
  1513. }
  1514. final boolean wasModified = isModified();
  1515. setModified(false);
  1516. // If the new value differs from the previous one
  1517. if (!SharedUtil.equals(newFieldValue, getInternalValue())) {
  1518. setInternalValue(newFieldValue);
  1519. fireValueChange(false);
  1520. } else if (wasModified) {
  1521. // If the value did not change, but the modification status did
  1522. markAsDirty();
  1523. }
  1524. }
  1525. }
  1526. /**
  1527. * Gets the converter used to convert the property data source value to the
  1528. * field value.
  1529. *
  1530. * @return The converter or null if none is set.
  1531. */
  1532. public Converter<T, Object> getConverter() {
  1533. return converter;
  1534. }
  1535. /**
  1536. * Sets the converter used to convert the field value to property data
  1537. * source type. The converter must have a presentation type that matches the
  1538. * field type.
  1539. *
  1540. * @param converter
  1541. * The new converter to use.
  1542. */
  1543. public void setConverter(Converter<T, ?> converter) {
  1544. this.converter = (Converter<T, Object>) converter;
  1545. markAsDirty();
  1546. }
  1547. @Override
  1548. protected AbstractFieldState getState() {
  1549. return (AbstractFieldState) super.getState();
  1550. }
  1551. @Override
  1552. protected AbstractFieldState getState(boolean markAsDirty) {
  1553. return (AbstractFieldState) super.getState(markAsDirty);
  1554. }
  1555. @Override
  1556. public void beforeClientResponse(boolean initial) {
  1557. super.beforeClientResponse(initial);
  1558. // Hide the error indicator if needed
  1559. getState().hideErrors = shouldHideErrors();
  1560. }
  1561. /**
  1562. * Registers this as an event listener for events sent by the data source
  1563. * (if any). Does nothing if
  1564. * <code>isListeningToPropertyEvents == true</code>.
  1565. */
  1566. private void addPropertyListeners() {
  1567. if (!isListeningToPropertyEvents) {
  1568. if (dataSource instanceof Property.ValueChangeNotifier) {
  1569. ((Property.ValueChangeNotifier) dataSource).addListener(this);
  1570. }
  1571. if (dataSource instanceof Property.ReadOnlyStatusChangeNotifier) {
  1572. ((Property.ReadOnlyStatusChangeNotifier) dataSource)
  1573. .addListener(this);
  1574. }
  1575. isListeningToPropertyEvents = true;
  1576. }
  1577. }
  1578. /**
  1579. * Stops listening to events sent by the data source (if any). Does nothing
  1580. * if <code>isListeningToPropertyEvents == false</code>.
  1581. */
  1582. private void removePropertyListeners() {
  1583. if (isListeningToPropertyEvents) {
  1584. if (dataSource instanceof Property.ValueChangeNotifier) {
  1585. ((Property.ValueChangeNotifier) dataSource)
  1586. .removeListener(this);
  1587. }
  1588. if (dataSource instanceof Property.ReadOnlyStatusChangeNotifier) {
  1589. ((Property.ReadOnlyStatusChangeNotifier) dataSource)
  1590. .removeListener(this);
  1591. }
  1592. isListeningToPropertyEvents = false;
  1593. }
  1594. }
  1595. /**
  1596. * {@inheritDoc}
  1597. * <p>
  1598. * Fields are automatically set to immediate if validators have been added.
  1599. */
  1600. @Override
  1601. public boolean isImmediate() {
  1602. if (getExplicitImmediateValue() != null) {
  1603. return getExplicitImmediateValue();
  1604. }
  1605. // Make field immediate when there is some kind of validation present
  1606. // (validator or required). This will avoid the UI being in a wrong
  1607. // state, e.g. user entered valid data but old validation error is still
  1608. // shown
  1609. return super.isImmediate() || !getValidators().isEmpty()
  1610. || isRequired();
  1611. }
  1612. /*
  1613. * (non-Javadoc)
  1614. *
  1615. * @see com.vaadin.ui.AbstractComponent#readDesign(org.jsoup.nodes .Element,
  1616. * com.vaadin.ui.declarative.DesignContext)
  1617. */
  1618. @Override
  1619. public void readDesign(Element design, DesignContext designContext) {
  1620. super.readDesign(design, designContext);
  1621. Attributes attr = design.attributes();
  1622. if (design.hasAttr("readonly")) {
  1623. setReadOnly(DesignAttributeHandler.readAttribute("readonly", attr,
  1624. Boolean.class));
  1625. }
  1626. }
  1627. /*
  1628. * (non-Javadoc)
  1629. *
  1630. * @see com.vaadin.ui.AbstractComponent#getCustomAttributes()
  1631. */
  1632. @Override
  1633. protected Collection<String> getCustomAttributes() {
  1634. Collection<String> attributes = super.getCustomAttributes();
  1635. attributes.add("readonly");
  1636. // must be handled by subclasses
  1637. attributes.add("value");
  1638. attributes.add("converted-value");
  1639. return attributes;
  1640. }
  1641. /*
  1642. * (non-Javadoc)
  1643. *
  1644. * @see com.vaadin.ui.AbstractComponent#writeDesign(org.jsoup.nodes.Element
  1645. * , com.vaadin.ui.declarative.DesignContext)
  1646. */
  1647. @Override
  1648. public void writeDesign(Element design, DesignContext designContext) {
  1649. super.writeDesign(design, designContext);
  1650. AbstractField def = (AbstractField) designContext
  1651. .getDefaultInstance(this);
  1652. Attributes attr = design.attributes();
  1653. // handle readonly
  1654. DesignAttributeHandler.writeAttribute("readonly", attr,
  1655. super.isReadOnly(), def.isReadOnly(), Boolean.class);
  1656. }
  1657. private static final Logger getLogger() {
  1658. return Logger.getLogger(AbstractField.class.getName());
  1659. }
  1660. }