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

The following examples show how to use reactor.core.publisher.Mono#fromFuture() . 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: ArmeriaHttpClientResponseSubscriber.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(Subscriber<? super HttpObject> s) {
    for (;;) {
        final Subscriber<? super HttpObject> oldSubscriber = subscriber;
        if (oldSubscriber == null) {
            // The first subscriber.
            if (subscriberUpdater.compareAndSet(this, null, s)) {
                s.onSubscribe(this);
                break;
            }
        } else {
            // The other subscribers - notify whether completed successfully only.
            if (publisherForLateSubscribers == null) {
                @SuppressWarnings({ "unchecked", "rawtypes" })
                final Publisher<HttpObject> newPublisher =
                        (Publisher) Mono.fromFuture(parent.completionFuture);
                publisherForLateSubscribers = newPublisher;
            }
            publisherForLateSubscribers.subscribe(s);
            break;
        }
    }
}
 
Example 2
Source File: ArmeriaServerHttpResponse.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the {@link HttpResponseWriter} if it is opened.
 */
private Mono<Void> cleanup(@Nullable Throwable cause) {
    if (future.isDone()) {
        return Mono.empty();
    }

    if (cause != null) {
        future.completeExceptionally(cause);
        logger.debug("{} Response future has been completed with a cause", ctx, cause);
        return Mono.empty();
    }

    final HttpResponse response = HttpResponse.of(buildResponseHeaders());
    future.complete(response);
    logger.debug("{} Response future has been completed with an HttpResponse", ctx);
    return Mono.fromFuture(response.whenComplete());
}
 
Example 3
Source File: MonoTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void fromFutureSupplier() {
	AtomicInteger source = new AtomicInteger();

	Supplier<CompletableFuture<Integer>> supplier = () -> CompletableFuture.completedFuture(source.incrementAndGet());
	Mono<Number> mono = Mono.fromFuture(supplier);

	Assertions.assertThat(source).hasValue(0);

	Assertions.assertThat(mono.block())
	          .isEqualTo(source.get())
	          .isEqualTo(1);

	Assertions.assertThat(mono.block())
	          .isEqualTo(source.get())
	          .isEqualTo(2);
}
 
Example 4
Source File: CaffeineAsyncLoadingTest.java    From promregator with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailureOnAsynchronous() {
	FakeTicker ticker = new FakeTicker();
	
	AsyncLoadingCache<String, Integer> subject = Caffeine.newBuilder()
			.expireAfterAccess(240, TimeUnit.SECONDS)
			.refreshAfterWrite(120, TimeUnit.SECONDS)
			.ticker(ticker::read)
			.recordStats()
			.buildAsync(new AsyncCacheLoaderFailureImplementation());
	
	Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block());
	
	ticker.advance(Duration.ofSeconds(10));
	
	Assert.assertEquals(new Integer(0), Mono.fromFuture(subject.get("a")).block());
	
	ticker.advance(Duration.ofSeconds(250));
	
	Mono<Integer> errorMono = Mono.fromFuture(subject.get("a"));
	
	boolean thrown = false;
	try {
		errorMono.block();
		thrown = false;
	} catch (Throwable t) {
		thrown = true;
	}
	Assert.assertTrue(thrown);
}
 
Example 5
Source File: UploadResource.java    From tutorials with MIT License 5 votes vote down vote up
private Mono<CompleteMultipartUploadResponse> completeUpload(UploadState state) {        
    log.info("[I202] completeUpload: bucket={}, filekey={}, completedParts.size={}", state.bucket, state.filekey, state.completedParts.size());        

    CompletedMultipartUpload multipartUpload = CompletedMultipartUpload.builder()
        .parts(state.completedParts.values())
        .build();

    return Mono.fromFuture(s3client.completeMultipartUpload(CompleteMultipartUploadRequest.builder()
        .bucket(state.bucket)
        .uploadId(state.uploadId)
        .multipartUpload(multipartUpload)
        .key(state.filekey)
        .build()));
}
 
Example 6
Source File: MonosTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
    just = Mono.just(10);
    none = Mono.empty();
    none.toFuture().completeExceptionally(new Exception("boo"));
    active = Mono.fromFuture(CompletableFuture::new);
    just2 = Mono.just(20);
}
 
Example 7
Source File: MonoAdapter.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public <T, R> AnyM<mono, R> ap(AnyM<mono,? extends Function<? super T,? extends R>> fn, AnyM<mono, T> apply) {
    Mono<T> f = future(apply);
    Mono<? extends Function<? super T, ? extends R>> fnF = future(fn);
    Mono<R> res = Mono.fromFuture(fnF.toFuture().thenCombine(f.toFuture(), (a, b) -> a.apply(b)));
    return MonoAnyM.anyM(res);

}
 
Example 8
Source File: ReactiveAdapterFuture.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Mono<T> toMono(@Nullable Object source) {
    if (source == null) {
        return Mono.empty();
    } else {
        return Mono.fromFuture((CompletableFuture) source);
    }
}
 
Example 9
Source File: ApacheDubboProxyService.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Generic invoker object.
 *
 * @param body     the body
 * @param metaData the meta data
 * @param exchange the exchange
 * @return the object
 * @throws SoulException the soul exception
 */
public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws SoulException {
    ReferenceConfig<GenericService> reference = ApplicationConfigCache.getInstance().get(metaData.getServiceName());
    if (Objects.isNull(reference) || StringUtils.isEmpty(reference.getInterface())) {
        ApplicationConfigCache.getInstance().invalidate(metaData.getServiceName());
        reference = ApplicationConfigCache.getInstance().initRef(metaData);
    }
    GenericService genericService = reference.get();
    Pair<String[], Object[]> pair;
    try {
        if (null == body || "".equals(body) || "{}".equals(body) || "null".equals(body)) {
            pair = new ImmutablePair<>(new String[]{}, new Object[]{});
        } else {
            pair = dubboParamResolveService.buildParameter(body, metaData.getParameterTypes());
        }
        CompletableFuture<Object> future = genericService.$invokeAsync(metaData.getMethodName(), pair.getLeft(), pair.getRight());
        return Mono.fromFuture(future.thenApply(ret -> {
            if (Objects.nonNull(ret)) {
                exchange.getAttributes().put(Constants.DUBBO_RPC_RESULT, ret);
            } else {
                exchange.getAttributes().put(Constants.DUBBO_RPC_RESULT, Constants.DUBBO_RPC_RESULT_EMPTY);
            }
            exchange.getAttributes().put(Constants.CLIENT_RESPONSE_RESULT_TYPE, ResultEnum.SUCCESS.getName());
            return ret;
        }));
    } catch (GenericException e) {
        log.error("dubbo invoker have exception", e);
        throw new SoulException(e.getMessage());
    }
}
 
Example 10
Source File: CFAccessorCacheCaffeine.java    From promregator with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ListSpacesResponse> retrieveSpaceIdsInOrg(String orgId) {
	return Mono.fromFuture(this.spaceIdInOrgCache.get(orgId));
}
 
Example 11
Source File: CFAccessorCacheCaffeine.java    From promregator with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ListOrganizationsResponse> retrieveAllOrgIds() {
	return Mono.fromFuture(this.allOrgIdCache.get("all"));
}
 
Example 12
Source File: TitusClientImpl.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Job> getJobById(String jobId) {
    return Mono.fromFuture(jobs.get(jobId));
}
 
Example 13
Source File: CFAccessorCacheCaffeine.java    From promregator with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<GetSpaceSummaryResponse> retrieveSpaceSummary(String spaceId) {
	return Mono.fromFuture(this.spaceSummaryCache.get(spaceId));
}
 
Example 14
Source File: CFAccessorCacheCaffeine.java    From promregator with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ListApplicationsResponse> retrieveAllApplicationIdsInSpace(String orgId, String spaceId) {
	final CacheKeyAppsInSpace key = new CacheKeyAppsInSpace(orgId, spaceId);
	
	return Mono.fromFuture(this.appsInSpaceCache.get(key));
}
 
Example 15
Source File: CFAccessorCacheCaffeine.java    From promregator with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ListOrganizationsResponse> retrieveOrgId(String orgName) {
	return Mono.fromFuture(this.orgCache.get(orgName));
}
 
Example 16
Source File: ReactorInvokerImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
private <R> Mono<R> mono(Future<R> future) {
    return Mono.fromFuture(toCompletableFuture(future, executorService));
}
 
Example 17
Source File: CompletableFutureDemoController.java    From spring-cloud-circuitbreaker-demo with Apache License 2.0 4 votes vote down vote up
@GetMapping("/completablefuture/get")
public Mono<Map> get() {
	return Mono.fromFuture(httpBin.get());
}
 
Example 18
Source File: CFAccessorCacheCaffeine.java    From promregator with Apache License 2.0 3 votes vote down vote up
@Override
public Mono<ListSpacesResponse> retrieveSpaceId(String orgId, String spaceName) {
	
	final CacheKeySpace key = new CacheKeySpace(orgId, spaceName);
	
	return Mono.fromFuture(this.spaceCache.get(key));
}