reactor.core.publisher.MonoSink Java Examples

The following examples show how to use reactor.core.publisher.MonoSink. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BoundedElasticSchedulerTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
private ExecutorService startProducer(LinkedList<MonoSink<String>> listeners) {
	ExecutorService producer = Executors.newSingleThreadExecutor();
	afterTest.autoDispose(producer::shutdownNow);

	producer.submit(() -> {
		int i = 0;
		while (true) {
			MonoSink<String> sink = listeners.poll();
			if (sink != null) {
				sink.success(Integer.toString(i++));
			}

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				LOGGER.info("Producer stopping");
				return;
			}
		}
	});

	return producer;
}
 
Example #2
Source File: DefaultAggregationService.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private <T> ActionListener<T> translatorActionListener(MonoSink<T> sink) {
    return new ActionListener<T>() {
        @Override
        public void onResponse(T response) {
            sink.success(response);
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof ElasticsearchException) {
                if (((ElasticsearchException) e).status().getStatus() == 404) {
                    sink.success();
                    return;
                } else if (((ElasticsearchException) e).status().getStatus() == 400) {
                    sink.error(new ElasticsearchParseException("查询参数格式错误", e));
                }
            }
            sink.error(e);
        }
    };
}
 
Example #3
Source File: ChangeActionHolder.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public ChangeActionHolder(Function<DATA, Mono<Function<DATA, DATA>>> action,
                          long transactionId,
                          long createTimestamp,
                          @Nullable MonoSink<DATA> subscriberSink) {
    this.action = action;
    this.transactionId = transactionId;
    this.createTimestamp = createTimestamp;
    this.subscriberSink = subscriberSink;

    if (subscriberSink != null) {
        subscriberSink.onCancel(() -> {
            cancelledRef.set(true);

            Disposable next;
            while ((next = cancelCallbacks.poll()) != null) {
                ReactorExt.safeDispose(next);
            }
        });
    }
}
 
Example #4
Source File: AbstractServiceBaseReactor.java    From rest-example with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the entity having supplied id.
 *
 * @param inEntityId Id of entity to retrieve.
 * @return Mono that will receive the found entity or error if error occurs or no
 * entity with supplied id is found.
 */
@Transactional(readOnly = true)
public Mono<E> find(final Long inEntityId) {
    return Mono.create((Consumer<MonoSink<E>>)  theMonoSink -> {
        try {
            LOGGER.info("Retrieving entity with id {}", inEntityId);

            final Optional<E> theFoundEntity = mRepository.findById(inEntityId);
            if (theFoundEntity.isPresent()) {
                theMonoSink.success(theFoundEntity.get());
            } else {
                theMonoSink.error(
                    new EntityNotFoundException("Entity with id " + inEntityId + " not found"));
            }
        } catch (final Throwable theException) {
            theMonoSink.error(theException);
        }
    })
        .subscribeOn(Schedulers.parallel());
}
 
Example #5
Source File: SpringCloudPipe.java    From bird-java with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> doExecute(ServerWebExchange exchange, PipeChain chain, RouteDefinition routeDefinition) {
    HttpHandle httpHandle = this.buildHttpHandle(routeDefinition);
    if (httpHandle == null) {
        log.error("discovery server never register this route,module = " + routeDefinition.getModule() + ";path = " + routeDefinition.getPath());
        return Mono.empty();
    }

    HttpCommand command = new HttpCommand(HystrixBuilder.build(httpHandle), exchange, chain, httpHandle);

    return Mono.create((MonoSink<Object> s) -> {
        Subscription sub = command.toObservable().subscribe(s::success, s::error, s::success);
        s.onCancel(sub::unsubscribe);
        if (command.isCircuitBreakerOpen()) {
            log.error(httpHandle.getGroupKey() + ":spring cloud execute circuitBreaker is Open !");
        }
    }).doOnError(throwable -> {
        throwable.printStackTrace();
        exchange.getAttributes().put(GatewayConstant.RESPONSE_RESULT_TYPE, ResultEnum.ERROR.getName());
        chain.execute(exchange);
    }).then();
}
 
Example #6
Source File: DubboPipe.java    From bird-java with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> doExecute(ServerWebExchange exchange, PipeChain chain, RouteDefinition routeDefinition) {

    DubboHandle dubboHandle = JSON.parseObject(routeDefinition.getRpcJson(), DubboHandle.class);

    if (!checkData(dubboHandle)) {
        return chain.execute(exchange);
    }

    DubboCommand command = new DubboCommand(HystrixBuilder.build(dubboHandle), exchange, chain, dubboHandle, dubboProxyService);
    return Mono.create((MonoSink<Object> s) -> {
        Subscription sub = command.toObservable().subscribe(s::success,
                s::error, s::success);
        s.onCancel(sub::unsubscribe);
        if (command.isCircuitBreakerOpen()) {
            log.error(dubboHandle.getGroupKey() + ":dubbo execute circuitBreaker is Open !");
        }
    }).doOnError(throwable -> {
        throwable.printStackTrace();
        exchange.getAttributes().put(GatewayConstant.RESPONSE_RESULT_TYPE, ResultEnum.ERROR.getName());
        chain.execute(exchange);
    }).then();
}
 
Example #7
Source File: ReactorElasticSearchClient.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static <T> ActionListener<T> getListener(MonoSink<T> sink) {
    return new ActionListener<T>() {
        @Override
        public void onResponse(T t) {
            sink.success(t);
        }

        @Override
        public void onFailure(Exception e) {
            sink.error(e);
        }
    };
}
 
Example #8
Source File: DefaultPooledConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
DisposableAcquire(
		ConnectionObserver obs,
		ChannelOperations.OnSetup opsFactory,
		long pendingAcquireTimeout,
		InstrumentedPool<PooledConnection> pool,
		MonoSink<Connection> sink) {
	this.cancellations = Disposables.composite();
	this.obs = obs;
	this.opsFactory = opsFactory;
	this.pendingAcquireTimeout = pendingAcquireTimeout;
	this.pool = pool;
	this.retried = false;
	this.sink = sink;
}
 
Example #9
Source File: DefaultPooledConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected CoreSubscriber<PooledRef<PooledConnection>> createDisposableAcquire(
		ConnectionObserver connectionObserver,
		ChannelOperations.OnSetup opsFactory,
		long pendingAcquireTimeout,
		InstrumentedPool<PooledConnection> pool,
		MonoSink<Connection> sink) {
	return new DisposableAcquire(connectionObserver, opsFactory, pendingAcquireTimeout, pool, sink);
}
 
Example #10
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected CoreSubscriber<PooledRef<Connection>> createDisposableAcquire(
		ConnectionObserver connectionObserver,
		ChannelOperations.OnSetup opsFactory,
		long pendingAcquireTimeout,
		InstrumentedPool<Connection> pool,
		MonoSink<Connection> sink) {
	return new DisposableAcquire(connectionObserver, opsFactory, pendingAcquireTimeout, pool, sink);
}
 
Example #11
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
DisposableAcquire(
		ConnectionObserver obs,
		ChannelOperations.OnSetup opsFactory,
		long pendingAcquireTimeout,
		InstrumentedPool<Connection> pool,
		MonoSink<Connection> sink) {
	this.cancellations = Disposables.composite();
	this.obs = obs;
	this.opsFactory = opsFactory;
	this.pendingAcquireTimeout = pendingAcquireTimeout;
	this.pool = pool;
	this.retried = false;
	this.sink = sink;
}
 
Example #12
Source File: DefaultManyReconciler.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private AddHolder(String id, DATA initial, MonoSink<Void> sink) {
    this.sink = sink;
    this.executor = new ReconcilerEngine<>(
            id,
            initial,
            reconcilerActionsProvider,
            metrics,
            titusRuntime
    );
}
 
Example #13
Source File: TimerWithWorker.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static <T> void timer(Supplier<T> action, Scheduler.Worker worker, Duration delay, MonoSink<T> sink) {
    worker.schedule(() -> {
        try {
            T result = action.get();
            if (result != null) {
                sink.success(result);
            } else {
                sink.success();
            }
        } catch (Exception e) {
            sink.error(e);
        }
    }, delay.toMillis(), TimeUnit.MILLISECONDS);
}
 
Example #14
Source File: AbstractServiceBaseReactor.java    From rest-example with Apache License 2.0 5 votes vote down vote up
/**
 * Saves the supplied entity.
 *
 * @param inEntity Entity to save.
 * @return Mono that will receive the saved entity, or exception if error occurs.
 */
public Mono<E> save(final E inEntity) {
    return Mono.create((Consumer<MonoSink<E>>) theMonoSink -> {
        try {
            LOGGER.info("Saving entity: {}", inEntity);

            final E theSavedEntity = mRepository.save(inEntity);
            theMonoSink.success(theSavedEntity);
        } catch (final Throwable theException) {
            theMonoSink.error(theException);
        }
    })
        .subscribeOn(Schedulers.parallel());
}
 
Example #15
Source File: GrpcUtil.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static <REQ> ClientResponseObserver<REQ, Empty> createEmptyClientMonoResponse(MonoSink<Empty> monoSink) {
    return createClientResponseObserver(
            requestStream -> monoSink.onCancel(() -> requestStream.cancel(CANCELLING_MESSAGE, null)),
            monoSink::success,
            monoSink::error,
            monoSink::success
    );
}
 
Example #16
Source File: SimpleConnectionPool.java    From styx with Apache License 2.0 5 votes vote down vote up
private void queueNewConnection(Connection connection) {
    MonoSink<Connection> subscriber = waitingSubscribers.poll();
    if (subscriber == null) {
        availableConnections.add(connection);
    } else {
        attemptBorrowConnection(subscriber, connection);
    }
}
 
Example #17
Source File: GrpcRetryTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Mono<Integer> newThreeErrorMono() {
    return Mono.create(new Consumer<MonoSink<Integer>>() {
        int count = 3;
        @Override
        public void accept(MonoSink<Integer> emitter){
            if (count > 0) {
                emitter.error(new Throwable("Not yet!"));
                count--;
            } else {
                emitter.success(0);
            }
        }
    });
}
 
Example #18
Source File: AbstractServiceBaseReactor.java    From rest-example with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the supplied entity.
 *
 * @param inEntity Entity to update.
 * @return Mono that will receive the updated entity, or exception if error occurs.
 */
public Mono<E> update(final E inEntity) {
    return Mono.create((Consumer<MonoSink<E>>) theMonoSink -> {
        try {
            LOGGER.info("Updating entity: {}", inEntity);

            final E theSavedEntity = mRepository.persist(inEntity);
            theMonoSink.success(theSavedEntity);
        } catch (final Throwable theException) {
            theMonoSink.error(theException);
        }
    })
        .subscribeOn(Schedulers.parallel());
}
 
Example #19
Source File: RequestTask.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static <T> RequestTask<T> wrap(ClientMessage message, MonoSink<T> sink, Supplier<T> supplier) {
    if (message instanceof Disposable) {
        return new RequestTask<>((Disposable) message, sink, supplier);
    }

    return new RequestTask<>(null, sink, supplier);
}
 
Example #20
Source File: SimpleConnectionPool.java    From styx with Apache License 2.0 5 votes vote down vote up
private void attemptBorrowConnection(MonoSink<Connection> sink, Connection connection) {
    borrowedCount.incrementAndGet();
    sink.onCancel(() -> {
        returnConnection(connection);
    });
    sink.success(connection);
}
 
Example #21
Source File: AbstractServiceBaseReactor.java    From rest-example with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the entity having supplied id.
 *
 * @param inEntityId Id of entity to delete.
 * @return Mono that will receive completion or error.
 */
public Mono<Void> delete(final Long inEntityId) {
    return Mono.create((Consumer<MonoSink<Void>>) theMonoSink -> {
        try {
            LOGGER.info("Deleting entity with id {}", inEntityId);

            mRepository.deleteById(inEntityId);
            theMonoSink.success();
        } catch (final Throwable theException) {
            theMonoSink.error(theException);
        }
    })
        .subscribeOn(Schedulers.parallel());
}
 
Example #22
Source File: WriteStreamSubscriber.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
private WriteStreamSubscriber(T writeStream, BiConsumer<T, U> nextHandler, MonoSink<Void> endHook) {
    this.writeStream = writeStream;
    this.nextHandler = nextHandler;
    this.endHook = endHook;
    this.logPrefix = "[" + ObjectUtils.getIdentityHexString(writeStream) + "] ";

    writeStream.exceptionHandler(this::exceptionHandler);
}
 
Example #23
Source File: VertxWebSocketClient.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
private void connect(URI uri, VertxHttpHeaders headers, WebSocketHandler handler, MonoSink<Void> callback) {
    HttpClient client = vertx.createHttpClient(clientOptions);
    client.websocket(uri.getPort(), uri.getHost(), uri.getPath(), headers,
        socket -> handler.handle(initSession(uri, socket))
            .doOnSuccess(callback::success)
            .doOnError(callback::error)
            .doFinally(ignore -> client.close())
            .subscribe(),
        callback::error
    );
}
 
Example #24
Source File: AbstractServiceBaseReactor.java    From rest-example with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes all entities.
 *
 * @return Mono that will receive completion or error.
 */
public Mono<Void> deleteAll() {
    return Mono.create((Consumer<MonoSink<Void>>) theMonoSink -> {
        try {
            LOGGER.info("Deleting all entities.");

            mRepository.deleteAll();
            theMonoSink.success();
        } catch (final Throwable theException) {
            theMonoSink.error(theException);
        }
    })
        .subscribeOn(Schedulers.parallel());
}
 
Example #25
Source File: FunctionConfiguration.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
private Publisher<Object> setupBindingTrigger(GenericApplicationContext context) {
	AtomicReference<MonoSink<Object>> triggerRef = new AtomicReference<>();
	Publisher<Object> beginPublishingTrigger = Mono.create(emmiter -> {
		triggerRef.set(emmiter);
	});
	context.addApplicationListener(event -> {
		if (event instanceof BindingCreatedEvent) {
			if (triggerRef.get() != null) {
				triggerRef.get().success();
			}
		}
	});
	return beginPublishingTrigger;
}
 
Example #26
Source File: RequestTask.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static <T> RequestTask<T> wrap(ClientMessage message, MonoSink<T> sink, Supplier<T> supplier) {
    if (message instanceof Disposable) {
        return new RequestTask<>((Disposable) message, sink, supplier);
    }

    return new RequestTask<>(null, sink, supplier);
}
 
Example #27
Source File: NewConnectionProvider.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
NewConnectionObserver(MonoSink<Connection> sink, ConnectionObserver obs) {
	this.sink = sink;
	this.obs = obs;
}
 
Example #28
Source File: HttpClientConnect.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
ClientTransportSubscriber(MonoSink<Connection> sink) {
	this.sink = sink;
}
 
Example #29
Source File: HttpClientConnect.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
HttpObserver(MonoSink<Connection> sink, HttpClientHandler handler) {
	this.sink = sink;
	this.handler = handler;
}
 
Example #30
Source File: ReconcilerEngine.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
/**
 * Returns function, so evaluation which notifies a subscriber may be run on a different thread.
 * <p>
 * TODO Support concurrent transactions in the reconciliation loop.
 */
Optional<Pair<Optional<DATA>, Runnable>> closeFinishedTransaction() {
    if (pendingTransaction == null) {
        return Optional.empty();
    }

    TransactionStatus<DATA> status = pendingTransaction.getStatus();
    TransactionStatus.State state = status.getState();

    // Still running
    if (state == TransactionStatus.State.Started || state == TransactionStatus.State.ResultReady) {
        if (this.state.get() != ReconcilerState.Running) {
            pendingTransaction.cancel();
        }
        return Optional.empty();
    }

    // If sink is null, it is a reconciliation action
    MonoSink<DATA> sink = pendingTransaction.getActionHolder().getSubscriberSink();

    try {
        // Completed
        if (state == TransactionStatus.State.Completed) {
            DATA result = status.getResult();
            if (sink == null) {
                return Optional.of(Pair.of(Optional.ofNullable(result), Evaluators::doNothing));
            }
            if (result == null) {
                return Optional.of(Pair.of(Optional.empty(), () -> ExceptionExt.silent(sink::success)));
            }
            return Optional.of(Pair.of(Optional.of(result), () -> ExceptionExt.silent(() -> sink.success(result))));
        }

        // Failed
        if (state == TransactionStatus.State.Failed) {
            if (sink == null) {
                logger.warn("Reconciler action failure: {}", pendingTransaction.getStatus().getError().getMessage());
                return Optional.empty();
            }
            return Optional.of(Pair.of(Optional.empty(), () -> ExceptionExt.silent(() -> sink.error(status.getError()))));
        }

        // Cancelled
        if (state == TransactionStatus.State.Cancelled) {
            if (sink == null) {
                return Optional.empty();
            }
            return Optional.of(Pair.of(Optional.empty(), () -> ExceptionExt.silent(() -> sink.error(new IllegalStateException("cancelled")))));
        }

        // Not reachable unless there is a serious bug.
        logger.error("Unexpected state: {}", state);
        return Optional.empty();
    } finally {
        pendingTransaction = null;
    }
}