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 62KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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() || getValidators() != null || 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. /**
  799. * Removes the validator from the field.
  800. *
  801. * @param validator
  802. * the validator to remove.
  803. */
  804. @Override
  805. public void removeValidator(Validator validator) {
  806. if (validators != null) {
  807. validators.remove(validator);
  808. }
  809. markAsDirty();
  810. }
  811. /**
  812. * Removes all validators from the field.
  813. */
  814. @Override
  815. public void removeAllValidators() {
  816. if (validators != null) {
  817. validators.clear();
  818. }
  819. markAsDirty();
  820. }
  821. /**
  822. * Tests the current value against registered validators if the field is not
  823. * empty. If the field is empty it is considered valid if it is not required
  824. * and invalid otherwise. Validators are never checked for empty fields.
  825. *
  826. * In most cases, {@link #validate()} should be used instead of
  827. * {@link #isValid()} to also get the error message.
  828. *
  829. * @return <code>true</code> if all registered validators claim that the
  830. * current value is valid or if the field is empty and not required,
  831. * <code>false</code> otherwise.
  832. */
  833. @Override
  834. public boolean isValid() {
  835. try {
  836. validate();
  837. return true;
  838. } catch (InvalidValueException e) {
  839. return false;
  840. }
  841. }
  842. /**
  843. * Checks the validity of the Field.
  844. *
  845. * A field is invalid if it is set as required (using
  846. * {@link #setRequired(boolean)} and is empty, if one or several of the
  847. * validators added to the field indicate it is invalid or if the value
  848. * cannot be converted provided a converter has been set.
  849. *
  850. * The "required" validation is a built-in validation feature. If the field
  851. * is required and empty this method throws an EmptyValueException with the
  852. * error message set using {@link #setRequiredError(String)}.
  853. *
  854. * @see com.vaadin.data.Validatable#validate()
  855. */
  856. @Override
  857. public void validate() throws Validator.InvalidValueException {
  858. if (isRequired() && isEmpty()) {
  859. throw new Validator.EmptyValueException(requiredError);
  860. }
  861. validate(getFieldValue());
  862. }
  863. /**
  864. * Validates that the given value pass the validators for the field.
  865. * <p>
  866. * This method does not check the requiredness of the field.
  867. *
  868. * @param fieldValue
  869. * The value to check
  870. * @throws Validator.InvalidValueException
  871. * if one or several validators fail
  872. */
  873. protected void validate(T fieldValue)
  874. throws Validator.InvalidValueException {
  875. Object valueToValidate = fieldValue;
  876. // If there is a converter we start by converting the value as we want
  877. // to validate the converted value
  878. if (getConverter() != null) {
  879. try {
  880. valueToValidate = getConverter().convertToModel(fieldValue,
  881. getModelType(), getLocale());
  882. } catch (ConversionException e) {
  883. throw new InvalidValueException(getConversionError(
  884. getConverter().getModelType(), e));
  885. }
  886. }
  887. List<InvalidValueException> validationExceptions = new ArrayList<InvalidValueException>();
  888. if (validators != null) {
  889. // Gets all the validation errors
  890. for (Validator v : validators) {
  891. try {
  892. v.validate(valueToValidate);
  893. } catch (final Validator.InvalidValueException e) {
  894. validationExceptions.add(e);
  895. }
  896. }
  897. }
  898. // If there were no errors
  899. if (validationExceptions.isEmpty()) {
  900. return;
  901. }
  902. // If only one error occurred, throw it forwards
  903. if (validationExceptions.size() == 1) {
  904. throw validationExceptions.get(0);
  905. }
  906. InvalidValueException[] exceptionArray = validationExceptions
  907. .toArray(new InvalidValueException[validationExceptions.size()]);
  908. // Create a composite validator and include all exceptions
  909. throw new Validator.InvalidValueException(null, exceptionArray);
  910. }
  911. /**
  912. * Fields allow invalid values by default. In most cases this is wanted,
  913. * because the field otherwise visually forget the user input immediately.
  914. *
  915. * @return true iff the invalid values are allowed.
  916. * @see com.vaadin.data.Validatable#isInvalidAllowed()
  917. */
  918. @Override
  919. public boolean isInvalidAllowed() {
  920. return invalidAllowed;
  921. }
  922. /**
  923. * Fields allow invalid values by default. In most cases this is wanted,
  924. * because the field otherwise visually forget the user input immediately.
  925. * <p>
  926. * In common setting where the user wants to assure the correctness of the
  927. * datasource, but allow temporarily invalid contents in the field, the user
  928. * should add the validators to datasource, that should not allow invalid
  929. * values. The validators are automatically copied to the field when the
  930. * datasource is set.
  931. * </p>
  932. *
  933. * @see com.vaadin.data.Validatable#setInvalidAllowed(boolean)
  934. */
  935. @Override
  936. public void setInvalidAllowed(boolean invalidAllowed)
  937. throws UnsupportedOperationException {
  938. this.invalidAllowed = invalidAllowed;
  939. }
  940. /**
  941. * Error messages shown by the fields are composites of the error message
  942. * thrown by the superclasses (that is the component error message),
  943. * validation errors and buffered source errors.
  944. *
  945. * @see com.vaadin.ui.AbstractComponent#getErrorMessage()
  946. */
  947. @Override
  948. public ErrorMessage getErrorMessage() {
  949. /*
  950. * Check validation errors only if automatic validation is enabled.
  951. * Empty, required fields will generate a validation error containing
  952. * the requiredError string. For these fields the exclamation mark will
  953. * be hidden but the error must still be sent to the client.
  954. */
  955. Validator.InvalidValueException validationError = null;
  956. if (isValidationVisible()) {
  957. try {
  958. validate();
  959. } catch (Validator.InvalidValueException e) {
  960. if (!e.isInvisible()) {
  961. validationError = e;
  962. }
  963. }
  964. }
  965. // Check if there are any systems errors
  966. final ErrorMessage superError = super.getErrorMessage();
  967. // Return if there are no errors at all
  968. if (superError == null && validationError == null
  969. && getCurrentBufferedSourceException() == null) {
  970. return null;
  971. }
  972. // Throw combination of the error types
  973. return new CompositeErrorMessage(
  974. new ErrorMessage[] {
  975. superError,
  976. AbstractErrorMessage
  977. .getErrorMessageForException(validationError),
  978. AbstractErrorMessage
  979. .getErrorMessageForException(getCurrentBufferedSourceException()) });
  980. }
  981. /* Value change events */
  982. private static final Method VALUE_CHANGE_METHOD;
  983. static {
  984. try {
  985. VALUE_CHANGE_METHOD = Property.ValueChangeListener.class
  986. .getDeclaredMethod("valueChange",
  987. new Class[] { Property.ValueChangeEvent.class });
  988. } catch (final java.lang.NoSuchMethodException e) {
  989. // This should never happen
  990. throw new java.lang.RuntimeException(
  991. "Internal error finding methods in AbstractField");
  992. }
  993. }
  994. /*
  995. * Adds a value change listener for the field. Don't add a JavaDoc comment
  996. * here, we use the default documentation from the implemented interface.
  997. */
  998. @Override
  999. public void addValueChangeListener(Property.ValueChangeListener listener) {
  1000. addListener(AbstractField.ValueChangeEvent.class, listener,
  1001. VALUE_CHANGE_METHOD);
  1002. // ensure "automatic immediate handling" works
  1003. markAsDirty();
  1004. }
  1005. /**
  1006. * @deprecated As of 7.0, replaced by
  1007. * {@link #addValueChangeListener(com.vaadin.data.Property.ValueChangeListener)}
  1008. **/
  1009. @Override
  1010. @Deprecated
  1011. public void addListener(Property.ValueChangeListener listener) {
  1012. addValueChangeListener(listener);
  1013. }
  1014. /*
  1015. * Removes a value change listener from the field. Don't add a JavaDoc
  1016. * comment here, we use the default documentation from the implemented
  1017. * interface.
  1018. */
  1019. @Override
  1020. public void removeValueChangeListener(Property.ValueChangeListener listener) {
  1021. removeListener(AbstractField.ValueChangeEvent.class, listener,
  1022. VALUE_CHANGE_METHOD);
  1023. // ensure "automatic immediate handling" works
  1024. markAsDirty();
  1025. }
  1026. /**
  1027. * @deprecated As of 7.0, replaced by
  1028. * {@link #removeValueChangeListener(com.vaadin.data.Property.ValueChangeListener)}
  1029. **/
  1030. @Override
  1031. @Deprecated
  1032. public void removeListener(Property.ValueChangeListener listener) {
  1033. removeValueChangeListener(listener);
  1034. }
  1035. /**
  1036. * Emits the value change event. The value contained in the field is
  1037. * validated before the event is created.
  1038. */
  1039. protected void fireValueChange(boolean repaintIsNotNeeded) {
  1040. fireEvent(new AbstractField.ValueChangeEvent(this));
  1041. if (!repaintIsNotNeeded) {
  1042. markAsDirty();
  1043. }
  1044. }
  1045. /* Read-only status change events */
  1046. private static final Method READ_ONLY_STATUS_CHANGE_METHOD;
  1047. static {
  1048. try {
  1049. READ_ONLY_STATUS_CHANGE_METHOD = Property.ReadOnlyStatusChangeListener.class
  1050. .getDeclaredMethod(
  1051. "readOnlyStatusChange",
  1052. new Class[] { Property.ReadOnlyStatusChangeEvent.class });
  1053. } catch (final java.lang.NoSuchMethodException e) {
  1054. // This should never happen
  1055. throw new java.lang.RuntimeException(
  1056. "Internal error finding methods in AbstractField");
  1057. }
  1058. }
  1059. /**
  1060. * React to read only status changes of the property by requesting a
  1061. * repaint.
  1062. *
  1063. * @see Property.ReadOnlyStatusChangeListener
  1064. */
  1065. @Override
  1066. public void readOnlyStatusChange(Property.ReadOnlyStatusChangeEvent event) {
  1067. getState().propertyReadOnly = event.getProperty().isReadOnly();
  1068. }
  1069. /**
  1070. * An <code>Event</code> object specifying the Property whose read-only
  1071. * status has changed.
  1072. *
  1073. * @author Vaadin Ltd.
  1074. * @since 3.0
  1075. */
  1076. public static class ReadOnlyStatusChangeEvent extends Component.Event
  1077. implements Property.ReadOnlyStatusChangeEvent, Serializable {
  1078. /**
  1079. * New instance of text change event.
  1080. *
  1081. * @param source
  1082. * the Source of the event.
  1083. */
  1084. public ReadOnlyStatusChangeEvent(AbstractField source) {
  1085. super(source);
  1086. }
  1087. /**
  1088. * Property where the event occurred.
  1089. *
  1090. * @return the Source of the event.
  1091. */
  1092. @Override
  1093. public Property getProperty() {
  1094. return (Property) getSource();
  1095. }
  1096. }
  1097. /*
  1098. * Adds a read-only status change listener for the field. Don't add a
  1099. * JavaDoc comment here, we use the default documentation from the
  1100. * implemented interface.
  1101. */
  1102. @Override
  1103. public void addReadOnlyStatusChangeListener(
  1104. Property.ReadOnlyStatusChangeListener listener) {
  1105. addListener(Property.ReadOnlyStatusChangeEvent.class, listener,
  1106. READ_ONLY_STATUS_CHANGE_METHOD);
  1107. }
  1108. /**
  1109. * @deprecated As of 7.0, replaced by
  1110. * {@link #addReadOnlyStatusChangeListener(com.vaadin.data.Property.ReadOnlyStatusChangeListener)}
  1111. **/
  1112. @Override
  1113. @Deprecated
  1114. public void addListener(Property.ReadOnlyStatusChangeListener listener) {
  1115. addReadOnlyStatusChangeListener(listener);
  1116. }
  1117. /*
  1118. * Removes a read-only status change listener from the field. Don't add a
  1119. * JavaDoc comment here, we use the default documentation from the
  1120. * implemented interface.
  1121. */
  1122. @Override
  1123. public void removeReadOnlyStatusChangeListener(
  1124. Property.ReadOnlyStatusChangeListener listener) {
  1125. removeListener(Property.ReadOnlyStatusChangeEvent.class, listener,
  1126. READ_ONLY_STATUS_CHANGE_METHOD);
  1127. }
  1128. /**
  1129. * @deprecated As of 7.0, replaced by
  1130. * {@link #removeReadOnlyStatusChangeListener(com.vaadin.data.Property.ReadOnlyStatusChangeListener)}
  1131. **/
  1132. @Override
  1133. @Deprecated
  1134. public void removeListener(Property.ReadOnlyStatusChangeListener listener) {
  1135. removeReadOnlyStatusChangeListener(listener);
  1136. }
  1137. /**
  1138. * Emits the read-only status change event. The value contained in the field
  1139. * is validated before the event is created.
  1140. */
  1141. protected void fireReadOnlyStatusChange() {
  1142. fireEvent(new AbstractField.ReadOnlyStatusChangeEvent(this));
  1143. }
  1144. /**
  1145. * This method listens to data source value changes and passes the changes
  1146. * forwards.
  1147. *
  1148. * Changes are not forwarded to the listeners of the field during internal
  1149. * operations of the field to avoid duplicate notifications.
  1150. *
  1151. * @param event
  1152. * the value change event telling the data source contents have
  1153. * changed.
  1154. */
  1155. @Override
  1156. public void valueChange(Property.ValueChangeEvent event) {
  1157. if (!isBuffered()) {
  1158. if (committingValueToDataSource) {
  1159. boolean propertyNotifiesOfTheBufferedValue = SharedUtil.equals(
  1160. event.getProperty().getValue(), getInternalValue());
  1161. if (!propertyNotifiesOfTheBufferedValue) {
  1162. /*
  1163. * Property (or chained property like PropertyFormatter) now
  1164. * reports different value than the one the field has just
  1165. * committed to it. In this case we respect the property
  1166. * value.
  1167. *
  1168. * Still, we don't fire value change yet, but instead
  1169. * postpone it until "commit" is done. See setValue(Object,
  1170. * boolean) and commit().
  1171. */
  1172. readValueFromProperty(event);
  1173. valueWasModifiedByDataSourceDuringCommit = true;
  1174. }
  1175. } else if (!isModified()) {
  1176. readValueFromProperty(event);
  1177. fireValueChange(false);
  1178. }
  1179. }
  1180. }
  1181. private void readValueFromProperty(Property.ValueChangeEvent event) {
  1182. setInternalValue(convertFromModel(event.getProperty().getValue()));
  1183. }
  1184. /**
  1185. * {@inheritDoc}
  1186. */
  1187. @Override
  1188. public void focus() {
  1189. super.focus();
  1190. }
  1191. /*
  1192. * (non-Javadoc)
  1193. *
  1194. * @see com.vaadin.ui.Component.Focusable#getTabIndex()
  1195. */
  1196. @Override
  1197. public int getTabIndex() {
  1198. return getState(false).tabIndex;
  1199. }
  1200. /*
  1201. * (non-Javadoc)
  1202. *
  1203. * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
  1204. */
  1205. @Override
  1206. public void setTabIndex(int tabIndex) {
  1207. getState().tabIndex = tabIndex;
  1208. }
  1209. /**
  1210. * Returns the internal field value, which might not match the data source
  1211. * value e.g. if the field has been modified and is not in write-through
  1212. * mode.
  1213. *
  1214. * This method can be overridden by subclasses together with
  1215. * {@link #setInternalValue(Object)} to compute internal field value at
  1216. * runtime. When doing so, typically also {@link #isModified()} needs to be
  1217. * overridden and care should be taken in the management of the empty state
  1218. * and buffering support.
  1219. *
  1220. * @return internal field value
  1221. */
  1222. protected T getInternalValue() {
  1223. return value;
  1224. }
  1225. /**
  1226. * Sets the internal field value. This is purely used by AbstractField to
  1227. * change the internal Field value. It does not trigger valuechange events.
  1228. * It can be overridden by the inheriting classes to update all dependent
  1229. * variables.
  1230. *
  1231. * Subclasses can also override {@link #getInternalValue()} if necessary.
  1232. *
  1233. * @param newValue
  1234. * the new value to be set.
  1235. */
  1236. protected void setInternalValue(T newValue) {
  1237. value = newValue;
  1238. valueLocale = getLocale();
  1239. if (validators != null && !validators.isEmpty()) {
  1240. markAsDirty();
  1241. }
  1242. }
  1243. /**
  1244. * Notifies the component that it is connected to an application.
  1245. *
  1246. * @see com.vaadin.ui.Component#attach()
  1247. */
  1248. @Override
  1249. public void attach() {
  1250. super.attach();
  1251. localeMightHaveChanged();
  1252. if (!isListeningToPropertyEvents) {
  1253. addPropertyListeners();
  1254. if (!isModified() && !isBuffered()) {
  1255. // Update value from data source
  1256. updateValueFromDataSource();
  1257. }
  1258. }
  1259. }
  1260. @Override
  1261. public void setLocale(Locale locale) {
  1262. super.setLocale(locale);
  1263. localeMightHaveChanged();
  1264. }
  1265. private void localeMightHaveChanged() {
  1266. if (!SharedUtil.equals(valueLocale, getLocale())) {
  1267. // The locale HAS actually changed
  1268. if (dataSource != null && !isModified()) {
  1269. // When we have a data source and the internal value is directly
  1270. // read from that we want to update the value
  1271. T newInternalValue = convertFromModel(getPropertyDataSource()
  1272. .getValue());
  1273. if (!SharedUtil.equals(newInternalValue, getInternalValue())) {
  1274. setInternalValue(newInternalValue);
  1275. fireValueChange(false);
  1276. }
  1277. } else if (dataSource == null && converter != null) {
  1278. /*
  1279. * No data source but a converter has been set. The same issues
  1280. * as above but we cannot use propertyDataSource. Convert the
  1281. * current value back to a model value using the old locale and
  1282. * then convert back using the new locale. If this does not
  1283. * match the field value we need to set the converted value
  1284. * again.
  1285. */
  1286. Object convertedValue = convertToModel(getInternalValue(),
  1287. valueLocale);
  1288. T newinternalValue = convertFromModel(convertedValue);
  1289. if (!SharedUtil.equals(getInternalValue(), newinternalValue)) {
  1290. setInternalValue(newinternalValue);
  1291. fireValueChange(false);
  1292. }
  1293. }
  1294. }
  1295. }
  1296. @Override
  1297. public void detach() {
  1298. super.detach();
  1299. // Stop listening to data source events on detach to avoid a potential
  1300. // memory leak. See #6155.
  1301. removePropertyListeners();
  1302. }
  1303. /**
  1304. * Is this field required. Required fields must filled by the user.
  1305. *
  1306. * If the field is required, it is visually indicated in the user interface.
  1307. * Furthermore, setting field to be required implicitly adds "non-empty"
  1308. * validator and thus isValid() == false or any isEmpty() fields. In those
  1309. * cases validation errors are not painted as it is obvious that the user
  1310. * must fill in the required fields.
  1311. *
  1312. * On the other hand, for the non-required fields isValid() == true if the
  1313. * field isEmpty() regardless of any attached validators.
  1314. *
  1315. *
  1316. * @return <code>true</code> if the field is required, otherwise
  1317. * <code>false</code>.
  1318. */
  1319. @Override
  1320. public boolean isRequired() {
  1321. return getState(false).required;
  1322. }
  1323. /**
  1324. * Sets the field required. Required fields must filled by the user.
  1325. *
  1326. * If the field is required, it is visually indicated in the user interface.
  1327. * Furthermore, setting field to be required implicitly adds "non-empty"
  1328. * validator and thus isValid() == false or any isEmpty() fields. In those
  1329. * cases validation errors are not painted as it is obvious that the user
  1330. * must fill in the required fields.
  1331. *
  1332. * On the other hand, for the non-required fields isValid() == true if the
  1333. * field isEmpty() regardless of any attached validators.
  1334. *
  1335. * @param required
  1336. * Is the field required.
  1337. */
  1338. @Override
  1339. public void setRequired(boolean required) {
  1340. getState().required = required;
  1341. }
  1342. /**
  1343. * Set the error that is show if this field is required, but empty. When
  1344. * setting requiredMessage to be "" or null, no error pop-up or exclamation
  1345. * mark is shown for a empty required field. This faults to "". Even in
  1346. * those cases isValid() returns false for empty required fields.
  1347. *
  1348. * @param requiredMessage
  1349. * Message to be shown when this field is required, but empty.
  1350. */
  1351. @Override
  1352. public void setRequiredError(String requiredMessage) {
  1353. requiredError = requiredMessage;
  1354. markAsDirty();
  1355. }
  1356. @Override
  1357. public String getRequiredError() {
  1358. return requiredError;
  1359. }
  1360. /**
  1361. * Gets the error that is shown if the field value cannot be converted to
  1362. * the data source type.
  1363. *
  1364. * @return The error that is shown if conversion of the field value fails
  1365. */
  1366. public String getConversionError() {
  1367. return conversionError;
  1368. }
  1369. /**
  1370. * Sets the error that is shown if the field value cannot be converted to
  1371. * the data source type. If {0} is present in the message, it will be
  1372. * replaced by the simple name of the data source type. If {1} is present in
  1373. * the message, it will be replaced by the ConversionException message.
  1374. *
  1375. * @param valueConversionError
  1376. * Message to be shown when conversion of the value fails
  1377. */
  1378. public void setConversionError(String valueConversionError) {
  1379. this.conversionError = valueConversionError;
  1380. markAsDirty();
  1381. }
  1382. @Override
  1383. public boolean isEmpty() {
  1384. return (getFieldValue() == null);
  1385. }
  1386. @Override
  1387. public void clear() {
  1388. setValue(null);
  1389. }
  1390. /**
  1391. * Is automatic, visible validation enabled?
  1392. *
  1393. * If automatic validation is enabled, any validators connected to this
  1394. * component are evaluated while painting the component and potential error
  1395. * messages are sent to client. If the automatic validation is turned off,
  1396. * isValid() and validate() methods still work, but one must show the
  1397. * validation in their own code.
  1398. *
  1399. * @return True, if automatic validation is enabled.
  1400. */
  1401. public boolean isValidationVisible() {
  1402. return validationVisible;
  1403. }
  1404. /**
  1405. * Enable or disable automatic, visible validation.
  1406. *
  1407. * If automatic validation is enabled, any validators connected to this
  1408. * component are evaluated while painting the component and potential error
  1409. * messages are sent to client. If the automatic validation is turned off,
  1410. * isValid() and validate() methods still work, but one must show the
  1411. * validation in their own code.
  1412. *
  1413. * @param validateAutomatically
  1414. * True, if automatic validation is enabled.
  1415. */
  1416. public void setValidationVisible(boolean validateAutomatically) {
  1417. if (validationVisible != validateAutomatically) {
  1418. markAsDirty();
  1419. validationVisible = validateAutomatically;
  1420. }
  1421. }
  1422. /**
  1423. * Sets the current buffered source exception.
  1424. *
  1425. * @param currentBufferedSourceException
  1426. */
  1427. public void setCurrentBufferedSourceException(
  1428. Buffered.SourceException currentBufferedSourceException) {
  1429. this.currentBufferedSourceException = currentBufferedSourceException;
  1430. markAsDirty();
  1431. }
  1432. /**
  1433. * Gets the current buffered source exception.
  1434. *
  1435. * @return The current source exception
  1436. */
  1437. protected Buffered.SourceException getCurrentBufferedSourceException() {
  1438. return currentBufferedSourceException;
  1439. }
  1440. /**
  1441. * A ready-made {@link ShortcutListener} that focuses the given
  1442. * {@link Focusable} (usually a {@link Field}) when the keyboard shortcut is
  1443. * invoked.
  1444. *
  1445. */
  1446. public static class FocusShortcut extends ShortcutListener {
  1447. protected Focusable focusable;
  1448. /**
  1449. * Creates a keyboard shortcut for focusing the given {@link Focusable}
  1450. * using the shorthand notation defined in {@link ShortcutAction}.
  1451. *
  1452. * @param focusable
  1453. * to focused when the shortcut is invoked
  1454. * @param shorthandCaption
  1455. * caption with keycode and modifiers indicated
  1456. */
  1457. public FocusShortcut(Focusable focusable, String shorthandCaption) {
  1458. super(shorthandCaption);
  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. * @param modifiers
  1469. * modifiers required to invoke the shortcut
  1470. */
  1471. public FocusShortcut(Focusable focusable, int keyCode, int... modifiers) {
  1472. super(null, keyCode, modifiers);
  1473. this.focusable = focusable;
  1474. }
  1475. /**
  1476. * Creates a keyboard shortcut for focusing the given {@link Focusable}.
  1477. *
  1478. * @param focusable
  1479. * to focused when the shortcut is invoked
  1480. * @param keyCode
  1481. * keycode that invokes the shortcut
  1482. */
  1483. public FocusShortcut(Focusable focusable, int keyCode) {
  1484. this(focusable, keyCode, null);
  1485. }
  1486. @Override
  1487. public void handleAction(Object sender, Object target) {
  1488. focusable.focus();
  1489. }
  1490. }
  1491. private void updateValueFromDataSource() {
  1492. if (dataSource != null) {
  1493. // Gets the correct value from datasource
  1494. T newFieldValue;
  1495. try {
  1496. // Discards buffer by overwriting from datasource
  1497. newFieldValue = convertFromModel(getDataSourceValue());
  1498. // If successful, remove set the buffering state to be ok
  1499. if (getCurrentBufferedSourceException() != null) {
  1500. setCurrentBufferedSourceException(null);
  1501. }
  1502. } catch (final Throwable e) {
  1503. // FIXME: What should really be done here if conversion fails?
  1504. // Sets the buffering state
  1505. currentBufferedSourceException = new Buffered.SourceException(
  1506. this, e);
  1507. markAsDirty();
  1508. // Throws the source exception
  1509. throw currentBufferedSourceException;
  1510. }
  1511. final boolean wasModified = isModified();
  1512. setModified(false);
  1513. // If the new value differs from the previous one
  1514. if (!SharedUtil.equals(newFieldValue, getInternalValue())) {
  1515. setInternalValue(newFieldValue);
  1516. fireValueChange(false);
  1517. } else if (wasModified) {
  1518. // If the value did not change, but the modification status did
  1519. markAsDirty();
  1520. }
  1521. }
  1522. }
  1523. /**
  1524. * Gets the converter used to convert the property data source value to the
  1525. * field value.
  1526. *
  1527. * @return The converter or null if none is set.
  1528. */
  1529. public Converter<T, Object> getConverter() {
  1530. return converter;
  1531. }
  1532. /**
  1533. * Sets the converter used to convert the field value to property data
  1534. * source type. The converter must have a presentation type that matches the
  1535. * field type.
  1536. *
  1537. * @param converter
  1538. * The new converter to use.
  1539. */
  1540. public void setConverter(Converter<T, ?> converter) {
  1541. this.converter = (Converter<T, Object>) converter;
  1542. markAsDirty();
  1543. }
  1544. @Override
  1545. protected AbstractFieldState getState() {
  1546. return (AbstractFieldState) super.getState();
  1547. }
  1548. @Override
  1549. protected AbstractFieldState getState(boolean markAsDirty) {
  1550. return (AbstractFieldState) super.getState(markAsDirty);
  1551. }
  1552. @Override
  1553. public void beforeClientResponse(boolean initial) {
  1554. super.beforeClientResponse(initial);
  1555. // Hide the error indicator if needed
  1556. getState().hideErrors = shouldHideErrors();
  1557. }
  1558. /**
  1559. * Registers this as an event listener for events sent by the data source
  1560. * (if any). Does nothing if
  1561. * <code>isListeningToPropertyEvents == true</code>.
  1562. */
  1563. private void addPropertyListeners() {
  1564. if (!isListeningToPropertyEvents) {
  1565. if (dataSource instanceof Property.ValueChangeNotifier) {
  1566. ((Property.ValueChangeNotifier) dataSource).addListener(this);
  1567. }
  1568. if (dataSource instanceof Property.ReadOnlyStatusChangeNotifier) {
  1569. ((Property.ReadOnlyStatusChangeNotifier) dataSource)
  1570. .addListener(this);
  1571. }
  1572. isListeningToPropertyEvents = true;
  1573. }
  1574. }
  1575. /**
  1576. * Stops listening to events sent by the data source (if any). Does nothing
  1577. * if <code>isListeningToPropertyEvents == false</code>.
  1578. */
  1579. private void removePropertyListeners() {
  1580. if (isListeningToPropertyEvents) {
  1581. if (dataSource instanceof Property.ValueChangeNotifier) {
  1582. ((Property.ValueChangeNotifier) dataSource)
  1583. .removeListener(this);
  1584. }
  1585. if (dataSource instanceof Property.ReadOnlyStatusChangeNotifier) {
  1586. ((Property.ReadOnlyStatusChangeNotifier) dataSource)
  1587. .removeListener(this);
  1588. }
  1589. isListeningToPropertyEvents = false;
  1590. }
  1591. }
  1592. /**
  1593. * {@inheritDoc}
  1594. * <p>
  1595. * Fields are automatically set to immediate if validators have been added.
  1596. */
  1597. @Override
  1598. public boolean isImmediate() {
  1599. if (getExplicitImmediateValue() != null) {
  1600. return getExplicitImmediateValue();
  1601. }
  1602. // Make field immediate when there is some kind of validation present
  1603. // (validator or required). This will avoid the UI being in a wrong
  1604. // state, e.g. user entered valid data but old validation error is still
  1605. // shown
  1606. return super.isImmediate() || !getValidators().isEmpty()
  1607. || isRequired();
  1608. }
  1609. /*
  1610. * (non-Javadoc)
  1611. *
  1612. * @see com.vaadin.ui.AbstractComponent#readDesign(org.jsoup.nodes .Element,
  1613. * com.vaadin.ui.declarative.DesignContext)
  1614. */
  1615. @Override
  1616. public void readDesign(Element design, DesignContext designContext) {
  1617. super.readDesign(design, designContext);
  1618. Attributes attr = design.attributes();
  1619. if (design.hasAttr("readonly")) {
  1620. setReadOnly(DesignAttributeHandler.readAttribute("readonly", attr,
  1621. Boolean.class));
  1622. }
  1623. }
  1624. /*
  1625. * (non-Javadoc)
  1626. *
  1627. * @see com.vaadin.ui.AbstractComponent#getCustomAttributes()
  1628. */
  1629. @Override
  1630. protected Collection<String> getCustomAttributes() {
  1631. Collection<String> attributes = super.getCustomAttributes();
  1632. attributes.add("readonly");
  1633. // must be handled by subclasses
  1634. attributes.add("value");
  1635. attributes.add("converted-value");
  1636. return attributes;
  1637. }
  1638. /*
  1639. * (non-Javadoc)
  1640. *
  1641. * @see com.vaadin.ui.AbstractComponent#writeDesign(org.jsoup.nodes.Element
  1642. * , com.vaadin.ui.declarative.DesignContext)
  1643. */
  1644. @Override
  1645. public void writeDesign(Element design, DesignContext designContext) {
  1646. super.writeDesign(design, designContext);
  1647. AbstractField def = (AbstractField) designContext
  1648. .getDefaultInstance(this);
  1649. Attributes attr = design.attributes();
  1650. // handle readonly
  1651. DesignAttributeHandler.writeAttribute("readonly", attr,
  1652. super.isReadOnly(), def.isReadOnly(), Boolean.class);
  1653. }
  1654. private static final Logger getLogger() {
  1655. return Logger.getLogger(AbstractField.class.getName());
  1656. }
  1657. }