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

The following examples show how to use reactor.core.publisher.Mono#from() . 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
private Mono<?> prepareAttributeMono(String attributeName, ResolvableType attributeType,
		BindingContext context, ServerWebExchange exchange) {

	Object attribute = context.getModel().asMap().get(attributeName);

	if (attribute == null) {
		attribute = findAndRemoveReactiveAttribute(context.getModel(), attributeName);
	}

	if (attribute == null) {
		return createAttribute(attributeName, attributeType.toClass(), context, exchange);
	}

	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(null, attribute);
	if (adapter != null) {
		Assert.isTrue(!adapter.isMultiValue(), "Data binding only supports single-value async types");
		return Mono.from(adapter.toPublisher(attribute));
	}
	else {
		return Mono.justOrEmpty(attribute);
	}
}
 
Example 2
private Mono<?> prepareAttributeMono(String attributeName, ResolvableType attributeType,
		BindingContext context, ServerWebExchange exchange) {

	Object attribute = context.getModel().asMap().get(attributeName);

	if (attribute == null) {
		attribute = findAndRemoveReactiveAttribute(context.getModel(), attributeName);
	}

	if (attribute == null) {
		return createAttribute(attributeName, attributeType.toClass(), context, exchange);
	}

	ReactiveAdapter adapterFrom = getAdapterRegistry().getAdapter(null, attribute);
	if (adapterFrom != null) {
		Assert.isTrue(!adapterFrom.isMultiValue(), "Data binding only supports single-value async types");
		return Mono.from(adapterFrom.toPublisher(attribute));
	}
	else {
		return Mono.justOrEmpty(attribute);
	}
}
 
Example 3
@GetMapping("/standard/{deviceId}/property/{property:.+}")
@SneakyThrows
public Mono<DevicePropertiesEntity> getStandardProperty(@PathVariable String deviceId, @PathVariable String property) {
    return Mono.from(registry
        .getDevice(deviceId)
        .switchIfEmpty(ErrorUtils.notFound("设备不存在"))
        .flatMapMany(deviceOperator -> deviceOperator.messageSender()
            .readProperty(property).messageId(IDGenerator.SNOW_FLAKE_STRING.generate())
            .send()
            .map(mapReply(ReadPropertyMessageReply::getProperties))
            .flatMap(map -> {
                Object value = map.get(property);
                return deviceOperator.getMetadata()
                    .map(deviceMetadata -> deviceMetadata.getProperty(property)
                        .map(PropertyMetadata::getValueType)
                        .orElse(new StringType()))
                    .map(dataType -> DevicePropertiesEntity.builder()
                        .deviceId(deviceId)
                        .productId(property)
                        .build()
                        .withValue(dataType, value));
            })))
        ;

}
 
Example 4
@Override
public <T> Mono<T> toMono(@Nullable Object source) {
    if (source instanceof Mono) {
        return (Mono) source;
    } else if (source instanceof Publisher) {
        return Mono.from((Publisher) source);
    } else {
        return (Mono<T>) Mono.justOrEmpty(source);
    }
}
 
Example 5
Source Project: reactor-core   File: MonoTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromMonoDoesntCallAssemblyHook() {
	final Mono<Integer> source = Mono.just(1);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.from(source);
	Assertions.assertThat(wrappedCount).hasValue(0);
}
 
Example 6
protected Mono<Response<ServiceInstance>> choose(String serviceId) {
	ReactiveLoadBalancer<ServiceInstance> loadBalancer = loadBalancerFactory
			.getInstance(serviceId);
	if (loadBalancer == null) {
		return Mono.just(new EmptyResponse());
	}
	return Mono.from(loadBalancer.choose());
}
 
Example 7
Source Project: reactor-core   File: MonoTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromFluxWrappingMonoDoesntCallAssemblyHook() {
	final Flux<Integer> source = Flux.from(Mono.just(1).hide());

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.from(source);
	Assertions.assertThat(wrappedCount).hasValue(0);
}
 
Example 8
@Override
public Mono<T> mono() {
	if (violations.isEmpty()) {
		return Mono.from(this);
	}
	else {
		return Mono.fromDirect(this);
	}
}
 
Example 9
@Override
public Mono<Object> resolveArgument(
		MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {

	Mono<Principal> principal = exchange.getPrincipal();
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType());
	return (adapter != null ? Mono.just(adapter.fromPublisher(principal)) : Mono.from(principal));
}
 
Example 10
@Override
public Mono<Object> resolveArgument(
		MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {

	Mono<WebSession> session = exchange.getSession();
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType());
	return (adapter != null ? Mono.just(adapter.fromPublisher(session)) : Mono.from(session));
}
 
Example 11
Source Project: etherjar   File: ReactorBatch.java    License: Apache License 2.0 4 votes vote down vote up
public Mono<RES> getResult() {
    Mono<RES> value = Mono.from(proc);
    return value.or(Mono.when(onceExecuted).then(value));
}
 
Example 12
Source Project: immutables   File: ReactorWritable.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Mono<WriteResult> upsertAll(Iterable<? extends T> docs) {
  return Mono.from(writable.upsertAll(docs));
}
 
Example 13
Source Project: java-technology-stack   File: AbstractView.java    License: MIT License 4 votes vote down vote up
/**
 * By default, resolve async attributes supported by the
 * {@link ReactiveAdapterRegistry} to their blocking counterparts.
 * <p>View implementations capable of taking advantage of reactive types
 * can override this method if needed.
 * @return {@code Mono} for the completion of async attributes resolution
 */
protected Mono<Void> resolveAsyncAttributes(Map<String, Object> model) {
	List<String> names = new ArrayList<>();
	List<Mono<?>> valueMonos = new ArrayList<>();

	for (Map.Entry<String, ?> entry : model.entrySet()) {
		Object value =  entry.getValue();
		if (value == null) {
			continue;
		}
		ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(null, value);
		if (adapter != null) {
			names.add(entry.getKey());
			if (adapter.isMultiValue()) {
				Flux<Object> fluxValue = Flux.from(adapter.toPublisher(value));
				valueMonos.add(fluxValue.collectList().defaultIfEmpty(Collections.emptyList()));
			}
			else {
				Mono<Object> monoValue = Mono.from(adapter.toPublisher(value));
				valueMonos.add(monoValue.defaultIfEmpty(NO_VALUE));
			}
		}
	}

	if (names.isEmpty()) {
		return Mono.empty();
	}

	return Mono.zip(valueMonos,
			values -> {
				for (int i=0; i < values.length; i++) {
					if (values[i] != NO_VALUE) {
						model.put(names.get(i), values[i]);
					}
					else {
						model.remove(names.get(i));
					}
				}
				return NO_VALUE;
			})
			.then();
}
 
Example 14
Source Project: reactor-core   File: ColdTestPublisher.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Mono<T> mono() {
	return Mono.from(this);
}
 
Example 15
Source Project: cyclops   File: ReactorOperators.java    License: Apache License 2.0 4 votes vote down vote up
public static <T,R> Function<Mono<T>,Mono<R>> future(final Function<? super Future<? super T>,? extends Future<? extends R>> fn){
        return s-> Mono.from(fn.apply(Future.fromPublisher(s)));
}
 
Example 16
Source Project: james-project   File: PreDeletionHooks.java    License: Apache License 2.0 4 votes vote down vote up
private Mono<Void> publishMetric(PreDeletionHook.DeleteOperation deleteOperation, PreDeletionHook hook, MetricFactory factory) {
    return Mono.from(
        factory.decoratePublisherWithTimerMetric(PRE_DELETION_HOOK_METRIC_NAME, hook.notifyDelete(deleteOperation)));
}
 
Example 17
private Mono<Void> handleEvent(Username username, QuotaUsageUpdatedEvent event) {
    return Mono.from(eventSourcingSystem.dispatch(
        new DetectThresholdCrossing(username, event.getCountQuota(), event.getSizeQuota(), event.getInstant())));
}
 
Example 18
Source Project: cyclops   File: Monos.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Lazily combine this Mono with the supplied value via the supplied BiFunction
 *
 * @param mono Mono to combine with another value
 * @param app Value to combine with supplied mono
 * @param fn Combiner function
 * @return Combined Mono
 */
public static <T1, T2, R> Mono<R> combine(Mono<? extends T1> mono, Value<? extends T2> app,
        BiFunction<? super T1, ? super T2, ? extends R> fn) {
    return Mono.from(Future.of(mono.toFuture())
                            .zip(app, fn));
}
 
Example 19
Source Project: cyclops   File: Monos.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Construct a Mono from Iterable by taking the first value from Iterable
 *
 * @param t Iterable to populate Mono from
 * @return Mono containing first element from Iterable (or empty Mono)
 */
public static <T> Mono<T> fromIterable(Iterable<T> t) {
    return Mono.from(Flux.fromIterable(t));
}
 
Example 20
Source Project: cyclops   File: Monos.java    License: Apache License 2.0 votes vote down vote up
/**
 * Select the first Future to return with a successful result
 *
 * <pre>
 * {@code
 * Mono<Integer> ft = Mono.empty();
  Mono<Integer> result = Monos.firstSuccess(Mono.deferred(()->1),ft);

ft.complete(10);
result.get() //1
 * }
 * </pre>
 *
 * @param fts Monos to race
 * @return First Mono to return with a result
 */
@SafeVarargs
public static <T> Mono<T> firstSuccess(Mono<T>... fts) {
    return Mono.from(Future.firstSuccess(futures(fts)));

}