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.

AbstractField.java 61KB

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