Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.data.util.sqlcontainer;
  5. import java.io.IOException;
  6. import java.sql.ResultSet;
  7. import java.sql.ResultSetMetaData;
  8. import java.sql.SQLException;
  9. import java.util.ArrayList;
  10. import java.util.Collection;
  11. import java.util.Collections;
  12. import java.util.ConcurrentModificationException;
  13. import java.util.Date;
  14. import java.util.EventObject;
  15. import java.util.HashMap;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.logging.Level;
  20. import java.util.logging.Logger;
  21. import com.vaadin.data.Container;
  22. import com.vaadin.data.Item;
  23. import com.vaadin.data.Property;
  24. import com.vaadin.data.util.filter.Compare.Equal;
  25. import com.vaadin.data.util.filter.Like;
  26. import com.vaadin.data.util.filter.UnsupportedFilterException;
  27. import com.vaadin.data.util.sqlcontainer.query.OrderBy;
  28. import com.vaadin.data.util.sqlcontainer.query.QueryDelegate;
  29. import com.vaadin.data.util.sqlcontainer.query.QueryDelegate.RowIdChangeListener;
  30. import com.vaadin.data.util.sqlcontainer.query.TableQuery;
  31. import com.vaadin.data.util.sqlcontainer.query.generator.MSSQLGenerator;
  32. import com.vaadin.data.util.sqlcontainer.query.generator.OracleGenerator;
  33. public class SQLContainer implements Container, Container.Filterable,
  34. Container.Indexed, Container.Sortable, Container.ItemSetChangeNotifier {
  35. /** Query delegate */
  36. private QueryDelegate delegate;
  37. /** Auto commit mode, default = false */
  38. private boolean autoCommit = false;
  39. /** Page length = number of items contained in one page */
  40. private int pageLength = DEFAULT_PAGE_LENGTH;
  41. public static final int DEFAULT_PAGE_LENGTH = 100;
  42. /** Number of items to cache = CACHE_RATIO x pageLength */
  43. public static final int CACHE_RATIO = 2;
  44. /** Item and index caches */
  45. private final Map<Integer, RowId> itemIndexes = new HashMap<Integer, RowId>();
  46. private final CacheMap<RowId, RowItem> cachedItems = new CacheMap<RowId, RowItem>();
  47. /** Container properties = column names, data types and statuses */
  48. private final List<String> propertyIds = new ArrayList<String>();
  49. private final Map<String, Class<?>> propertyTypes = new HashMap<String, Class<?>>();
  50. private final Map<String, Boolean> propertyReadOnly = new HashMap<String, Boolean>();
  51. private final Map<String, Boolean> propertyNullable = new HashMap<String, Boolean>();
  52. /** Filters (WHERE) and sorters (ORDER BY) */
  53. private final List<Filter> filters = new ArrayList<Filter>();
  54. private final List<OrderBy> sorters = new ArrayList<OrderBy>();
  55. /**
  56. * Total number of items available in the data source using the current
  57. * query, filters and sorters.
  58. */
  59. private int size;
  60. /**
  61. * Size updating logic. Do not update size from data source if it has been
  62. * updated in the last sizeValidMilliSeconds milliseconds.
  63. */
  64. private final int sizeValidMilliSeconds = 10000;
  65. private boolean sizeDirty = true;
  66. private Date sizeUpdated = new Date();
  67. /** Starting row number of the currently fetched page */
  68. private int currentOffset;
  69. /** ItemSetChangeListeners */
  70. private LinkedList<Container.ItemSetChangeListener> itemSetChangeListeners;
  71. /** Temporary storage for modified items and items to be removed and added */
  72. private final Map<RowId, RowItem> removedItems = new HashMap<RowId, RowItem>();
  73. private final List<RowItem> addedItems = new ArrayList<RowItem>();
  74. private final List<RowItem> modifiedItems = new ArrayList<RowItem>();
  75. /** List of references to other SQLContainers */
  76. private final Map<SQLContainer, Reference> references = new HashMap<SQLContainer, Reference>();
  77. /** Cache flush notification system enabled. Disabled by default. */
  78. private boolean notificationsEnabled;
  79. /**
  80. * Prevent instantiation without a QueryDelegate.
  81. */
  82. @SuppressWarnings("unused")
  83. private SQLContainer() {
  84. }
  85. /**
  86. * Creates and initializes SQLContainer using the given QueryDelegate
  87. *
  88. * @param delegate
  89. * QueryDelegate implementation
  90. * @throws SQLException
  91. */
  92. public SQLContainer(QueryDelegate delegate) throws SQLException {
  93. if (delegate == null) {
  94. throw new IllegalArgumentException(
  95. "QueryDelegate must not be null.");
  96. }
  97. this.delegate = delegate;
  98. getPropertyIds();
  99. cachedItems.setCacheLimit(CACHE_RATIO * getPageLength());
  100. }
  101. /**************************************/
  102. /** Methods from interface Container **/
  103. /**************************************/
  104. /**
  105. * Note! If auto commit mode is enabled, this method will still return the
  106. * temporary row ID assigned for the item. Implement
  107. * QueryDelegate.RowIdChangeListener to receive the actual Row ID value
  108. * after the addition has been committed.
  109. *
  110. * {@inheritDoc}
  111. */
  112. @Override
  113. public Object addItem() throws UnsupportedOperationException {
  114. Object emptyKey[] = new Object[delegate.getPrimaryKeyColumns().size()];
  115. RowId itemId = new TemporaryRowId(emptyKey);
  116. // Create new empty column properties for the row item.
  117. List<ColumnProperty> itemProperties = new ArrayList<ColumnProperty>();
  118. for (String propertyId : propertyIds) {
  119. /* Default settings for new item properties. */
  120. itemProperties
  121. .add(new ColumnProperty(propertyId, propertyReadOnly
  122. .get(propertyId),
  123. !propertyReadOnly.get(propertyId), propertyNullable
  124. .get(propertyId), null, getType(propertyId)));
  125. }
  126. RowItem newRowItem = new RowItem(this, itemId, itemProperties);
  127. if (autoCommit) {
  128. /* Add and commit instantly */
  129. try {
  130. if (delegate instanceof TableQuery) {
  131. itemId = ((TableQuery) delegate)
  132. .storeRowImmediately(newRowItem);
  133. } else {
  134. delegate.beginTransaction();
  135. delegate.storeRow(newRowItem);
  136. delegate.commit();
  137. }
  138. refresh();
  139. if (notificationsEnabled) {
  140. CacheFlushNotifier.notifyOfCacheFlush(this);
  141. }
  142. getLogger().log(Level.FINER, "Row added to DB...");
  143. return itemId;
  144. } catch (SQLException e) {
  145. getLogger().log(Level.WARNING,
  146. "Failed to add row to DB. Rolling back.", e);
  147. try {
  148. delegate.rollback();
  149. } catch (SQLException ee) {
  150. getLogger().log(Level.SEVERE,
  151. "Failed to roll back row addition", e);
  152. }
  153. return null;
  154. }
  155. } else {
  156. addedItems.add(newRowItem);
  157. fireContentsChange();
  158. return itemId;
  159. }
  160. }
  161. /*
  162. * (non-Javadoc)
  163. *
  164. * @see com.vaadin.data.Container#containsId(java.lang.Object)
  165. */
  166. @Override
  167. public boolean containsId(Object itemId) {
  168. if (itemId == null) {
  169. return false;
  170. }
  171. if (cachedItems.containsKey(itemId)) {
  172. return true;
  173. } else {
  174. for (RowItem item : addedItems) {
  175. if (item.getId().equals(itemId)) {
  176. return itemPassesFilters(item);
  177. }
  178. }
  179. }
  180. if (removedItems.containsKey(itemId)) {
  181. return false;
  182. }
  183. if (itemId instanceof ReadOnlyRowId) {
  184. int rowNum = ((ReadOnlyRowId) itemId).getRowNum();
  185. return rowNum >= 0 && rowNum < size;
  186. }
  187. if (itemId instanceof RowId && !(itemId instanceof TemporaryRowId)) {
  188. try {
  189. return delegate.containsRowWithKey(((RowId) itemId).getId());
  190. } catch (Exception e) {
  191. /* Query failed, just return false. */
  192. getLogger().log(Level.WARNING, "containsId query failed", e);
  193. }
  194. }
  195. return false;
  196. }
  197. /*
  198. * (non-Javadoc)
  199. *
  200. * @see com.vaadin.data.Container#getContainerProperty(java.lang.Object,
  201. * java.lang.Object)
  202. */
  203. @Override
  204. public Property<?> getContainerProperty(Object itemId, Object propertyId) {
  205. Item item = getItem(itemId);
  206. if (item == null) {
  207. return null;
  208. }
  209. return item.getItemProperty(propertyId);
  210. }
  211. /*
  212. * (non-Javadoc)
  213. *
  214. * @see com.vaadin.data.Container#getContainerPropertyIds()
  215. */
  216. @Override
  217. public Collection<?> getContainerPropertyIds() {
  218. return Collections.unmodifiableCollection(propertyIds);
  219. }
  220. /*
  221. * (non-Javadoc)
  222. *
  223. * @see com.vaadin.data.Container#getItem(java.lang.Object)
  224. */
  225. @Override
  226. public Item getItem(Object itemId) {
  227. if (!cachedItems.containsKey(itemId)) {
  228. int index = indexOfId(itemId);
  229. if (index >= size) {
  230. // The index is in the added items
  231. int offset = index - size;
  232. RowItem item = addedItems.get(offset);
  233. if (itemPassesFilters(item)) {
  234. return item;
  235. } else {
  236. return null;
  237. }
  238. } else {
  239. // load the item into cache
  240. updateOffsetAndCache(index);
  241. }
  242. }
  243. return cachedItems.get(itemId);
  244. }
  245. /**
  246. * Bypasses in-memory filtering to return items that are cached in memory.
  247. * <em>NOTE</em>: This does not bypass database-level filtering.
  248. *
  249. * @param itemId
  250. * the id of the item to retrieve.
  251. * @return the item represented by itemId.
  252. */
  253. public Item getItemUnfiltered(Object itemId) {
  254. if (!cachedItems.containsKey(itemId)) {
  255. for (RowItem item : addedItems) {
  256. if (item.getId().equals(itemId)) {
  257. return item;
  258. }
  259. }
  260. }
  261. return cachedItems.get(itemId);
  262. }
  263. /**
  264. * NOTE! Do not use this method if in any way avoidable. This method doesn't
  265. * (and cannot) use lazy loading, which means that all rows in the database
  266. * will be loaded into memory.
  267. *
  268. * {@inheritDoc}
  269. */
  270. @Override
  271. public Collection<?> getItemIds() {
  272. updateCount();
  273. ArrayList<RowId> ids = new ArrayList<RowId>();
  274. ResultSet rs = null;
  275. try {
  276. // Load ALL rows :(
  277. delegate.beginTransaction();
  278. rs = delegate.getResults(0, 0);
  279. List<String> pKeys = delegate.getPrimaryKeyColumns();
  280. while (rs.next()) {
  281. RowId id = null;
  282. if (pKeys.isEmpty()) {
  283. /* Create a read only itemId */
  284. id = new ReadOnlyRowId(rs.getRow());
  285. } else {
  286. /* Generate itemId for the row based on primary key(s) */
  287. Object[] itemId = new Object[pKeys.size()];
  288. for (int i = 0; i < pKeys.size(); i++) {
  289. itemId[i] = rs.getObject(pKeys.get(i));
  290. }
  291. id = new RowId(itemId);
  292. }
  293. if (id != null && !removedItems.containsKey(id)) {
  294. ids.add(id);
  295. }
  296. }
  297. rs.getStatement().close();
  298. rs.close();
  299. delegate.commit();
  300. } catch (SQLException e) {
  301. getLogger().log(Level.WARNING,
  302. "getItemIds() failed, rolling back.", e);
  303. try {
  304. delegate.rollback();
  305. } catch (SQLException e1) {
  306. getLogger().log(Level.SEVERE, "Failed to roll back state", e1);
  307. }
  308. try {
  309. rs.getStatement().close();
  310. rs.close();
  311. } catch (SQLException e1) {
  312. getLogger().log(Level.WARNING, "Closing session failed", e1);
  313. }
  314. throw new RuntimeException("Failed to fetch item indexes.", e);
  315. }
  316. for (RowItem item : getFilteredAddedItems()) {
  317. ids.add(item.getId());
  318. }
  319. return Collections.unmodifiableCollection(ids);
  320. }
  321. /*
  322. * (non-Javadoc)
  323. *
  324. * @see com.vaadin.data.Container#getType(java.lang.Object)
  325. */
  326. @Override
  327. public Class<?> getType(Object propertyId) {
  328. if (!propertyIds.contains(propertyId)) {
  329. return null;
  330. }
  331. return propertyTypes.get(propertyId);
  332. }
  333. /*
  334. * (non-Javadoc)
  335. *
  336. * @see com.vaadin.data.Container#size()
  337. */
  338. @Override
  339. public int size() {
  340. updateCount();
  341. return size + sizeOfAddedItems() - removedItems.size();
  342. }
  343. /*
  344. * (non-Javadoc)
  345. *
  346. * @see com.vaadin.data.Container#removeItem(java.lang.Object)
  347. */
  348. @Override
  349. public boolean removeItem(Object itemId)
  350. throws UnsupportedOperationException {
  351. if (!containsId(itemId)) {
  352. return false;
  353. }
  354. for (RowItem item : addedItems) {
  355. if (item.getId().equals(itemId)) {
  356. addedItems.remove(item);
  357. fireContentsChange();
  358. return true;
  359. }
  360. }
  361. if (autoCommit) {
  362. /* Remove and commit instantly. */
  363. Item i = getItem(itemId);
  364. if (i == null) {
  365. return false;
  366. }
  367. try {
  368. delegate.beginTransaction();
  369. boolean success = delegate.removeRow((RowItem) i);
  370. delegate.commit();
  371. refresh();
  372. if (notificationsEnabled) {
  373. CacheFlushNotifier.notifyOfCacheFlush(this);
  374. }
  375. if (success) {
  376. getLogger().log(Level.FINER, "Row removed from DB...");
  377. }
  378. return success;
  379. } catch (SQLException e) {
  380. getLogger().log(Level.WARNING,
  381. "Failed to remove row, rolling back", e);
  382. try {
  383. delegate.rollback();
  384. } catch (SQLException ee) {
  385. /* Nothing can be done here */
  386. getLogger().log(Level.SEVERE,
  387. "Failed to rollback row removal", ee);
  388. }
  389. return false;
  390. } catch (OptimisticLockException e) {
  391. getLogger().log(Level.WARNING,
  392. "Failed to remove row, rolling back", e);
  393. try {
  394. delegate.rollback();
  395. } catch (SQLException ee) {
  396. /* Nothing can be done here */
  397. getLogger().log(Level.SEVERE,
  398. "Failed to rollback row removal", ee);
  399. }
  400. throw e;
  401. }
  402. } else {
  403. removedItems.put((RowId) itemId, (RowItem) getItem(itemId));
  404. cachedItems.remove(itemId);
  405. refresh();
  406. return true;
  407. }
  408. }
  409. /*
  410. * (non-Javadoc)
  411. *
  412. * @see com.vaadin.data.Container#removeAllItems()
  413. */
  414. @Override
  415. public boolean removeAllItems() throws UnsupportedOperationException {
  416. if (autoCommit) {
  417. /* Remove and commit instantly. */
  418. try {
  419. delegate.beginTransaction();
  420. boolean success = true;
  421. for (Object id : getItemIds()) {
  422. if (!delegate.removeRow((RowItem) getItem(id))) {
  423. success = false;
  424. }
  425. }
  426. if (success) {
  427. delegate.commit();
  428. getLogger().log(Level.FINER, "All rows removed from DB...");
  429. refresh();
  430. if (notificationsEnabled) {
  431. CacheFlushNotifier.notifyOfCacheFlush(this);
  432. }
  433. } else {
  434. delegate.rollback();
  435. }
  436. return success;
  437. } catch (SQLException e) {
  438. getLogger().log(Level.WARNING,
  439. "removeAllItems() failed, rolling back", e);
  440. try {
  441. delegate.rollback();
  442. } catch (SQLException ee) {
  443. /* Nothing can be done here */
  444. getLogger().log(Level.SEVERE, "Failed to roll back", ee);
  445. }
  446. return false;
  447. } catch (OptimisticLockException e) {
  448. getLogger().log(Level.WARNING,
  449. "removeAllItems() failed, rolling back", e);
  450. try {
  451. delegate.rollback();
  452. } catch (SQLException ee) {
  453. /* Nothing can be done here */
  454. getLogger().log(Level.SEVERE, "Failed to roll back", ee);
  455. }
  456. throw e;
  457. }
  458. } else {
  459. for (Object id : getItemIds()) {
  460. removedItems.put((RowId) id, (RowItem) getItem(id));
  461. cachedItems.remove(id);
  462. }
  463. refresh();
  464. return true;
  465. }
  466. }
  467. /*************************************************/
  468. /** Methods from interface Container.Filterable **/
  469. /*************************************************/
  470. /**
  471. * {@inheritDoc}
  472. */
  473. @Override
  474. public void addContainerFilter(Filter filter)
  475. throws UnsupportedFilterException {
  476. // filter.setCaseSensitive(!ignoreCase);
  477. filters.add(filter);
  478. refresh();
  479. }
  480. /**
  481. * {@inheritDoc}
  482. */
  483. @Override
  484. public void removeContainerFilter(Filter filter) {
  485. filters.remove(filter);
  486. }
  487. /**
  488. * {@inheritDoc}
  489. */
  490. public void addContainerFilter(Object propertyId, String filterString,
  491. boolean ignoreCase, boolean onlyMatchPrefix) {
  492. if (propertyId == null || !propertyIds.contains(propertyId)) {
  493. return;
  494. }
  495. /* Generate Filter -object */
  496. String likeStr = onlyMatchPrefix ? filterString + "%" : "%"
  497. + filterString + "%";
  498. Like like = new Like(propertyId.toString(), likeStr);
  499. like.setCaseSensitive(!ignoreCase);
  500. filters.add(like);
  501. refresh();
  502. }
  503. /**
  504. * {@inheritDoc}
  505. */
  506. public void removeContainerFilters(Object propertyId) {
  507. ArrayList<Filter> toRemove = new ArrayList<Filter>();
  508. for (Filter f : filters) {
  509. if (f.appliesToProperty(propertyId)) {
  510. toRemove.add(f);
  511. }
  512. }
  513. filters.removeAll(toRemove);
  514. refresh();
  515. }
  516. /**
  517. * {@inheritDoc}
  518. */
  519. @Override
  520. public void removeAllContainerFilters() {
  521. filters.clear();
  522. refresh();
  523. }
  524. /**********************************************/
  525. /** Methods from interface Container.Indexed **/
  526. /**********************************************/
  527. /*
  528. * (non-Javadoc)
  529. *
  530. * @see com.vaadin.data.Container.Indexed#indexOfId(java.lang.Object)
  531. */
  532. @Override
  533. public int indexOfId(Object itemId) {
  534. // First check if the id is in the added items
  535. for (int ix = 0; ix < addedItems.size(); ix++) {
  536. RowItem item = addedItems.get(ix);
  537. if (item.getId().equals(itemId)) {
  538. if (itemPassesFilters(item)) {
  539. updateCount();
  540. return size + ix;
  541. } else {
  542. return -1;
  543. }
  544. }
  545. }
  546. if (!containsId(itemId)) {
  547. return -1;
  548. }
  549. if (cachedItems.isEmpty()) {
  550. getPage();
  551. }
  552. int size = size();
  553. boolean wrappedAround = false;
  554. while (!wrappedAround) {
  555. for (Integer i : itemIndexes.keySet()) {
  556. if (itemIndexes.get(i).equals(itemId)) {
  557. return i;
  558. }
  559. }
  560. // load in the next page.
  561. int nextIndex = (currentOffset / (pageLength * CACHE_RATIO) + 1)
  562. * (pageLength * CACHE_RATIO);
  563. if (nextIndex >= size) {
  564. // Container wrapped around, start from index 0.
  565. wrappedAround = true;
  566. nextIndex = 0;
  567. }
  568. updateOffsetAndCache(nextIndex);
  569. }
  570. return -1;
  571. }
  572. /*
  573. * (non-Javadoc)
  574. *
  575. * @see com.vaadin.data.Container.Indexed#getIdByIndex(int)
  576. */
  577. @Override
  578. public Object getIdByIndex(int index) {
  579. if (index < 0 || index > size() - 1) {
  580. return null;
  581. }
  582. if (index < size) {
  583. if (itemIndexes.keySet().contains(index)) {
  584. return itemIndexes.get(index);
  585. }
  586. updateOffsetAndCache(index);
  587. return itemIndexes.get(index);
  588. } else {
  589. // The index is in the added items
  590. int offset = index - size;
  591. return addedItems.get(offset).getId();
  592. }
  593. }
  594. /**********************************************/
  595. /** Methods from interface Container.Ordered **/
  596. /**********************************************/
  597. /*
  598. * (non-Javadoc)
  599. *
  600. * @see com.vaadin.data.Container.Ordered#nextItemId(java.lang.Object)
  601. */
  602. @Override
  603. public Object nextItemId(Object itemId) {
  604. return getIdByIndex(indexOfId(itemId) + 1);
  605. }
  606. /*
  607. * (non-Javadoc)
  608. *
  609. * @see com.vaadin.data.Container.Ordered#prevItemId(java.lang.Object)
  610. */
  611. @Override
  612. public Object prevItemId(Object itemId) {
  613. return getIdByIndex(indexOfId(itemId) - 1);
  614. }
  615. /*
  616. * (non-Javadoc)
  617. *
  618. * @see com.vaadin.data.Container.Ordered#firstItemId()
  619. */
  620. @Override
  621. public Object firstItemId() {
  622. updateCount();
  623. if (size == 0) {
  624. if (addedItems.isEmpty()) {
  625. return null;
  626. } else {
  627. int ix = -1;
  628. do {
  629. ix++;
  630. } while (!itemPassesFilters(addedItems.get(ix))
  631. && ix < addedItems.size());
  632. if (ix < addedItems.size()) {
  633. return addedItems.get(ix).getId();
  634. }
  635. }
  636. }
  637. if (!itemIndexes.containsKey(0)) {
  638. updateOffsetAndCache(0);
  639. }
  640. return itemIndexes.get(0);
  641. }
  642. /*
  643. * (non-Javadoc)
  644. *
  645. * @see com.vaadin.data.Container.Ordered#lastItemId()
  646. */
  647. @Override
  648. public Object lastItemId() {
  649. if (addedItems.isEmpty()) {
  650. int lastIx = size() - 1;
  651. if (!itemIndexes.containsKey(lastIx)) {
  652. updateOffsetAndCache(size - 1);
  653. }
  654. return itemIndexes.get(lastIx);
  655. } else {
  656. int ix = addedItems.size();
  657. do {
  658. ix--;
  659. } while (!itemPassesFilters(addedItems.get(ix)) && ix >= 0);
  660. if (ix >= 0) {
  661. return addedItems.get(ix).getId();
  662. } else {
  663. return null;
  664. }
  665. }
  666. }
  667. /*
  668. * (non-Javadoc)
  669. *
  670. * @see com.vaadin.data.Container.Ordered#isFirstId(java.lang.Object)
  671. */
  672. @Override
  673. public boolean isFirstId(Object itemId) {
  674. return firstItemId().equals(itemId);
  675. }
  676. /*
  677. * (non-Javadoc)
  678. *
  679. * @see com.vaadin.data.Container.Ordered#isLastId(java.lang.Object)
  680. */
  681. @Override
  682. public boolean isLastId(Object itemId) {
  683. return lastItemId().equals(itemId);
  684. }
  685. /***********************************************/
  686. /** Methods from interface Container.Sortable **/
  687. /***********************************************/
  688. /*
  689. * (non-Javadoc)
  690. *
  691. * @see com.vaadin.data.Container.Sortable#sort(java.lang.Object[],
  692. * boolean[])
  693. */
  694. @Override
  695. public void sort(Object[] propertyId, boolean[] ascending) {
  696. sorters.clear();
  697. if (propertyId == null || propertyId.length == 0) {
  698. refresh();
  699. return;
  700. }
  701. /* Generate OrderBy -objects */
  702. boolean asc = true;
  703. for (int i = 0; i < propertyId.length; i++) {
  704. /* Check that the property id is valid */
  705. if (propertyId[i] instanceof String
  706. && propertyIds.contains(propertyId[i])) {
  707. try {
  708. asc = ascending[i];
  709. } catch (Exception e) {
  710. getLogger().log(Level.WARNING, "", e);
  711. }
  712. sorters.add(new OrderBy((String) propertyId[i], asc));
  713. }
  714. }
  715. refresh();
  716. }
  717. /*
  718. * (non-Javadoc)
  719. *
  720. * @see com.vaadin.data.Container.Sortable#getSortableContainerPropertyIds()
  721. */
  722. @Override
  723. public Collection<?> getSortableContainerPropertyIds() {
  724. return getContainerPropertyIds();
  725. }
  726. /**************************************/
  727. /** Methods specific to SQLContainer **/
  728. /**************************************/
  729. /**
  730. * Refreshes the container - clears all caches and resets size and offset.
  731. * Does NOT remove sorting or filtering rules!
  732. */
  733. public void refresh() {
  734. sizeDirty = true;
  735. currentOffset = 0;
  736. cachedItems.clear();
  737. itemIndexes.clear();
  738. fireContentsChange();
  739. }
  740. /**
  741. * Returns modify state of the container.
  742. *
  743. * @return true if contents of this container have been modified
  744. */
  745. public boolean isModified() {
  746. return !removedItems.isEmpty() || !addedItems.isEmpty()
  747. || !modifiedItems.isEmpty();
  748. }
  749. /**
  750. * Set auto commit mode enabled or disabled. Auto commit mode means that all
  751. * changes made to items of this container will be immediately written to
  752. * the underlying data source.
  753. *
  754. * @param autoCommitEnabled
  755. * true to enable auto commit mode
  756. */
  757. public void setAutoCommit(boolean autoCommitEnabled) {
  758. autoCommit = autoCommitEnabled;
  759. }
  760. /**
  761. * Returns status of the auto commit mode.
  762. *
  763. * @return true if auto commit mode is enabled
  764. */
  765. public boolean isAutoCommit() {
  766. return autoCommit;
  767. }
  768. /**
  769. * Returns the currently set page length.
  770. *
  771. * @return current page length
  772. */
  773. public int getPageLength() {
  774. return pageLength;
  775. }
  776. /**
  777. * Sets the page length used in lazy fetching of items from the data source.
  778. * Also resets the cache size to match the new page length.
  779. *
  780. * As a side effect the container will be refreshed.
  781. *
  782. * @param pageLength
  783. * new page length
  784. */
  785. public void setPageLength(int pageLength) {
  786. setPageLengthInternal(pageLength);
  787. refresh();
  788. }
  789. /**
  790. * Sets the page length internally, without refreshing the container.
  791. *
  792. * @param pageLength
  793. * the new page length
  794. */
  795. private void setPageLengthInternal(int pageLength) {
  796. this.pageLength = pageLength > 0 ? pageLength : DEFAULT_PAGE_LENGTH;
  797. cachedItems.setCacheLimit(CACHE_RATIO * getPageLength());
  798. }
  799. /**
  800. * Adds the given OrderBy to this container and refreshes the container
  801. * contents with the new sorting rules.
  802. *
  803. * Note that orderBy.getColumn() must return a column name that exists in
  804. * this container.
  805. *
  806. * @param orderBy
  807. * OrderBy to be added to the container sorting rules
  808. */
  809. public void addOrderBy(OrderBy orderBy) {
  810. if (orderBy == null) {
  811. return;
  812. }
  813. if (!propertyIds.contains(orderBy.getColumn())) {
  814. throw new IllegalArgumentException(
  815. "The column given for sorting does not exist in this container.");
  816. }
  817. sorters.add(orderBy);
  818. refresh();
  819. }
  820. /**
  821. * Commits all the changes, additions and removals made to the items of this
  822. * container.
  823. *
  824. * @throws UnsupportedOperationException
  825. * @throws SQLException
  826. */
  827. public void commit() throws UnsupportedOperationException, SQLException {
  828. try {
  829. getLogger().log(Level.FINER,
  830. "Commiting changes through delegate...");
  831. delegate.beginTransaction();
  832. /* Perform buffered deletions */
  833. for (RowItem item : removedItems.values()) {
  834. if (!delegate.removeRow(item)) {
  835. throw new SQLException("Removal failed for row with ID: "
  836. + item.getId());
  837. }
  838. }
  839. /* Perform buffered modifications */
  840. for (RowItem item : modifiedItems) {
  841. if (delegate.storeRow(item) > 0) {
  842. /*
  843. * Also reset the modified state in the item in case it is
  844. * reused e.g. in a form.
  845. */
  846. item.commit();
  847. } else {
  848. delegate.rollback();
  849. refresh();
  850. throw new ConcurrentModificationException(
  851. "Item with the ID '" + item.getId()
  852. + "' has been externally modified.");
  853. }
  854. }
  855. /* Perform buffered additions */
  856. for (RowItem item : addedItems) {
  857. delegate.storeRow(item);
  858. }
  859. delegate.commit();
  860. removedItems.clear();
  861. addedItems.clear();
  862. modifiedItems.clear();
  863. refresh();
  864. if (notificationsEnabled) {
  865. CacheFlushNotifier.notifyOfCacheFlush(this);
  866. }
  867. } catch (SQLException e) {
  868. delegate.rollback();
  869. throw e;
  870. } catch (OptimisticLockException e) {
  871. delegate.rollback();
  872. throw e;
  873. }
  874. }
  875. /**
  876. * Rolls back all the changes, additions and removals made to the items of
  877. * this container.
  878. *
  879. * @throws UnsupportedOperationException
  880. * @throws SQLException
  881. */
  882. public void rollback() throws UnsupportedOperationException, SQLException {
  883. getLogger().log(Level.FINE, "Rolling back changes...");
  884. removedItems.clear();
  885. addedItems.clear();
  886. modifiedItems.clear();
  887. refresh();
  888. }
  889. /**
  890. * Notifies this container that a property in the given item has been
  891. * modified. The change will be buffered or made instantaneously depending
  892. * on auto commit mode.
  893. *
  894. * @param changedItem
  895. * item that has a modified property
  896. */
  897. void itemChangeNotification(RowItem changedItem) {
  898. if (autoCommit) {
  899. try {
  900. delegate.beginTransaction();
  901. if (delegate.storeRow(changedItem) == 0) {
  902. delegate.rollback();
  903. refresh();
  904. throw new ConcurrentModificationException(
  905. "Item with the ID '" + changedItem.getId()
  906. + "' has been externally modified.");
  907. }
  908. delegate.commit();
  909. if (notificationsEnabled) {
  910. CacheFlushNotifier.notifyOfCacheFlush(this);
  911. }
  912. getLogger().log(Level.FINER, "Row updated to DB...");
  913. } catch (SQLException e) {
  914. getLogger().log(Level.WARNING,
  915. "itemChangeNotification failed, rolling back...", e);
  916. try {
  917. delegate.rollback();
  918. } catch (SQLException ee) {
  919. /* Nothing can be done here */
  920. getLogger().log(Level.SEVERE, "Rollback failed", e);
  921. }
  922. throw new RuntimeException(e);
  923. }
  924. } else {
  925. if (!(changedItem.getId() instanceof TemporaryRowId)
  926. && !modifiedItems.contains(changedItem)) {
  927. modifiedItems.add(changedItem);
  928. }
  929. }
  930. }
  931. /**
  932. * Determines a new offset for updating the row cache. The offset is
  933. * calculated from the given index, and will be fixed to match the start of
  934. * a page, based on the value of pageLength.
  935. *
  936. * @param index
  937. * Index of the item that was requested, but not found in cache
  938. */
  939. private void updateOffsetAndCache(int index) {
  940. if (itemIndexes.containsKey(index)) {
  941. return;
  942. }
  943. currentOffset = (index / (pageLength * CACHE_RATIO))
  944. * (pageLength * CACHE_RATIO);
  945. if (currentOffset < 0) {
  946. currentOffset = 0;
  947. }
  948. getPage();
  949. }
  950. /**
  951. * Fetches new count of rows from the data source, if needed.
  952. */
  953. private void updateCount() {
  954. if (!sizeDirty
  955. && new Date().getTime() < sizeUpdated.getTime()
  956. + sizeValidMilliSeconds) {
  957. return;
  958. }
  959. try {
  960. try {
  961. delegate.setFilters(filters);
  962. } catch (UnsupportedOperationException e) {
  963. getLogger().log(Level.FINE,
  964. "The query delegate doesn't support filtering", e);
  965. }
  966. try {
  967. delegate.setOrderBy(sorters);
  968. } catch (UnsupportedOperationException e) {
  969. getLogger().log(Level.FINE,
  970. "The query delegate doesn't support filtering", e);
  971. }
  972. int newSize = delegate.getCount();
  973. if (newSize != size) {
  974. size = newSize;
  975. refresh();
  976. }
  977. sizeUpdated = new Date();
  978. sizeDirty = false;
  979. getLogger().log(Level.FINER,
  980. "Updated row count. New count is: " + size);
  981. } catch (SQLException e) {
  982. throw new RuntimeException("Failed to update item set size.", e);
  983. }
  984. }
  985. /**
  986. * Fetches property id's (column names and their types) from the data
  987. * source.
  988. *
  989. * @throws SQLException
  990. */
  991. private void getPropertyIds() throws SQLException {
  992. propertyIds.clear();
  993. propertyTypes.clear();
  994. delegate.setFilters(null);
  995. delegate.setOrderBy(null);
  996. ResultSet rs = null;
  997. ResultSetMetaData rsmd = null;
  998. try {
  999. delegate.beginTransaction();
  1000. rs = delegate.getResults(0, 1);
  1001. boolean resultExists = rs.next();
  1002. rsmd = rs.getMetaData();
  1003. Class<?> type = null;
  1004. for (int i = 1; i <= rsmd.getColumnCount(); i++) {
  1005. if (!isColumnIdentifierValid(rsmd.getColumnLabel(i))) {
  1006. continue;
  1007. }
  1008. String colName = rsmd.getColumnLabel(i);
  1009. /*
  1010. * Make sure not to add the same colName twice. This can easily
  1011. * happen if the SQL query joins many tables with an ID column.
  1012. */
  1013. if (!propertyIds.contains(colName)) {
  1014. propertyIds.add(colName);
  1015. }
  1016. /* Try to determine the column's JDBC class by all means. */
  1017. if (resultExists && rs.getObject(i) != null) {
  1018. type = rs.getObject(i).getClass();
  1019. } else {
  1020. try {
  1021. type = Class.forName(rsmd.getColumnClassName(i));
  1022. } catch (Exception e) {
  1023. getLogger().log(Level.WARNING, "Class not found", e);
  1024. /* On failure revert to Object and hope for the best. */
  1025. type = Object.class;
  1026. }
  1027. }
  1028. /*
  1029. * Determine read only and nullability status of the column. A
  1030. * column is read only if it is reported as either read only or
  1031. * auto increment by the database, and also it is set as the
  1032. * version column in a TableQuery delegate.
  1033. */
  1034. boolean readOnly = rsmd.isAutoIncrement(i)
  1035. || rsmd.isReadOnly(i);
  1036. if (delegate instanceof TableQuery
  1037. && rsmd.getColumnLabel(i).equals(
  1038. ((TableQuery) delegate).getVersionColumn())) {
  1039. readOnly = true;
  1040. }
  1041. propertyReadOnly.put(colName, readOnly);
  1042. propertyNullable.put(colName,
  1043. rsmd.isNullable(i) == ResultSetMetaData.columnNullable);
  1044. propertyTypes.put(colName, type);
  1045. }
  1046. rs.getStatement().close();
  1047. rs.close();
  1048. delegate.commit();
  1049. getLogger().log(Level.FINER, "Property IDs fetched.");
  1050. } catch (SQLException e) {
  1051. getLogger().log(Level.WARNING,
  1052. "Failed to fetch property ids, rolling back", e);
  1053. try {
  1054. delegate.rollback();
  1055. } catch (SQLException e1) {
  1056. getLogger().log(Level.SEVERE, "Failed to roll back", e1);
  1057. }
  1058. try {
  1059. if (rs != null) {
  1060. if (rs.getStatement() != null) {
  1061. rs.getStatement().close();
  1062. }
  1063. rs.close();
  1064. }
  1065. } catch (SQLException e1) {
  1066. getLogger().log(Level.WARNING, "Failed to close session", e1);
  1067. }
  1068. throw e;
  1069. }
  1070. }
  1071. /**
  1072. * Fetches a page from the data source based on the values of pageLenght and
  1073. * currentOffset. Also updates the set of primary keys, used in
  1074. * identification of RowItems.
  1075. */
  1076. private void getPage() {
  1077. updateCount();
  1078. ResultSet rs = null;
  1079. ResultSetMetaData rsmd = null;
  1080. cachedItems.clear();
  1081. itemIndexes.clear();
  1082. try {
  1083. try {
  1084. delegate.setOrderBy(sorters);
  1085. } catch (UnsupportedOperationException e) {
  1086. /* The query delegate doesn't support sorting. */
  1087. /* No need to do anything. */
  1088. getLogger().log(Level.FINE,
  1089. "The query delegate doesn't support sorting", e);
  1090. }
  1091. delegate.beginTransaction();
  1092. rs = delegate.getResults(currentOffset, pageLength * CACHE_RATIO);
  1093. rsmd = rs.getMetaData();
  1094. List<String> pKeys = delegate.getPrimaryKeyColumns();
  1095. // }
  1096. /* Create new items and column properties */
  1097. ColumnProperty cp = null;
  1098. int rowCount = currentOffset;
  1099. if (!delegate.implementationRespectsPagingLimits()) {
  1100. rowCount = currentOffset = 0;
  1101. setPageLengthInternal(size);
  1102. }
  1103. while (rs.next()) {
  1104. List<ColumnProperty> itemProperties = new ArrayList<ColumnProperty>();
  1105. /* Generate row itemId based on primary key(s) */
  1106. Object[] itemId = new Object[pKeys.size()];
  1107. for (int i = 0; i < pKeys.size(); i++) {
  1108. itemId[i] = rs.getObject(pKeys.get(i));
  1109. }
  1110. RowId id = null;
  1111. if (pKeys.isEmpty()) {
  1112. id = new ReadOnlyRowId(rs.getRow());
  1113. } else {
  1114. id = new RowId(itemId);
  1115. }
  1116. List<String> propertiesToAdd = new ArrayList<String>(
  1117. propertyIds);
  1118. if (!removedItems.containsKey(id)) {
  1119. for (int i = 1; i <= rsmd.getColumnCount(); i++) {
  1120. if (!isColumnIdentifierValid(rsmd.getColumnLabel(i))) {
  1121. continue;
  1122. }
  1123. String colName = rsmd.getColumnLabel(i);
  1124. Object value = rs.getObject(i);
  1125. Class<?> type = value != null ? value.getClass()
  1126. : Object.class;
  1127. if (value == null) {
  1128. for (String propName : propertyTypes.keySet()) {
  1129. if (propName.equals(rsmd.getColumnLabel(i))) {
  1130. type = propertyTypes.get(propName);
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. /*
  1136. * In case there are more than one column with the same
  1137. * name, add only the first one. This can easily happen
  1138. * if you join many tables where each table has an ID
  1139. * column.
  1140. */
  1141. if (propertiesToAdd.contains(colName)) {
  1142. cp = new ColumnProperty(colName,
  1143. propertyReadOnly.get(colName),
  1144. !propertyReadOnly.get(colName),
  1145. propertyNullable.get(colName), value, type);
  1146. itemProperties.add(cp);
  1147. propertiesToAdd.remove(colName);
  1148. }
  1149. }
  1150. /* Cache item */
  1151. itemIndexes.put(rowCount, id);
  1152. // if an item with the id is contained in the modified
  1153. // cache, then use this record and add it to the cached
  1154. // items. Otherwise create a new item
  1155. int modifiedIndex = indexInModifiedCache(id);
  1156. if (modifiedIndex != -1) {
  1157. cachedItems.put(id, modifiedItems.get(modifiedIndex));
  1158. } else {
  1159. cachedItems.put(id, new RowItem(this, id,
  1160. itemProperties));
  1161. }
  1162. rowCount++;
  1163. }
  1164. }
  1165. rs.getStatement().close();
  1166. rs.close();
  1167. delegate.commit();
  1168. getLogger().log(
  1169. Level.FINER,
  1170. "Fetched " + pageLength * CACHE_RATIO
  1171. + " rows starting from " + currentOffset);
  1172. } catch (SQLException e) {
  1173. getLogger().log(Level.WARNING,
  1174. "Failed to fetch rows, rolling back", e);
  1175. try {
  1176. delegate.rollback();
  1177. } catch (SQLException e1) {
  1178. getLogger().log(Level.SEVERE, "Failed to roll back", e1);
  1179. }
  1180. try {
  1181. if (rs != null) {
  1182. if (rs.getStatement() != null) {
  1183. rs.getStatement().close();
  1184. rs.close();
  1185. }
  1186. }
  1187. } catch (SQLException e1) {
  1188. getLogger().log(Level.WARNING, "Failed to close session", e1);
  1189. }
  1190. throw new RuntimeException("Failed to fetch page.", e);
  1191. }
  1192. }
  1193. /**
  1194. * Returns the index of the item with the given itemId for the modified
  1195. * cache.
  1196. *
  1197. * @param itemId
  1198. * @return the index of the item with the itemId in the modified cache. Or
  1199. * -1 if not found.
  1200. */
  1201. private int indexInModifiedCache(Object itemId) {
  1202. for (int ix = 0; ix < modifiedItems.size(); ix++) {
  1203. RowItem item = modifiedItems.get(ix);
  1204. if (item.getId().equals(itemId)) {
  1205. return ix;
  1206. }
  1207. }
  1208. return -1;
  1209. }
  1210. private int sizeOfAddedItems() {
  1211. return getFilteredAddedItems().size();
  1212. }
  1213. private List<RowItem> getFilteredAddedItems() {
  1214. ArrayList<RowItem> filtered = new ArrayList<RowItem>(addedItems);
  1215. if (filters != null && !filters.isEmpty()) {
  1216. for (RowItem item : addedItems) {
  1217. if (!itemPassesFilters(item)) {
  1218. filtered.remove(item);
  1219. }
  1220. }
  1221. }
  1222. return filtered;
  1223. }
  1224. private boolean itemPassesFilters(RowItem item) {
  1225. for (Filter filter : filters) {
  1226. if (!filter.passesFilter(item.getId(), item)) {
  1227. return false;
  1228. }
  1229. }
  1230. return true;
  1231. }
  1232. /**
  1233. * Checks is the given column identifier valid to be used with SQLContainer.
  1234. * Currently the only non-valid identifier is "rownum" when MSSQL or Oracle
  1235. * is used. This is due to the way the SELECT queries are constructed in
  1236. * order to implement paging in these databases.
  1237. *
  1238. * @param identifier
  1239. * Column identifier
  1240. * @return true if the identifier is valid
  1241. */
  1242. private boolean isColumnIdentifierValid(String identifier) {
  1243. if (identifier.equalsIgnoreCase("rownum")
  1244. && delegate instanceof TableQuery) {
  1245. TableQuery tq = (TableQuery) delegate;
  1246. if (tq.getSqlGenerator() instanceof MSSQLGenerator
  1247. || tq.getSqlGenerator() instanceof OracleGenerator) {
  1248. return false;
  1249. }
  1250. }
  1251. return true;
  1252. }
  1253. /**
  1254. * Returns the QueryDelegate set for this SQLContainer.
  1255. *
  1256. * @return current querydelegate
  1257. */
  1258. protected QueryDelegate getQueryDelegate() {
  1259. return delegate;
  1260. }
  1261. /************************************/
  1262. /** UNSUPPORTED CONTAINER FEATURES **/
  1263. /************************************/
  1264. /*
  1265. * (non-Javadoc)
  1266. *
  1267. * @see com.vaadin.data.Container#addContainerProperty(java.lang.Object,
  1268. * java.lang.Class, java.lang.Object)
  1269. */
  1270. @Override
  1271. public boolean addContainerProperty(Object propertyId, Class<?> type,
  1272. Object defaultValue) throws UnsupportedOperationException {
  1273. throw new UnsupportedOperationException();
  1274. }
  1275. /*
  1276. * (non-Javadoc)
  1277. *
  1278. * @see com.vaadin.data.Container#removeContainerProperty(java.lang.Object)
  1279. */
  1280. @Override
  1281. public boolean removeContainerProperty(Object propertyId)
  1282. throws UnsupportedOperationException {
  1283. throw new UnsupportedOperationException();
  1284. }
  1285. /*
  1286. * (non-Javadoc)
  1287. *
  1288. * @see com.vaadin.data.Container#addItem(java.lang.Object)
  1289. */
  1290. @Override
  1291. public Item addItem(Object itemId) throws UnsupportedOperationException {
  1292. throw new UnsupportedOperationException();
  1293. }
  1294. /*
  1295. * (non-Javadoc)
  1296. *
  1297. * @see com.vaadin.data.Container.Ordered#addItemAfter(java.lang.Object,
  1298. * java.lang.Object)
  1299. */
  1300. @Override
  1301. public Item addItemAfter(Object previousItemId, Object newItemId)
  1302. throws UnsupportedOperationException {
  1303. throw new UnsupportedOperationException();
  1304. }
  1305. /*
  1306. * (non-Javadoc)
  1307. *
  1308. * @see com.vaadin.data.Container.Indexed#addItemAt(int, java.lang.Object)
  1309. */
  1310. @Override
  1311. public Item addItemAt(int index, Object newItemId)
  1312. throws UnsupportedOperationException {
  1313. throw new UnsupportedOperationException();
  1314. }
  1315. /*
  1316. * (non-Javadoc)
  1317. *
  1318. * @see com.vaadin.data.Container.Indexed#addItemAt(int)
  1319. */
  1320. @Override
  1321. public Object addItemAt(int index) throws UnsupportedOperationException {
  1322. throw new UnsupportedOperationException();
  1323. }
  1324. /*
  1325. * (non-Javadoc)
  1326. *
  1327. * @see com.vaadin.data.Container.Ordered#addItemAfter(java.lang.Object)
  1328. */
  1329. @Override
  1330. public Object addItemAfter(Object previousItemId)
  1331. throws UnsupportedOperationException {
  1332. throw new UnsupportedOperationException();
  1333. }
  1334. /******************************************/
  1335. /** ITEMSETCHANGENOTIFIER IMPLEMENTATION **/
  1336. /******************************************/
  1337. /*
  1338. * (non-Javadoc)
  1339. *
  1340. * @see
  1341. * com.vaadin.data.Container.ItemSetChangeNotifier#addListener(com.vaadin
  1342. * .data.Container.ItemSetChangeListener)
  1343. */
  1344. @Override
  1345. public void addListener(Container.ItemSetChangeListener listener) {
  1346. if (itemSetChangeListeners == null) {
  1347. itemSetChangeListeners = new LinkedList<Container.ItemSetChangeListener>();
  1348. }
  1349. itemSetChangeListeners.add(listener);
  1350. }
  1351. /*
  1352. * (non-Javadoc)
  1353. *
  1354. * @see
  1355. * com.vaadin.data.Container.ItemSetChangeNotifier#removeListener(com.vaadin
  1356. * .data.Container.ItemSetChangeListener)
  1357. */
  1358. @Override
  1359. public void removeListener(Container.ItemSetChangeListener listener) {
  1360. if (itemSetChangeListeners != null) {
  1361. itemSetChangeListeners.remove(listener);
  1362. }
  1363. }
  1364. protected void fireContentsChange() {
  1365. if (itemSetChangeListeners != null) {
  1366. final Object[] l = itemSetChangeListeners.toArray();
  1367. final Container.ItemSetChangeEvent event = new SQLContainer.ItemSetChangeEvent(
  1368. this);
  1369. for (int i = 0; i < l.length; i++) {
  1370. ((Container.ItemSetChangeListener) l[i])
  1371. .containerItemSetChange(event);
  1372. }
  1373. }
  1374. }
  1375. /**
  1376. * Simple ItemSetChangeEvent implementation.
  1377. */
  1378. @SuppressWarnings("serial")
  1379. public static class ItemSetChangeEvent extends EventObject implements
  1380. Container.ItemSetChangeEvent {
  1381. private ItemSetChangeEvent(SQLContainer source) {
  1382. super(source);
  1383. }
  1384. @Override
  1385. public Container getContainer() {
  1386. return (Container) getSource();
  1387. }
  1388. }
  1389. /**************************************************/
  1390. /** ROWIDCHANGELISTENER PASSING TO QUERYDELEGATE **/
  1391. /**************************************************/
  1392. /**
  1393. * Adds a RowIdChangeListener to the QueryDelegate
  1394. *
  1395. * @param listener
  1396. */
  1397. public void addListener(RowIdChangeListener listener) {
  1398. if (delegate instanceof QueryDelegate.RowIdChangeNotifier) {
  1399. ((QueryDelegate.RowIdChangeNotifier) delegate)
  1400. .addListener(listener);
  1401. }
  1402. }
  1403. /**
  1404. * Removes a RowIdChangeListener from the QueryDelegate
  1405. *
  1406. * @param listener
  1407. */
  1408. public void removeListener(RowIdChangeListener listener) {
  1409. if (delegate instanceof QueryDelegate.RowIdChangeNotifier) {
  1410. ((QueryDelegate.RowIdChangeNotifier) delegate)
  1411. .removeListener(listener);
  1412. }
  1413. }
  1414. /**
  1415. * Calling this will enable this SQLContainer to send and receive cache
  1416. * flush notifications for its lifetime.
  1417. */
  1418. public void enableCacheFlushNotifications() {
  1419. if (!notificationsEnabled) {
  1420. notificationsEnabled = true;
  1421. CacheFlushNotifier.addInstance(this);
  1422. }
  1423. }
  1424. /******************************************/
  1425. /** Referencing mechanism implementation **/
  1426. /******************************************/
  1427. /**
  1428. * Adds a new reference to the given SQLContainer. In addition to the
  1429. * container you must provide the column (property) names used for the
  1430. * reference in both this and the referenced SQLContainer.
  1431. *
  1432. * Note that multiple references pointing to the same SQLContainer are not
  1433. * supported.
  1434. *
  1435. * @param refdCont
  1436. * Target SQLContainer of the new reference
  1437. * @param refingCol
  1438. * Column (property) name in this container storing the (foreign
  1439. * key) reference
  1440. * @param refdCol
  1441. * Column (property) name in the referenced container storing the
  1442. * referenced key
  1443. */
  1444. public void addReference(SQLContainer refdCont, String refingCol,
  1445. String refdCol) {
  1446. if (refdCont == null) {
  1447. throw new IllegalArgumentException(
  1448. "Referenced SQLContainer can not be null.");
  1449. }
  1450. if (!getContainerPropertyIds().contains(refingCol)) {
  1451. throw new IllegalArgumentException(
  1452. "Given referencing column name is invalid."
  1453. + " Please ensure that this container"
  1454. + " contains a property ID named: " + refingCol);
  1455. }
  1456. if (!refdCont.getContainerPropertyIds().contains(refdCol)) {
  1457. throw new IllegalArgumentException(
  1458. "Given referenced column name is invalid."
  1459. + " Please ensure that the referenced container"
  1460. + " contains a property ID named: " + refdCol);
  1461. }
  1462. if (references.keySet().contains(refdCont)) {
  1463. throw new IllegalArgumentException(
  1464. "An SQLContainer instance can only be referenced once.");
  1465. }
  1466. references.put(refdCont, new Reference(refdCont, refingCol, refdCol));
  1467. }
  1468. /**
  1469. * Removes the reference pointing to the given SQLContainer.
  1470. *
  1471. * @param refdCont
  1472. * Target SQLContainer of the reference
  1473. * @return true if successful, false if the reference did not exist
  1474. */
  1475. public boolean removeReference(SQLContainer refdCont) {
  1476. if (refdCont == null) {
  1477. throw new IllegalArgumentException(
  1478. "Referenced SQLContainer can not be null.");
  1479. }
  1480. return references.remove(refdCont) == null ? false : true;
  1481. }
  1482. /**
  1483. * Sets the referenced item. The referencing column of the item in this
  1484. * container is updated accordingly.
  1485. *
  1486. * @param itemId
  1487. * Item Id of the reference source (from this container)
  1488. * @param refdItemId
  1489. * Item Id of the reference target (from referenced container)
  1490. * @param refdCont
  1491. * Target SQLContainer of the reference
  1492. * @return true if the referenced item was successfully set, false on
  1493. * failure
  1494. */
  1495. public boolean setReferencedItem(Object itemId, Object refdItemId,
  1496. SQLContainer refdCont) {
  1497. if (refdCont == null) {
  1498. throw new IllegalArgumentException(
  1499. "Referenced SQLContainer can not be null.");
  1500. }
  1501. Reference r = references.get(refdCont);
  1502. if (r == null) {
  1503. throw new IllegalArgumentException(
  1504. "Reference to the given SQLContainer not defined.");
  1505. }
  1506. try {
  1507. getContainerProperty(itemId, r.getReferencingColumn()).setValue(
  1508. refdCont.getContainerProperty(refdItemId,
  1509. r.getReferencedColumn()));
  1510. return true;
  1511. } catch (Exception e) {
  1512. getLogger()
  1513. .log(Level.WARNING, "Setting referenced item failed.", e);
  1514. return false;
  1515. }
  1516. }
  1517. /**
  1518. * Fetches the Item Id of the referenced item from the target SQLContainer.
  1519. *
  1520. * @param itemId
  1521. * Item Id of the reference source (from this container)
  1522. * @param refdCont
  1523. * Target SQLContainer of the reference
  1524. * @return Item Id of the referenced item, or null if not found
  1525. */
  1526. public Object getReferencedItemId(Object itemId, SQLContainer refdCont) {
  1527. if (refdCont == null) {
  1528. throw new IllegalArgumentException(
  1529. "Referenced SQLContainer can not be null.");
  1530. }
  1531. Reference r = references.get(refdCont);
  1532. if (r == null) {
  1533. throw new IllegalArgumentException(
  1534. "Reference to the given SQLContainer not defined.");
  1535. }
  1536. Object refKey = getContainerProperty(itemId, r.getReferencingColumn())
  1537. .getValue();
  1538. refdCont.removeAllContainerFilters();
  1539. refdCont.addContainerFilter(new Equal(r.getReferencedColumn(), refKey));
  1540. Object toReturn = refdCont.firstItemId();
  1541. refdCont.removeAllContainerFilters();
  1542. return toReturn;
  1543. }
  1544. /**
  1545. * Fetches the referenced item from the target SQLContainer.
  1546. *
  1547. * @param itemId
  1548. * Item Id of the reference source (from this container)
  1549. * @param refdCont
  1550. * Target SQLContainer of the reference
  1551. * @return The referenced item, or null if not found
  1552. */
  1553. public Item getReferencedItem(Object itemId, SQLContainer refdCont) {
  1554. return refdCont.getItem(getReferencedItemId(itemId, refdCont));
  1555. }
  1556. private void writeObject(java.io.ObjectOutputStream out) throws IOException {
  1557. out.defaultWriteObject();
  1558. }
  1559. private void readObject(java.io.ObjectInputStream in) throws IOException,
  1560. ClassNotFoundException {
  1561. in.defaultReadObject();
  1562. if (notificationsEnabled) {
  1563. /*
  1564. * Register instance with CacheFlushNotifier after de-serialization
  1565. * if notifications are enabled
  1566. */
  1567. CacheFlushNotifier.addInstance(this);
  1568. }
  1569. }
  1570. private static final Logger getLogger() {
  1571. return Logger.getLogger(SQLContainer.class.getName());
  1572. }
  1573. }