| 1 | /** |
| 2 | * Copyright (C) 2007 NetMind Consulting Bt. |
| 3 | * |
| 4 | * This library is free software; you can redistribute it and/or |
| 5 | * modify it under the terms of the GNU Lesser General Public |
| 6 | * License as published by the Free Software Foundation; either |
| 7 | * version 3 of the License, or (at your option) any later version. |
| 8 | * |
| 9 | * This library is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 | * Lesser General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Lesser General Public |
| 15 | * License along with this library; if not, write to the Free Software |
| 16 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 17 | */ |
| 18 | |
| 19 | package hu.netmind.beankeeper.type.impl; |
| 20 | |
| 21 | import hu.netmind.beankeeper.type.event.*; |
| 22 | import java.util.*; |
| 23 | import hu.netmind.beankeeper.parser.*; |
| 24 | import hu.netmind.beankeeper.model.*; |
| 25 | import hu.netmind.beankeeper.transaction.Transaction; |
| 26 | import hu.netmind.beankeeper.transaction.TransactionTracker; |
| 27 | import hu.netmind.beankeeper.db.SearchResult; |
| 28 | import hu.netmind.beankeeper.db.Limits; |
| 29 | import hu.netmind.beankeeper.db.Database; |
| 30 | import hu.netmind.beankeeper.serial.Serial; |
| 31 | import hu.netmind.beankeeper.query.LazyList; |
| 32 | import hu.netmind.beankeeper.query.QueryService; |
| 33 | import hu.netmind.beankeeper.object.ObjectTracker; |
| 34 | import hu.netmind.beankeeper.schema.SchemaManager; |
| 35 | import org.apache.log4j.Logger; |
| 36 | |
| 37 | /** |
| 38 | * Custom set implementation based on lazy lists. This is <strong>not</strong> |
| 39 | * thread-safe. |
| 40 | * @author Brautigam Robert |
| 41 | * @version Revision: $Revision$ |
| 42 | */ |
| 43 | public class SetImpl extends AbstractSet implements Container |
| 44 | { |
| 45 | private static final int INT_BITS = 32; |
| 46 | private static Logger logger = Logger.getLogger(SetImpl.class); |
| 47 | |
| 48 | private List originalList; |
| 49 | private TimeControl originalTimeControl; |
| 50 | private ClassInfo parentInfo; |
| 51 | private Object parent; |
| 52 | private String parentAttributeName; |
| 53 | private ContainerItemClass itemClass; |
| 54 | private Long lastSerial; |
| 55 | |
| 56 | private Set addedItems; |
| 57 | private Set removedItems; |
| 58 | private boolean cleared = false; |
| 59 | private int modCount = 0; |
| 60 | |
| 61 | private ClassTracker classTracker = null; // Injected |
| 62 | private QueryService queryService = null; // Injected |
| 63 | private ObjectTracker objectTracker = null; // Injected |
| 64 | private Database database = null; // Injected |
| 65 | private TransactionTracker transactionTracker = null; // Injected |
| 66 | private SchemaManager schemaManager = null; // Injected |
| 67 | |
| 68 | /** |
| 69 | * Initialize with a default list. |
| 70 | */ |
| 71 | public void init(ClassInfo classInfo, Object obj, |
| 72 | String attributeName, String itemClassName, Long lastSerial, TimeControl timeControl) |
| 73 | { |
| 74 | this.originalList=null; |
| 75 | this.originalTimeControl=new TimeControl(timeControl); |
| 76 | this.parentInfo=classInfo; |
| 77 | this.parent=obj; |
| 78 | this.parentAttributeName=attributeName; |
| 79 | this.lastSerial=lastSerial; |
| 80 | this.itemClass=new ContainerItemClass(schemaManager,itemClassName); |
| 81 | // Model |
| 82 | reload(); |
| 83 | } |
| 84 | |
| 85 | public Object getParent() |
| 86 | { |
| 87 | return parent; |
| 88 | } |
| 89 | |
| 90 | public String getItemClassName() |
| 91 | { |
| 92 | return itemClass.getItemClassName(); |
| 93 | } |
| 94 | |
| 95 | public void reload() |
| 96 | { |
| 97 | // Load list. If original list is mutable (is not a lazylist), |
| 98 | // then leave it, it should be ok. |
| 99 | if ( getItemClassName() == null ) |
| 100 | { |
| 101 | originalList = new ArrayList(); |
| 102 | } else { |
| 103 | if ( originalList instanceof ArrayList ) |
| 104 | { |
| 105 | // Remove removed items |
| 106 | Iterator originalIterator = originalList.iterator(); |
| 107 | while ( originalIterator.hasNext() ) |
| 108 | { |
| 109 | Object item = originalIterator.next(); |
| 110 | if ( removedItems.contains(new ObjectWrapper(item)) ) |
| 111 | originalIterator.remove(); |
| 112 | } |
| 113 | // Add added items |
| 114 | Iterator addedIterator = addedItems.iterator(); |
| 115 | while ( addedIterator.hasNext() ) |
| 116 | { |
| 117 | ObjectWrapper wrapper = (ObjectWrapper) addedIterator.next(); |
| 118 | originalList.add(wrapper.getObject()); |
| 119 | } |
| 120 | } else { |
| 121 | originalList = queryService.find( |
| 122 | "find item("+getItemClassName()+")"+ |
| 123 | " where persistence_container_parent("+parentInfo.getSourceEntry().getFullName()+")"+ |
| 124 | "."+parentAttributeName+" contains item and persistence_container_parent = ?", |
| 125 | new Object[] { parent }, originalTimeControl,null); |
| 126 | } |
| 127 | } |
| 128 | // Initialize internal change structures |
| 129 | modCount++; |
| 130 | cleared = false; |
| 131 | addedItems = new HashSet(); |
| 132 | removedItems = new HashSet(); |
| 133 | } |
| 134 | |
| 135 | /** |
| 136 | * Returns whether the container changes internally since last save(). |
| 137 | */ |
| 138 | public boolean hasChanged() |
| 139 | { |
| 140 | return (addedItems.size()>0) || (removedItems.size()>0) || (cleared); |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * Save the container to database. |
| 145 | */ |
| 146 | public void save(Transaction transaction, Long currentSerial, Set waitingObjects, |
| 147 | Set saveTables, Set removeTables, List events) |
| 148 | { |
| 149 | ClassEntry attributeClassEntry = parentInfo.getAttributeClassEntry(parentAttributeName); |
| 150 | String attributeTableName = schemaManager.getTableName(attributeClassEntry,parentAttributeName); |
| 151 | // If the list was cleared before, then clear the current values |
| 152 | if ( cleared ) |
| 153 | { |
| 154 | HashMap keyAttributes = new HashMap(); |
| 155 | keyAttributes.put("persistence_id",objectTracker.getIdentifier(parent)); |
| 156 | keyAttributes.put("persistence_end",Serial.getMaxSerial().getValue()); |
| 157 | keyAttributes.put("persistence_txend",Serial.getMaxSerial().getValue()); |
| 158 | HashMap removeAttributes = new HashMap(); |
| 159 | removeAttributes.put("persistence_txend",currentSerial); |
| 160 | removeAttributes.put("persistence_txendid",transaction.getSerial()); |
| 161 | database.save(transaction,attributeTableName,keyAttributes,removeAttributes); |
| 162 | removeTables.add(attributeTableName); |
| 163 | // Notify listeners |
| 164 | events.add(new ClearedContainerEvent(parent,parentAttributeName)); |
| 165 | } |
| 166 | // Remove removed items first |
| 167 | Iterator removedItemsIterator = removedItems.iterator(); |
| 168 | while ( removedItemsIterator.hasNext() ) |
| 169 | { |
| 170 | ObjectWrapper wrapper = (ObjectWrapper) removedItemsIterator.next(); |
| 171 | Object obj = wrapper.getObject(); |
| 172 | // Remove object from the list |
| 173 | HashMap keyAttributes = new HashMap(); |
| 174 | keyAttributes.put("persistence_id",objectTracker.getIdentifier(parent)); |
| 175 | keyAttributes.put("persistence_end",Serial.getMaxSerial().getValue()); |
| 176 | keyAttributes.put("persistence_txend",Serial.getMaxSerial().getValue()); |
| 177 | keyAttributes.put("value",objectTracker.getIdentifier(obj)); |
| 178 | HashMap removeAttributes = new HashMap(); |
| 179 | removeAttributes.put("persistence_txend",currentSerial); |
| 180 | removeAttributes.put("persistence_txendid",transaction.getSerial()); |
| 181 | database.save(transaction,attributeTableName,keyAttributes,removeAttributes); |
| 182 | removeTables.add(attributeTableName); |
| 183 | // Notify listeners |
| 184 | events.add(new RemovedItemEvent(parent,parentAttributeName,obj)); |
| 185 | } |
| 186 | // Add added items |
| 187 | Iterator addedItemsIterator = addedItems.iterator(); |
| 188 | while ( addedItemsIterator.hasNext() ) |
| 189 | { |
| 190 | ObjectWrapper wrapper = (ObjectWrapper) addedItemsIterator.next(); |
| 191 | Object obj = wrapper.getObject(); |
| 192 | // Item does not exist then put it in the save list |
| 193 | if ( ! objectTracker.exists(obj) ) |
| 194 | waitingObjects.add(objectTracker.getWrapper(obj)); |
| 195 | // Add item |
| 196 | HashMap itemAttributes = new HashMap(); |
| 197 | itemAttributes.put("persistence_id",objectTracker.getIdentifier(parent)); |
| 198 | itemAttributes.put("persistence_start",Serial.getMaxSerial().getValue()); |
| 199 | itemAttributes.put("persistence_end",Serial.getMaxSerial().getValue()); |
| 200 | itemAttributes.put("persistence_txendid",new Long(0)); |
| 201 | itemAttributes.put("persistence_txstartid",transaction.getSerial()); |
| 202 | itemAttributes.put("persistence_txstart",currentSerial); |
| 203 | itemAttributes.put("persistence_txend",Serial.getMaxSerial().getValue()); |
| 204 | itemAttributes.put("value",objectTracker.getIdentifier(obj)); |
| 205 | database.insert(transaction, attributeTableName, itemAttributes); |
| 206 | saveTables.add(attributeTableName); |
| 207 | // Notify listeners |
| 208 | logger.debug("adding item event to attribute: "+parentAttributeName+", obj: "+obj); |
| 209 | events.add(new AddedItemEvent(parent,parentAttributeName,obj)); |
| 210 | } |
| 211 | // Reload the changed list. Note, that the list should not |
| 212 | // be referenced until the Store.save() operation completes, because |
| 213 | // the list will not contain nonexisting object currently. |
| 214 | originalTimeControl = new TimeControl(currentSerial,transaction.getSerial(),true); |
| 215 | lastSerial = currentSerial; |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * Get the serial number of last modification. |
| 220 | */ |
| 221 | public Long getLastSerial() |
| 222 | { |
| 223 | return lastSerial; |
| 224 | } |
| 225 | |
| 226 | public boolean retainAll(Object c) |
| 227 | { |
| 228 | return retainAll( (Collection) c ); |
| 229 | } |
| 230 | |
| 231 | public boolean addAll(Object c) |
| 232 | { |
| 233 | return addAll( (Collection) c ); |
| 234 | } |
| 235 | |
| 236 | /* |
| 237 | * Implementing Set |
| 238 | */ |
| 239 | |
| 240 | public boolean add(Object item) |
| 241 | { |
| 242 | // Check item validity |
| 243 | if ( item == null ) |
| 244 | throw new IllegalArgumentException("set does not accept null values."); |
| 245 | ClassTracker.ClassType type = classTracker.getType(item.getClass()); |
| 246 | if ( (type != ClassTracker.ClassType.TYPE_OBJECT) && (type != ClassTracker.ClassType.TYPE_PRIMITIVE) ) |
| 247 | throw new IllegalArgumentException("set only handles object or primitive types, but was: "+item+" ("+item.getClass().getName()+")"); |
| 248 | // Ensure item exists |
| 249 | if ( ! contains(item) ) |
| 250 | { |
| 251 | // Object does not exist. If it does not exist because it is |
| 252 | // in the remove list, then simply remove from remove list. |
| 253 | ObjectWrapper wrapper = new ObjectWrapper(item); |
| 254 | if ( removedItems.contains(wrapper) ) |
| 255 | { |
| 256 | removedItems.remove(wrapper); |
| 257 | } else { |
| 258 | itemClass.updateItemClassName(originalList,item.getClass(),addedItems.size()==0); |
| 259 | addedItems.add(wrapper); |
| 260 | } |
| 261 | modCount++; |
| 262 | return true; |
| 263 | } |
| 264 | return false; |
| 265 | } |
| 266 | |
| 267 | public void clear() |
| 268 | { |
| 269 | // Clear content and mark cleared flag |
| 270 | cleared = true; |
| 271 | addedItems = new HashSet(); |
| 272 | removedItems = new HashSet(); |
| 273 | originalList = new ArrayList(); |
| 274 | itemClass.clear(); |
| 275 | modCount++; |
| 276 | } |
| 277 | |
| 278 | public boolean contains(Object item) |
| 279 | { |
| 280 | if ( item == null ) |
| 281 | return false; |
| 282 | ClassTracker.ClassType type = classTracker.getType(item.getClass()); |
| 283 | ObjectWrapper wrapper = new ObjectWrapper(item); |
| 284 | // If the item is removed, then it is not contained. |
| 285 | if ( removedItems.contains(wrapper) ) |
| 286 | return false; |
| 287 | // If it is added, then it is contained. |
| 288 | if ( addedItems.contains(wrapper) ) |
| 289 | return true; |
| 290 | // Else, check the list |
| 291 | if ( (originalList instanceof LazyList) && (!((LazyList) originalList).isIterationCheap()) ) |
| 292 | { |
| 293 | // This means, that the backing lazy list would page if we |
| 294 | // were to iterate. So instead, we run a specific query for |
| 295 | // the given id. |
| 296 | Transaction tx = transactionTracker.getTransaction(TransactionTracker.TX_REQUIRED); |
| 297 | tx.begin(); |
| 298 | try |
| 299 | { |
| 300 | ClassInfo itemInfo = classTracker.getClassInfo(item.getClass(),item); |
| 301 | String itemTableName = schemaManager.getTableName(itemInfo.getSourceEntry()); |
| 302 | TableTerm itemTableTerm = new TableTerm(itemTableName,null); |
| 303 | String listTableName = schemaManager.getTableName( |
| 304 | parentInfo.getAttributeClassEntry(parentAttributeName),parentAttributeName); |
| 305 | TableTerm listTableTerm = new TableTerm(listTableName,null); |
| 306 | Expression listExpression = new Expression(); |
| 307 | listExpression.add(new ReferenceTerm(listTableTerm,"persistence_id")); |
| 308 | listExpression.add("="); |
| 309 | listExpression.add(new ConstantTerm(objectTracker.getIdentifier(parent))); |
| 310 | listExpression.add("and"); |
| 311 | if ( type != ClassTracker.ClassType.TYPE_PRIMITIVE ) |
| 312 | { |
| 313 | listExpression.add(new ReferenceTerm(listTableTerm,"value")); |
| 314 | listExpression.add("="); |
| 315 | listExpression.add(new ConstantTerm(wrapper.getIdentifier())); |
| 316 | } else { |
| 317 | listExpression.add(new ReferenceTerm(itemTableTerm,"value")); |
| 318 | listExpression.add("="); |
| 319 | listExpression.add(new ConstantTerm(item)); |
| 320 | } |
| 321 | listExpression.add("and"); |
| 322 | listExpression.add(new ReferenceTerm(itemTableTerm,"persistence_id")); |
| 323 | listExpression.add("="); |
| 324 | listExpression.add(new ReferenceTerm(listTableTerm,"value")); |
| 325 | listExpression.add("and"); |
| 326 | originalTimeControl.apply(listExpression,itemTableTerm); |
| 327 | listExpression.add("and"); |
| 328 | originalTimeControl.apply(listExpression,listTableTerm); |
| 329 | // Execute. If there is a hit, then object exists |
| 330 | QueryStatement stmt = new QueryStatement(listTableTerm,listExpression,null); |
| 331 | stmt.getSpecifiedTerms().add(new SpecifiedTableTerm(itemTableTerm)); |
| 332 | stmt.setTimeControl(originalTimeControl); |
| 333 | stmt.setStaticRepresentation("FIND "+listTableTerm+" WHERE persistence_id = "+ |
| 334 | objectTracker.getIdentifier(parent)+" and value = "+wrapper.getIdentifier()); |
| 335 | SearchResult result = queryService.find(stmt,new Limits(0,0,-1)); |
| 336 | // Check |
| 337 | if ( result.getResultSize() > 0 ) |
| 338 | return true; // Object exists |
| 339 | } finally { |
| 340 | tx.commit(); |
| 341 | } |
| 342 | } else { |
| 343 | // Set is small, so iterate |
| 344 | for ( int i=0; i<originalList.size(); i++ ) |
| 345 | { |
| 346 | Object obj = originalList.get(i); |
| 347 | if ( ((type==ClassTracker.ClassType.TYPE_PRIMITIVE) && (item.equals(obj))) || |
| 348 | ((type!=ClassTracker.ClassType.TYPE_PRIMITIVE) && (objectTracker.getIdentifier(obj).equals(wrapper.getIdentifier()) )) ) |
| 349 | return true; |
| 350 | } |
| 351 | } |
| 352 | // Fall through |
| 353 | return false; |
| 354 | } |
| 355 | |
| 356 | /** |
| 357 | * This hash code invokes the parent, which is ok becaue the equals method |
| 358 | * does the same thing as the superclass', just more efficiently. |
| 359 | */ |
| 360 | public int hashCode() |
| 361 | { |
| 362 | return super.hashCode(); |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Determine whether list equals another list in content. |
| 367 | */ |
| 368 | public boolean equals(Object obj) |
| 369 | { |
| 370 | // If it is not a collection, then it surely does not equal. |
| 371 | if ( ! (obj instanceof Collection) ) |
| 372 | return false; |
| 373 | // If they are the same size, and all items equal, then the |
| 374 | // collections equal. |
| 375 | Collection c = (Collection) obj; |
| 376 | return (size()==c.size()) && (containsAll(c)); |
| 377 | } |
| 378 | |
| 379 | /** |
| 380 | * Get iterator. |
| 381 | */ |
| 382 | public Iterator iterator() |
| 383 | { |
| 384 | return new SetImplIteratorImpl(); |
| 385 | } |
| 386 | |
| 387 | /** |
| 388 | * Remove object from set. |
| 389 | */ |
| 390 | public boolean remove(Object item) |
| 391 | { |
| 392 | // Ensure item exists |
| 393 | if ( contains(item) ) |
| 394 | { |
| 395 | // Object does exist. If it does exist because it is |
| 396 | // in the added list, then simply remove from added list. |
| 397 | ObjectWrapper wrapper = new ObjectWrapper(item); |
| 398 | if ( addedItems.contains(wrapper) ) |
| 399 | addedItems.remove(wrapper); |
| 400 | else |
| 401 | removedItems.add(wrapper); |
| 402 | modCount++; |
| 403 | return true; |
| 404 | } |
| 405 | return false; |
| 406 | } |
| 407 | |
| 408 | public int size() |
| 409 | { |
| 410 | return originalList.size() - removedItems.size() + addedItems.size(); |
| 411 | } |
| 412 | |
| 413 | public String toString() |
| 414 | { |
| 415 | return originalList.toString(); |
| 416 | } |
| 417 | |
| 418 | public class SetImplIteratorImpl implements Iterator |
| 419 | { |
| 420 | private int ownModCount; |
| 421 | private int index; |
| 422 | private boolean hasNext; |
| 423 | private Object next; |
| 424 | private Object current; |
| 425 | private Iterator addedIterator; |
| 426 | |
| 427 | public SetImplIteratorImpl() |
| 428 | { |
| 429 | index = 0; |
| 430 | ownModCount=modCount; |
| 431 | addedIterator = addedItems.iterator(); |
| 432 | // preread |
| 433 | read(); |
| 434 | } |
| 435 | |
| 436 | private void read() |
| 437 | { |
| 438 | // Ensure that no modification took place |
| 439 | if ( ownModCount != modCount ) |
| 440 | throw new java.util.ConcurrentModificationException("set was modified while iterating"); |
| 441 | // Check whether there are elements left in the list |
| 442 | while ( index<originalList.size() ) |
| 443 | { |
| 444 | Object obj = originalList.get(index); |
| 445 | index++; // Next |
| 446 | ObjectWrapper wrapper = new ObjectWrapper(obj); |
| 447 | if ( ! removedItems.contains(wrapper) ) |
| 448 | { |
| 449 | // This is a valid item |
| 450 | hasNext = true; |
| 451 | next = obj; |
| 452 | return; |
| 453 | } |
| 454 | } |
| 455 | // If there were no elements in the original list, check through |
| 456 | // the added items. |
| 457 | if ( addedIterator.hasNext() ) |
| 458 | { |
| 459 | hasNext = true; |
| 460 | next = ((ObjectWrapper) addedIterator.next()).getObject(); |
| 461 | return; |
| 462 | } |
| 463 | // Fall through |
| 464 | hasNext = false; |
| 465 | next = null; |
| 466 | } |
| 467 | |
| 468 | public void remove() |
| 469 | { |
| 470 | // Remove the current item |
| 471 | if ( index <= originalList.size() ) |
| 472 | { |
| 473 | // The current item is in the original list, not in the |
| 474 | // added list, insert into the removed list. |
| 475 | removedItems.add(new ObjectWrapper(current)); |
| 476 | } else { |
| 477 | // The current item is in the added list, so remove from it. |
| 478 | addedIterator.remove(); |
| 479 | // Modify the modcount, because the whole set changed |
| 480 | } |
| 481 | modCount++; |
| 482 | ownModCount = modCount; // The modcount changed, but we're safe |
| 483 | } |
| 484 | |
| 485 | public boolean hasNext() |
| 486 | { |
| 487 | return hasNext; |
| 488 | } |
| 489 | |
| 490 | public Object next() |
| 491 | { |
| 492 | current = next; |
| 493 | read(); // Pre-read next |
| 494 | return current; |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | public class ObjectWrapper |
| 499 | { |
| 500 | private Object obj; |
| 501 | private Long id; |
| 502 | private ClassTracker.ClassType type; |
| 503 | |
| 504 | public ObjectWrapper(Object obj) |
| 505 | { |
| 506 | this.obj=obj; |
| 507 | objectTracker.registerObject(obj); |
| 508 | this.id=objectTracker.getIdentifier(obj); |
| 509 | this.type=classTracker.getType(obj.getClass()); |
| 510 | } |
| 511 | |
| 512 | public Long getIdentifier() |
| 513 | { |
| 514 | return id; |
| 515 | } |
| 516 | |
| 517 | public Object getObject() |
| 518 | { |
| 519 | return obj; |
| 520 | } |
| 521 | |
| 522 | public int hashCode() |
| 523 | { |
| 524 | if ( type == ClassTracker.ClassType.TYPE_PRIMITIVE ) |
| 525 | return obj.hashCode(); |
| 526 | else |
| 527 | return (int) (id.longValue()>>INT_BITS); |
| 528 | } |
| 529 | |
| 530 | public boolean equals(Object rhs) |
| 531 | { |
| 532 | if ( ! (rhs instanceof ObjectWrapper) ) |
| 533 | return false; |
| 534 | if ( type == ClassTracker.ClassType.TYPE_PRIMITIVE ) |
| 535 | return obj.equals( ((ObjectWrapper)rhs).obj ); |
| 536 | else |
| 537 | return id.equals(((ObjectWrapper) rhs).id); |
| 538 | } |
| 539 | |
| 540 | } |
| 541 | } |
| 542 | |