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

The following examples show how to use reactor.core.publisher.Mono#from() . 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: ModelAttributeMethodArgumentResolver.java    From java-technology-stack with MIT License 7 votes vote down vote up
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 2
Source File: ModelAttributeMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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 3
Source File: DeviceMessageController.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@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
Source File: DefaultTestPublisher.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<T> mono() {
	if (violations.isEmpty()) {
		return Mono.from(this);
	}
	else {
		return Mono.fromDirect(this);
	}
}
 
Example 5
Source File: ReactiveAdapterDefault.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 instanceof Mono) {
        return (Mono) source;
    } else if (source instanceof Publisher) {
        return Mono.from((Publisher) source);
    } else {
        return (Mono<T>) Mono.justOrEmpty(source);
    }
}
 
Example 6
Source File: WebSessionMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 7
Source File: PrincipalMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 8
Source File: MonoTests.java    From reactor-core with 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 9
Source File: ReactorLoadBalancerExchangeFilterFunction.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
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 10
Source File: MonoTests.java    From reactor-core with 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 11
Source File: ColdTestPublisher.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<T> mono() {
	return Mono.from(this);
}
 
Example 12
Source File: ReactorBatch.java    From etherjar with 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 13
Source File: AbstractView.java    From java-technology-stack with 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 File: ReactorOperators.java    From cyclops with 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 15
Source File: PreDeletionHooks.java    From james-project with 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 16
Source File: QuotaThresholdCrossingListener.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Mono<Void> handleEvent(Username username, QuotaUsageUpdatedEvent event) {
    return Mono.from(eventSourcingSystem.dispatch(
        new DetectThresholdCrossing(username, event.getCountQuota(), event.getSizeQuota(), event.getInstant())));
}
 
Example 17
Source File: ReactorWritable.java    From immutables with 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 18
Source File: Monos.java    From cyclops with 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 19
Source File: Monos.java    From cyclops with 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 20
Source File: Monos.java    From cyclops with 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)));

}