Java Code Examples for reactor.core.publisher.Mono#defer()

The following examples show how to use reactor.core.publisher.Mono#defer() . These examples are extracted from open source projects. 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 Project: soul   File: SoulWebHandler.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * Delegate to the next {@code WebFilter} in the chain.
 *
 * @param exchange the current server exchange
 * @return {@code Mono<Void>} to indicate when request handling is complete
 */
@Override
public Mono<Void> execute(final ServerWebExchange exchange) {
    return Mono.defer(() -> {
        if (this.index < plugins.size()) {
            SoulPlugin plugin = plugins.get(this.index++);
            Boolean skip = plugin.skip(exchange);
            if (skip) {
                return this.execute(exchange);
            } else {
                return plugin.execute(exchange, this);
            }
        } else {
            return Mono.empty();
        }
    });
}
 
Example 2
@Override
public Mono<Void> subscribe(ByteBuffer... channels) {
    monosListener.acquire();
    return Mono.defer(() -> {
        RedissonPromise<Void> result = new RedissonPromise<>();
        result.onComplete((r, ex) -> {
            monosListener.release();
        });
        CountableListener<Void> listener = new CountableListener<>(result, null, channels.length);
        for (ByteBuffer channel : channels) {
            ChannelName cn = toChannelName(channel);
            RFuture<PubSubConnectionEntry> f = subscribeService.subscribe(ByteArrayCodec.INSTANCE, cn);
            f.onComplete((res, e) -> RedissonReactiveSubscription.this.channels.put(cn, res));
            f.onComplete(listener);
        }

        return Mono.fromFuture(result);
    });
}
 
Example 3
@Nonnull
@Override
public Mono<MqttClientProperties> createConfig(@Nonnull NetworkProperties properties) {
    return Mono.defer(() -> {
        MqttClientProperties config = FastBeanCopier.copy(properties.getConfigurations(), new MqttClientProperties());
        config.setId(properties.getId());
        if (config.getOptions() == null) {
            config.setOptions(new MqttClientOptions());
            config.getOptions().setClientId(config.getClientId());
            config.getOptions().setPassword(config.getPassword());
            config.getOptions().setUsername(config.getUsername());
        }
        if (config.isSsl()) {
            config.getOptions().setSsl(true);
            return certificateManager.getCertificate(config.getCertId())
                .map(VertxKeyCertTrustOptions::new)
                .doOnNext(config.getOptions()::setKeyCertOptions)
                .doOnNext(config.getOptions()::setTrustOptions)
                .thenReturn(config);
        }
        return Mono.just(config);
    });
}
 
Example 4
@Nonnull
@Override
public Mono<VertxMqttServerProperties> createConfig(@Nonnull NetworkProperties properties) {
    return Mono.defer(() -> {
        VertxMqttServerProperties config = FastBeanCopier.copy(properties.getConfigurations(), new VertxMqttServerProperties());
        config.setId(properties.getId());

        config.setOptions(new JSONObject(properties.getConfigurations()).toJavaObject(MqttServerOptions.class));

        if (config.isSsl()) {
            config.getOptions().setSsl(true);
            return certificateManager.getCertificate(config.getCertId())
                    .map(VertxKeyCertTrustOptions::new)
                    .doOnNext(config.getOptions()::setKeyCertOptions)
                    .doOnNext(config.getOptions()::setTrustOptions)
                    .thenReturn(config);
        }
        return Mono.just(config);
    });
}
 
Example 5
private Mono<Void> authorizeJobUpdate(CallMetadata callMetadata, String jobId) {
    return Mono.defer(() -> {
        com.netflix.titus.api.jobmanager.model.job.Job<?> job = jobOperations.getJob(jobId).orElse(null);
        if (job == null) {
            return Mono.error(JobManagerException.jobNotFound(jobId));
        }
        return authorizeJobUpdate(callMetadata, job);
    });
}
 
Example 6
Source Project: reactor-pool   File: SimplePool.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Integer> warmup() {
    if (poolConfig.allocationStrategy().permitMinimum() > 0) {
        return Mono.defer(() -> {
            int initSize = poolConfig.allocationStrategy().getPermits(0);
            @SuppressWarnings({"unchecked", "rawtypes"})
            Mono<POOLABLE>[] allWarmups = new Mono[initSize];
            for (int i = 0; i < initSize; i++) {
                long start = clock.millis();
                allWarmups[i] = poolConfig
                        .allocator()
                        .doOnNext(p -> {
                            metricsRecorder.recordAllocationSuccessAndLatency(clock.millis() - start);
                            //the pool slot won't access this pool instance until after it has been constructed
                            this.elements.offer(createSlot(p));
                        })
                        .doOnError(e -> {
                            metricsRecorder.recordAllocationFailureAndLatency(clock.millis() - start);
                            poolConfig.allocationStrategy().returnPermits(1);
                        });
            }
            return Flux.concat(allWarmups)
                       .reduce(0, (count, p) -> count + 1);
        });
    }
    else {
        return Mono.just(0);
    }
}
 
Example 7
@Override
public Mono<Payload> requestResponse(Payload payload) {
	return Mono.defer(() -> {
		Timer.Sample sample = requestResponse.start();

		return delegate.requestResponse(payload)
				.doFinally(signalType -> requestResponse.accept(sample, signalType));
	});
}
 
Example 8
private <R> Mono<R> createNotFoundError() {
	return Mono.defer(() -> {
		Exception ex = new ResponseStatusException(HttpStatus.NOT_FOUND, "No matching handler");
		return Mono.error(ex);
	});
}
 
Example 9
Source Project: cloud-spanner-r2dbc   File: GrpcClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Session> createSession(String databaseName) {
  return Mono.defer(() -> {
    Assert.requireNonEmpty(databaseName, "Database name must not be empty");

    CreateSessionRequest request = CreateSessionRequest.newBuilder()
        .setDatabase(databaseName)
        .build();

    return ObservableReactiveUtil.unaryCall((obs) -> this.spanner.createSession(request, obs));
  });
}
 
Example 10
public Mono<User> requestUserData(String userId) {
    return Mono.defer(() ->
        isValid(userId)
            ? Mono.fromCallable(() -> requestUser(userId))
            : Mono.error(new IllegalArgumentException("Invalid user id")));
}
 
Example 11
Source Project: cloud-spanner-r2dbc   File: GrpcClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> deleteSession(String sessionName) {
  return Mono.defer(() -> {
    Assert.requireNonNull(sessionName, "Session name must not be null");

    DeleteSessionRequest deleteSessionRequest =
        DeleteSessionRequest.newBuilder()
            .setName(sessionName)
            .build();

    return ObservableReactiveUtil.<Empty>unaryCall(
        (observer) -> this.spanner.deleteSession(deleteSessionRequest, observer))
        .then();
  });
}
 
Example 12
@Nonnull
@Override
public Mono<WeixinCorpNotifier> createNotifier(@Nonnull NotifierProperties properties) {
    return Mono.defer(() -> {
        WechatCorpProperties wechatCorpProperties = FastBeanCopier.copy(properties.getConfiguration(), new WechatCorpProperties());
        return Mono.just(new WeixinCorpNotifier(properties.getId(),client, ValidatorUtils.tryValidate(wechatCorpProperties), templateManager));
    });
}
 
Example 13
Source Project: reactor-pool   File: SimplePool.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> invalidate() {
    return Mono.defer(() -> {
        if (markInvalidate()) {
            //immediately clean up state
            ACQUIRED.decrementAndGet(pool);
            return pool.destroyPoolable(this).then(Mono.fromRunnable(pool::drain));
        }
        else {
            return Mono.empty();
        }
    });
}
 
Example 14
Source Project: ratelimitj   File: RedisScriptLoader.java    License: Apache License 2.0 4 votes vote down vote up
Mono<StoredScript> storedScript() {
    return Mono.defer(() -> {
        Flux<String> source = this.storedScript.get();
        return source.next().map(sha -> new StoredScript(sha, source));
    });
}
 
Example 15
@Override
@SuppressWarnings("unchecked")
public Mono<Success> filter(E exchange) {
	return Mono.defer(() -> this.currentFilter != null && this.next != null
			? this.currentFilter.filter(exchange, this.next) : getMonoSuccess());
}
 
Example 16
@Override
public Mono<String> newSpanInTraceContext() {
	return Mono.defer(() -> Mono.just(id(this.tracer)));
}
 
Example 17
private Mono<Void> save() {
	return Mono.defer(() -> saveChangeSessionId().then(saveDelta()).doOnSuccess((aVoid) -> this.isNew = false));
}
 
Example 18
@Override
@SuppressWarnings("unchecked")
public Mono<Void> disposeLater(Duration quietPeriod, Duration timeout) {
	return Mono.defer(() -> {
		long quietPeriodMillis = quietPeriod.toMillis();
		long timeoutMillis = timeout.toMillis();

		EventLoopGroup serverLoopsGroup = serverLoops.get();
		EventLoopGroup clientLoopsGroup = clientLoops.get();
		EventLoopGroup serverSelectLoopsGroup = serverSelectLoops.get();
		EventLoopGroup cacheNativeClientGroup = cacheNativeClientLoops.get();
		EventLoopGroup cacheNativeSelectGroup = cacheNativeSelectLoops.get();
		EventLoopGroup cacheNativeServerGroup = cacheNativeServerLoops.get();

		Mono<?> clMono = Mono.empty();
		Mono<?> sslMono = Mono.empty();
		Mono<?> slMono = Mono.empty();
		Mono<?> cnclMono = Mono.empty();
		Mono<?> cnslMono = Mono.empty();
		Mono<?> cnsrvlMono = Mono.empty();
		if (running.compareAndSet(true, false)) {
			if (clientLoopsGroup != null) {
				clMono = FutureMono.from((Future) clientLoopsGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (serverSelectLoopsGroup != null) {
				sslMono = FutureMono.from((Future) serverSelectLoopsGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (serverLoopsGroup != null) {
				slMono = FutureMono.from((Future) serverLoopsGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (cacheNativeClientGroup != null) {
				cnclMono = FutureMono.from((Future) cacheNativeClientGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (cacheNativeSelectGroup != null) {
				cnslMono = FutureMono.from((Future) cacheNativeSelectGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (cacheNativeServerGroup != null) {
				cnsrvlMono = FutureMono.from((Future) cacheNativeServerGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
		}

		return Mono.when(clMono, sslMono, slMono, cnclMono, cnslMono, cnsrvlMono);
	});
}
 
Example 19
Source Project: reactor-netty   File: TcpResources.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Prepare to shutdown the global {@link TcpResources} without resetting them,
 * effectively cleaning up associated resources without creating new ones. This only
 * occurs when the returned {@link Mono} is subscribed to.
 * It is guaranteed that the disposal of the underlying LoopResources will not happen before
 * {@code quietPeriod} is over. If a task is submitted during the {@code quietPeriod},
 * it is guaranteed to be accepted and the {@code quietPeriod} will start over.
 *
 * @param quietPeriod the quiet period as described above
 * @param timeout the maximum amount of time to wait until the disposal of the underlying
 * LoopResources regardless if a task was submitted during the quiet period
 * @return a {@link Mono} triggering the {@link #disposeLoopsAndConnections()} when subscribed to.
 * @since 0.9.3
 */
public static Mono<Void> disposeLoopsAndConnectionsLater(Duration quietPeriod, Duration timeout) {
	return Mono.defer(() -> {
		TcpResources resources = tcpResources.getAndSet(null);
		if (resources != null) {
			return resources._disposeLater(quietPeriod, timeout);
		}
		return Mono.empty();
	});
}
 
Example 20
/**
 * Returns a {@link Mono} indicating that the rate limit has ended.
 *
 * @return a {@link Mono} that completes when the currently set limit has completed
 */
private Mono<Void> onComplete() {
    return Mono.defer(this::notifier);
}