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

com.ghunteranderson.nexus.client.PaginationIterator Maven / Gradle / Ivy

The newest version!
package com.ghunteranderson.nexus.client;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterators;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class PaginationIterator  implements Iterator{

	private Iterator buffer;
	private String token;
	private final Function> source;
	
	public PaginationIterator(Function> source) {
		this.source = source;
	}
	
	
	@Override
	public boolean hasNext() {
		if(buffer == null || !buffer.hasNext())
			loadNext();
		return buffer.hasNext();
	}
	@Override
	public E next() {
		if(hasNext())
			return buffer.next();
		else
			throw new NoSuchElementException();
	}
	
	private void loadNext() {
		if(buffer != null && token == null)
			return;
		
		PaginatedResponse next = source.apply(token);
		token = next.getContinuationToken();
		buffer = next.getItems().iterator();
	}
	
	public Stream stream(){
		return StreamSupport.stream(Spliterators.spliteratorUnknownSize(this, 0), false);
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy