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

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