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

com.greenback.kit.util.StreamingPaginated Maven / Gradle / Ivy

There is a newer version: 1.0.39
Show newest version
package com.greenback.kit.util;

import com.greenback.kit.model.Paginated;
import com.greenback.kit.util.IoFunction;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Iterator;
import static java.util.Optional.ofNullable;
import java.util.concurrent.atomic.AtomicReference;

public class StreamingPaginated extends Paginated {

    private IoFunction,Paginated> nextMethod;

    public IoFunction,Paginated> nextMethod() {
        return this.nextMethod;
    }

    public void nextMethod(IoFunction,Paginated> nextMethod) {
        this.nextMethod = nextMethod;
    }

    @Override
    public Iterator iterator() {
        final AtomicReference> responseRef = new AtomicReference<>(this);
        final AtomicReference> iterRef = new AtomicReference<>(ofNullable(this.getValues())
            .map(v -> v.iterator())
            .orElse(null));
        
        return new Iterator() {
            @Override
            public boolean hasNext() {
                final Iterator iter = iterRef.get();
                
                if (iter == null || !iter.hasNext()) {
                    if (!responseRef.get().hasNext()) {
                        return false;
                    }
                    
                    try {
                        Paginated nextPage = ((StreamingPaginated)responseRef.get())
                            .nextMethod()
                            .apply(responseRef.get());

                        responseRef.set(nextPage);
                        
                        Iterator nextPageIterator = ofNullable(nextPage)
                            .map(v -> v.getValues())
                            .map(v -> v.iterator())
                            .orElse(null);
                        
                        iterRef.set(nextPageIterator);

                        if (iterRef.get() == null) {
                            return false;   // done
                        }

                        return iterRef.get().hasNext();
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
                
                return true;
            }

            @Override
            public T next() {
                return iterRef.get().next();
            }
        };
    }
    
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy