io.contek.zeus.client.grpc.GrpcIterator Maven / Gradle / Ivy
package io.contek.zeus.client.grpc;
import io.contek.zeus.client.ICloseableIterator;
import io.grpc.Context;
import io.grpc.StatusRuntimeException;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import static io.grpc.Context.CancellableContext;
@NotThreadSafe
public final class GrpcIterator implements ICloseableIterator {
private final Iterator iterator;
private final CancellableContext cancellableContext;
public static GrpcIterator fromCallable(Callable> callable) {
CancellableContext cancellableContext = Context.current().withCancellation();
Iterator streamingIterator;
try {
streamingIterator = cancellableContext.call(callable);
} catch (Throwable t) {
streamingIterator = Collections.emptyIterator();
}
return new GrpcIterator<>(streamingIterator, cancellableContext);
}
@Override
public boolean hasNext() {
try {
return iterator.hasNext();
} catch (StatusRuntimeException e) {
return false;
}
}
@Override
public T next() {
try {
return iterator.next();
} catch (StatusRuntimeException e) {
throw new NoSuchElementException(e.getStatus().toString());
}
}
@Override
public void close() {
cancellableContext.close();
}
private GrpcIterator(Iterator iterator, Context.CancellableContext context) {
this.iterator = iterator;
this.cancellableContext = context;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy