When using the new API services, I’ve found a need to iterate over all the results, for example when retrieving all the members of a certain group. So I decided to implement an Iterator (as such, it’s not thread-safe) to iterate over the results. This is much slower than deprecated functions like spaceManager.getAllSpaces(), but seems to be the future for Atlassian Java libraries.
import com.atlassian.confluence.api.model.pagination.PageRequest;
import com.atlassian.confluence.api.model.pagination.PageResponse;
import com.atlassian.confluence.api.model.pagination.SimplePageRequest;
import com.atlassian.confluence.api.service.finder.ManyFetcher;
import java.util.Iterator;
public class ManyFetcherIterator<V> implements Iterator<V> {
private final ManyFetcher<V> manyFetcher;
private PageResponse<V> pageResponse;
private Iterator<V> iterator;
public ManyFetcherIterator(ManyFetcher<V> manyFetcher) {
this.manyFetcher = manyFetcher;
this.pageResponse = manyFetcher.fetchMany(new SimplePageRequest(0, Integer.MAX_VALUE));
this.iterator = pageResponse.iterator();
}
@Override
public boolean hasNext() {
if (!(iterator.hasNext() || pageResponse.getResults().isEmpty())) {
loadNextRequest();
}
return iterator.hasNext();
}
private void loadNextRequest() {
PageRequest pageRequest = pageResponse.getPageRequest();
int start = pageRequest.getStart() + pageRequest.getLimit();
pageResponse = manyFetcher.fetchMany(new SimplePageRequest(start, pageRequest.getLimit()));
iterator = pageResponse.iterator();
}
@Override
public V next() {
return iterator.next();
}
}
And an example of use with com.atlassian.confluence.api.service.content.SpaceService
:
ManyFetcher<Space> manyFetcher = spaceService.find();
ManyFetcherIterator<Space> spaceManyFetcherIterator = new ManyFetcherIterator<>(manyFetcher);
while (spaceManyFetcherIterator.hasNext()) {
Space space = spaceManyFetcherIterator.next();
System.out.println(space.getName());
}
No guarantees are given, but any feedback is welcome