001/************************************************************************ 002 * Licensed under Public Domain (CC0) * 003 * * 004 * To the extent possible under law, the person who associated CC0 with * 005 * this code has waived all copyright and related or neighboring * 006 * rights to this code. * 007 * * 008 * You should have received a copy of the CC0 legalcode along with this * 009 * work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.* 010 ************************************************************************/ 011 012package org.reactivestreams.tck.support; 013 014import java.util.Collections; 015import java.util.Iterator; 016import java.util.concurrent.Executor; 017import org.reactivestreams.Subscription; 018import org.reactivestreams.Subscriber; 019import org.reactivestreams.Publisher; 020import org.reactivestreams.example.unicast.AsyncIterablePublisher; 021 022public class HelperPublisher<T> extends AsyncIterablePublisher<T> { 023 024 public HelperPublisher(final int from, final int to, final Function<Integer, T> create, final Executor executor) { 025 super(new Iterable<T>() { 026 { if(from > to) throw new IllegalArgumentException("from must be equal or greater than to!"); } 027 @Override public Iterator<T> iterator() { 028 return new Iterator<T>() { 029 private int at = from; 030 @Override public boolean hasNext() { return at < to; } 031 @Override public T next() { 032 if (!hasNext()) return Collections.<T>emptyList().iterator().next(); 033 else try { 034 return create.apply(at++); 035 } catch (Throwable t) { 036 throw new IllegalStateException(String.format("Failed to create element for id %d!", at - 1), t); 037 } 038 } 039 @Override public void remove() { throw new UnsupportedOperationException(); } 040 }; 041 } 042 }, executor); 043 } 044}