All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.buschmais.xo.impl.transaction.TransactionalResultIterator Maven / Gradle / Ivy

The newest version!
package com.buschmais.xo.impl.transaction;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.buschmais.xo.api.ResultIterator;
import com.buschmais.xo.api.XOTransaction;

public class TransactionalResultIterator implements ResultIterator, XOTransaction.Synchronization {

    private ResultIterator delegateIterator;
    private XOTransaction xoTransaction;

    public TransactionalResultIterator(ResultIterator delegateIterator, XOTransaction xoTransaction) {
        this.xoTransaction = xoTransaction;
        this.delegateIterator = delegateIterator;
        if (isTransactional()) {
            xoTransaction.registerSynchronization(this);
        }
    }

    @Override
    public void close() {
        unregisterSynchronization();
        delegateIterator.close();
    }

    @Override
    public boolean hasNext() {
        boolean hasNext = delegateIterator.hasNext();
        if (!hasNext) {
            unregisterSynchronization();
        }
        return hasNext;
    }

    @Override
    public E next() {
        return delegateIterator.next();
    }

    @Override
    public void remove() {
        delegateIterator.remove();
    }

    @Override
    public void beforeCompletion() {
        final List detachedList = new ArrayList<>();
        while (delegateIterator.hasNext()) {
            detachedList.add(delegateIterator.next());
        }
        final Iterator iterator = detachedList.iterator();
        this.delegateIterator = new ResultIterator() {
            @Override
            public void close() {
                // forced by interface
            }

            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public E next() {
                return iterator.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Remove is not supported for this iterator.");
            }
        };
    }

    @Override
    public void afterCompletion(boolean committed) {
        // nothing to do
    }

    private void unregisterSynchronization() {
        if (isTransactional()) {
            this.xoTransaction.unregisterSynchronization(this);
            this.xoTransaction = null;
        }
    }

    private boolean isTransactional() {
        return this.xoTransaction != null && this.xoTransaction.isActive();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy