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

The following examples show how to use reactor.core.publisher.Mono#fromFuture() . 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: reactor-core   File: MonoTests.java    License: 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 2
/**
 * 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
@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 4
@Override
public <T> Mono<T> toMono(@Nullable Object source) {
    if (source == null) {
        return Mono.empty();
    } else {
        return Mono.fromFuture((CompletableFuture) source);
    }
}
 
Example 5
Source Project: soul   File: ApacheDubboProxyService.java    License: 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 6
@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 7
Source Project: cyclops   File: MonoAdapter.java    License: 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 Project: cyclops   File: MonosTest.java    License: 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 9
Source Project: tutorials   File: UploadResource.java    License: 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 10
@GetMapping("/completablefuture/get")
public Mono<Map> get() {
	return Mono.fromFuture(httpBin.get());
}
 
Example 11
@Override
public Mono<ListOrganizationsResponse> retrieveOrgId(String orgName) {
	return Mono.fromFuture(this.orgCache.get(orgName));
}
 
Example 12
@Override
public Mono<ListApplicationsResponse> retrieveAllApplicationIdsInSpace(String orgId, String spaceId) {
	final CacheKeyAppsInSpace key = new CacheKeyAppsInSpace(orgId, spaceId);
	
	return Mono.fromFuture(this.appsInSpaceCache.get(key));
}
 
Example 13
@Override
public Mono<GetSpaceSummaryResponse> retrieveSpaceSummary(String spaceId) {
	return Mono.fromFuture(this.spaceSummaryCache.get(spaceId));
}
 
Example 14
@Override
public Mono<ListOrganizationsResponse> retrieveAllOrgIds() {
	return Mono.fromFuture(this.allOrgIdCache.get("all"));
}
 
Example 15
@Override
public Mono<ListSpacesResponse> retrieveSpaceIdsInOrg(String orgId) {
	return Mono.fromFuture(this.spaceIdInOrgCache.get(orgId));
}
 
Example 16
@Override
public Mono<Job> getJobById(String jobId) {
    return Mono.fromFuture(jobs.get(jobId));
}
 
Example 17
Source Project: cxf   File: ReactorInvokerImpl.java    License: 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 18
@Override
public Mono<ListSpacesResponse> retrieveSpaceId(String orgId, String spaceName) {
	
	final CacheKeySpace key = new CacheKeySpace(orgId, spaceName);
	
	return Mono.fromFuture(this.spaceCache.get(key));
}