View Javadoc
1   package de.fhdw.wtf.context.model.collections;
2   
3   import java.util.Iterator;
4   
5   import de.fhdw.wtf.context.core.ObjectFactoryProvider;
6   import de.fhdw.wtf.context.core.TransactionManager;
7   import de.fhdw.wtf.context.model.Anything;
8   import de.fhdw.wtf.persistence.meta.Object;
9   import de.fhdw.wtf.persistence.meta.UnidirectionalLink;
10  import de.fhdw.wtf.persistence.utils.Tuple;
11  
12  /**
13   * This class provides an Iterator for Persistant* with Links(Unidirectional).
14   * 
15   * @param <T>
16   *            The underlying element type.
17   */
18  public class PersistenceIteratorWithLink<T extends Anything> implements Iterator<T> {
19  	
20  	/**
21  	 * An iterator over the underlying links.
22  	 */
23  	private final Iterator<Tuple<UnidirectionalLink, Object>> unidirectionalLinkIterator;
24  	
25  	/**
26  	 * The element read last through the iterator.
27  	 */
28  	private UnidirectionalLink lastRead;
29  	
30  	/**
31  	 * True if at least one element has been read through the iterator.
32  	 */
33  	private boolean hasLast;
34  	
35  	/**
36  	 * Creates a PersistenceIteratorWithLink.
37  	 * 
38  	 * @param unidirectionalLinks
39  	 *            A collection of the underlying links.
40  	 */
41  	public PersistenceIteratorWithLink(final java.util.Collection<Tuple<UnidirectionalLink, Object>> unidirectionalLinks) {
42  		this.unidirectionalLinkIterator = unidirectionalLinks.iterator();
43  	}
44  	
45  	@Override
46  	public boolean hasNext() {
47  		return this.unidirectionalLinkIterator.hasNext();
48  	}
49  	
50  	@Override
51  	public T next() {
52  		this.lastRead = this.unidirectionalLinkIterator.next().getFirst();
53  		this.hasLast = true;
54  		return this.provideNewInstanceForType(this.lastRead.getTarget());
55  		
56  	}
57  	
58  	@Override
59  	public void remove() {
60  		if (this.hasLast) {
61  			TransactionManager.getContext().unset(this.lastRead);
62  		}
63  		this.unidirectionalLinkIterator.remove();
64  	}
65  	
66  	/**
67  	 * Instantiates the Java object for the underlying database object.
68  	 * 
69  	 * @param object
70  	 *            The database object.
71  	 * @return The corresponding Java object.
72  	 */
73  	@SuppressWarnings("unchecked")
74  	private T provideNewInstanceForType(final Object object) {
75  		return (T) ObjectFactoryProvider.instance().createObject(object);
76  	}
77  	
78  }