Search in sources :

Example 76 with Subscriber

use of org.reactivestreams.Subscriber in project reactive-streams-jvm by reactive-streams.

the class PublisherVerificationTest method multiSubscribersPublisherVerification.

/**
 * Verification using a Publisher that supports multiple subscribers
 * @param shouldBlowUp if true {@link RuntimeException} will be thrown during second subscription.
 */
final PublisherVerification<Integer> multiSubscribersPublisherVerification(final boolean shouldBlowUp) {
    return new PublisherVerification<Integer>(newTestEnvironment()) {

        @Override
        public Publisher<Integer> createPublisher(final long elements) {
            return new Publisher<Integer>() {

                private final Collection<CancelableSubscription> subscriptions = new CopyOnWriteArrayList<CancelableSubscription>();

                private final AtomicLong source = new AtomicLong(elements);

                @Override
                public void subscribe(Subscriber<? super Integer> s) {
                    // onSubscribe first
                    CancelableSubscription subscription = new CancelableSubscription(s);
                    s.onSubscribe(subscription);
                    if (shouldBlowUp && !subscriptions.isEmpty()) {
                        s.onError(new RuntimeException("Unexpected additional subscriber"));
                    } else {
                        subscriptions.add(subscription);
                    }
                }

                class CancelableSubscription implements Subscription {

                    final AtomicBoolean canceled = new AtomicBoolean();

                    Subscriber<? super Integer> subscriber;

                    CancelableSubscription(Subscriber<? super Integer> subscriber) {
                        this.subscriber = subscriber;
                    }

                    @Override
                    public void request(long n) {
                        if (!canceled.get()) {
                            for (long i = 0; i < n; i++) {
                                if (source.getAndDecrement() < 0) {
                                    canceled.set(true);
                                    subscriber.onComplete();
                                } else {
                                    subscriber.onNext((int) i);
                                }
                            }
                        }
                    }

                    @Override
                    public void cancel() {
                        canceled.set(true);
                        subscriber = null;
                        subscriptions.remove(this);
                    }
                }
            };
        }

        @Override
        public Publisher<Integer> createFailedPublisher() {
            return SKIP;
        }
    };
}
Also used : Publisher(org.reactivestreams.Publisher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Subscriber(org.reactivestreams.Subscriber) Collection(java.util.Collection)

Example 77 with Subscriber

use of org.reactivestreams.Subscriber in project jOOQ by jOOQ.

the class R2DBC method block.

@SuppressWarnings("unchecked")
static final <T> T block(Publisher<? extends T> publisher) {
    Object complete = new Object();
    LinkedBlockingQueue<Object> queue = new LinkedBlockingQueue<>();
    publisher.subscribe(subscriber(s -> s.request(1), queue::add, queue::add, () -> queue.add(complete)));
    try {
        Object result = queue.take();
        if (result instanceof Throwable)
            throw new DataAccessException("Exception when blocking on publisher", (Throwable) result);
        else if (result == complete)
            return null;
        else
            return (T) result;
    } catch (InterruptedException e) {
        throw new DataAccessException("Exception when blocking on publisher", e);
    }
}
Also used : Time(java.sql.Time) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) BiFunction(java.util.function.BiFunction) Batch(io.r2dbc.spi.Batch) ByteBuffer(java.nio.ByteBuffer) Array(java.sql.Array) BigDecimal(java.math.BigDecimal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultResultSet(org.jooq.tools.jdbc.DefaultResultSet) LocalTime(java.time.LocalTime) SQLType(java.sql.SQLType) Result(io.r2dbc.spi.Result) DataTypeException(org.jooq.exception.DataTypeException) SQLDialect(org.jooq.SQLDialect) DataType(org.jooq.DataType) JooqLogger(org.jooq.tools.JooqLogger) JDBCUtils.safeClose(org.jooq.tools.jdbc.JDBCUtils.safeClose) Timestamp(java.sql.Timestamp) Builder(io.r2dbc.spi.ConnectionFactoryOptions.Builder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Field(org.jooq.Field) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Cursor(org.jooq.Cursor) Option(io.r2dbc.spi.Option) Connection(io.r2dbc.spi.Connection) LocalDate(java.time.LocalDate) StringUtils.defaultIfNull(org.jooq.tools.StringUtils.defaultIfNull) Query(org.jooq.Query) Internal.subscriber(org.jooq.impl.Internal.subscriber) Guard(org.jooq.impl.ThreadGuard.Guard) ResultSetMetaData(java.sql.ResultSetMetaData) Types(java.sql.Types) DefaultPreparedStatement(org.jooq.tools.jdbc.DefaultPreparedStatement) ConnectionFactories(io.r2dbc.spi.ConnectionFactories) Row(io.r2dbc.spi.Row) XML(org.jooq.XML) ConnectionFactoryOptions(io.r2dbc.spi.ConnectionFactoryOptions) Tools.visitAll(org.jooq.impl.Tools.visitAll) LocalDateTime(java.time.LocalDateTime) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Tools.recordFactory(org.jooq.impl.Tools.recordFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) BindingGetResultSetContext(org.jooq.BindingGetResultSetContext) ConcurrentMap(java.util.concurrent.ConcurrentMap) RowMetadata(io.r2dbc.spi.RowMetadata) SQLException(java.sql.SQLException) ColumnMetadata(io.r2dbc.spi.ColumnMetadata) EMPTY_PARAM(org.jooq.impl.Tools.EMPTY_PARAM) Tools.abstractDMLQuery(org.jooq.impl.Tools.abstractDMLQuery) Subscriber(org.reactivestreams.Subscriber) MockArray(org.jooq.tools.jdbc.MockArray) Record(org.jooq.Record) DataAccessException(org.jooq.exception.DataAccessException) Properties(java.util.Properties) Tools.translate(org.jooq.impl.Tools.translate) SettingsTools(org.jooq.conf.SettingsTools) Publisher(org.reactivestreams.Publisher) JSON(org.jooq.JSON) Settings(org.jooq.conf.Settings) Tools.abstractResultQuery(org.jooq.impl.Tools.abstractResultQuery) Converter(org.jooq.Converter) Date(java.sql.Date) Consumer(java.util.function.Consumer) Param(org.jooq.Param) AtomicLong(java.util.concurrent.atomic.AtomicLong) Configuration(org.jooq.Configuration) NAMED(org.jooq.conf.ParamType.NAMED) Tools.fields(org.jooq.impl.Tools.fields) Rendered(org.jooq.impl.DefaultRenderContext.Rendered) Subscription(org.reactivestreams.Subscription) JSONB(org.jooq.JSONB) Statement(io.r2dbc.spi.Statement) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) DataAccessException(org.jooq.exception.DataAccessException)

Example 78 with Subscriber

use of org.reactivestreams.Subscriber in project aws-doc-sdk-examples by awsdocs.

the class KinesisStreamEx method main.

public static void main(String[] args) {
    // snippet-start:[kinesis.java2.stream_example.setup]
    Region region = Region.US_EAST_1;
    KinesisAsyncClient client = KinesisAsyncClient.builder().region(region).build();
    SubscribeToShardRequest request = SubscribeToShardRequest.builder().consumerARN(CONSUMER_ARN).shardId("arn:aws:kinesis:us-east-1:111122223333:stream/StockTradeStream").startingPosition(s -> s.type(ShardIteratorType.LATEST)).build();
    // snippet-end:[kinesis.java2.stream_example.setup]
    SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler.builder().onError(t -> System.err.println("Error during stream - " + t.getMessage())).subscriber(MySubscriber::new).build();
    client.subscribeToShard(request, responseHandler);
    client.close();
}
Also used : KinesisAsyncClient(software.amazon.awssdk.services.kinesis.KinesisAsyncClient) ShardIteratorType(software.amazon.awssdk.services.kinesis.model.ShardIteratorType) SubscribeToShardResponseHandler(software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler) SubscribeToShardEventStream(software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream) CompletableFuture(java.util.concurrent.CompletableFuture) SdkPublisher(software.amazon.awssdk.core.async.SdkPublisher) SubscribeToShardRequest(software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest) SubscribeToShardResponse(software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Subscription(org.reactivestreams.Subscription) Region(software.amazon.awssdk.regions.Region) SubscribeToShardEvent(software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent) Subscriber(org.reactivestreams.Subscriber) SubscribeToShardResponseHandler(software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler) KinesisAsyncClient(software.amazon.awssdk.services.kinesis.KinesisAsyncClient) SubscribeToShardRequest(software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest) Region(software.amazon.awssdk.regions.Region)

Example 79 with Subscriber

use of org.reactivestreams.Subscriber in project aws-doc-sdk-examples by awsdocs.

the class KinesisStreamEx method responseHandlerBuilderVisitorBuilder.

// snippet-end:[kinesis.java2.stream_example.publish_transformer]
/**
 * Creates a SubscribeToShardResponseHandler.Visitor using the builder which lets you register an event handler for
 * all events you're interested in rather than implementing the interface.
 */
// snippet-start:[kinesis.java2.stream_example.visitor]
private static CompletableFuture<Void> responseHandlerBuilderVisitorBuilder(KinesisAsyncClient client, SubscribeToShardRequest request) {
    SubscribeToShardResponseHandler.Visitor visitor = SubscribeToShardResponseHandler.Visitor.builder().onSubscribeToShardEvent(e -> System.out.println("Received subscribe to shard event " + e)).build();
    SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler.builder().onError(t -> System.err.println("Error during stream - " + t.getMessage())).subscriber(visitor).build();
    return client.subscribeToShard(request, responseHandler);
}
Also used : SubscribeToShardResponseHandler(software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler) KinesisAsyncClient(software.amazon.awssdk.services.kinesis.KinesisAsyncClient) ShardIteratorType(software.amazon.awssdk.services.kinesis.model.ShardIteratorType) SubscribeToShardResponseHandler(software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler) SubscribeToShardEventStream(software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream) CompletableFuture(java.util.concurrent.CompletableFuture) SdkPublisher(software.amazon.awssdk.core.async.SdkPublisher) SubscribeToShardRequest(software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest) SubscribeToShardResponse(software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Subscription(org.reactivestreams.Subscription) Region(software.amazon.awssdk.regions.Region) SubscribeToShardEvent(software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent) Subscriber(org.reactivestreams.Subscriber)

Example 80 with Subscriber

use of org.reactivestreams.Subscriber in project quasar by puniverse.

the class TestHelper method createDummyFailedPublisher.

public static <T> Publisher<T> createDummyFailedPublisher() {
    return new Publisher<T>() {

        @Override
        public void subscribe(Subscriber<? super T> s) {
            s.onSubscribe(new Subscription() {

                @Override
                public void request(long n) {
                }

                @Override
                public void cancel() {
                }
            });
            s.onError(new RuntimeException("Can't subscribe subscriber: " + s + ", because of reasons."));
        }
    };
}
Also used : Subscriber(org.reactivestreams.Subscriber) Publisher(org.reactivestreams.Publisher) Subscription(org.reactivestreams.Subscription)

Aggregations

Subscriber (org.reactivestreams.Subscriber)92 Subscription (org.reactivestreams.Subscription)56 Test (org.junit.Test)49 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)24 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 ProtonClient (io.vertx.proton.ProtonClient)22 ProtonConnection (io.vertx.proton.ProtonConnection)22 Message (org.apache.qpid.proton.message.Message)20 List (java.util.List)18 AmqpValue (org.apache.qpid.proton.amqp.messaging.AmqpValue)18 AtomicReference (java.util.concurrent.atomic.AtomicReference)17 Handler (io.vertx.core.Handler)16 Logger (io.vertx.core.impl.logging.Logger)16 LoggerFactory (io.vertx.core.impl.logging.LoggerFactory)16 ProtonStreams (io.vertx.proton.streams.ProtonStreams)16 ExecutionException (java.util.concurrent.ExecutionException)16 Symbol (org.apache.qpid.proton.amqp.Symbol)16 Section (org.apache.qpid.proton.amqp.messaging.Section)16 ArrayList (java.util.ArrayList)14 Collections (java.util.Collections)13