001package systems.dmx.storage.neo4j;
002
003import systems.dmx.core.model.AssociationModel;
004import systems.dmx.core.model.DMXObjectModel;
005import systems.dmx.core.model.TopicModel;
006
007import org.neo4j.graphdb.Node;
008import org.neo4j.tooling.GlobalGraphOperations;
009
010import java.util.Iterator;
011import java.util.NoSuchElementException;
012
013
014
015class TopicModelIterator extends ModelIterator<TopicModel> {
016
017    TopicModelIterator(Neo4jStorage storage) {
018        super(storage, NodeType.TOPIC);
019    }
020
021    @Override
022    TopicModel buildModel(Node node) {
023        return storage.buildTopic(node);
024    }
025}
026
027
028
029class AssociationModelIterator extends ModelIterator<AssociationModel> {
030
031    AssociationModelIterator(Neo4jStorage storage) {
032        super(storage, NodeType.ASSOC);
033    }
034
035    @Override
036    AssociationModel buildModel(Node node) {
037        return storage.buildAssociation(node);
038    }
039}
040
041
042
043abstract class ModelIterator<E extends DMXObjectModel> implements Iterator<E> {
044
045    // ---------------------------------------------------------------------------------------------- Instance Variables
046
047    protected Neo4jStorage storage;
048
049    private NodeType nodeType;
050    private Iterator<Node> nodes;
051    private Node nextNode;
052
053    // ---------------------------------------------------------------------------------------------------- Constructors
054
055    ModelIterator(Neo4jStorage storage, NodeType nodeType) {
056        this.storage = storage;
057        this.nodeType = nodeType;
058        this.nodes = GlobalGraphOperations.at(storage.neo4j).getAllNodes().iterator();
059    }
060
061    // -------------------------------------------------------------------------------------------------- Public Methods
062
063    @Override
064    public boolean hasNext() {
065        nextNode = fetchNextNode();
066        return nextNode != null;
067    }
068
069    @Override
070    public E next() {
071        if (nextNode == null) {
072            throw new NoSuchElementException("there is no next node");
073        }
074        //
075        return buildModel(nextNode);
076    }
077
078    @Override
079    public void remove() {
080        throw new UnsupportedOperationException("removal is not supported");
081    }
082
083    // ----------------------------------------------------------------------------------------- Package Private Methods
084
085    abstract E buildModel(Node node);
086
087    // ------------------------------------------------------------------------------------------------- Private Methods
088
089    private Node fetchNextNode() {
090        while (nodes.hasNext()) {
091            Node node = nodes.next();
092            if (nodeType.isTypeOf(node)) {
093                return node;
094            }
095        }
096        return null;
097    }
098}