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

The following examples show how to use reactor.core.publisher.Mono#fromCallable() . 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
/**
 * Notice on which thread everything runs
 */
@Test
public void blockTriggersWork() throws Exception {
	//given
	AtomicBoolean flag = new AtomicBoolean();

	//when
	log.info("About to create Mono");
	final Mono<Integer> work = Mono.fromCallable(() -> {
		log.info("Doing hard work");
		flag.set(true);
		return 42;
	});
	log.info("Mono was created");
	final Integer result = work.block();
	log.info("Work is done");

	//then
	assertThat(flag).isTrue();
	assertThat(result).isEqualTo(42);
}
 
Example 2
@Test // gh-22731
public void cancelWithProtobufDecoder() throws InterruptedException {
	ProtobufDecoder decoder = new ProtobufDecoder();

	Mono<DataBuffer> input = Mono.fromCallable(() -> {
		Msg msg = Msg.newBuilder().setFoo("Foo").build();
		byte[] bytes = msg.toByteArray();
		DataBuffer buffer = this.bufferFactory.allocateBuffer(bytes.length);
		buffer.write(bytes);
		return buffer;
	});

	Flux<Message> messages = decoder.decode(input, ResolvableType.forType(Msg.class),
			new MimeType("application", "x-protobuf"), Collections.emptyMap());
	ZeroDemandMessageSubscriber subscriber = new ZeroDemandMessageSubscriber();
	messages.subscribe(subscriber);
	subscriber.cancel();
}
 
Example 3
@Override
public Mono<V1Pod> launchTask(Job job, Task task) {
    return Mono.fromCallable(() -> {
        if (nextLaunchError != null) {
            try {
                throw nextLaunchError;
            } finally {
                nextLaunchError = null;
            }
        }
        V1Pod v1Pod = new V1Pod()
                .metadata(new V1ObjectMeta()
                        .name(task.getId())
                );
        podHoldersByTaskId.put(task.getId(), v1Pod);
        return v1Pod;
    });
}
 
Example 4
Source Project: tutorials   File: AmqpReactiveController.java    License: MIT License 6 votes vote down vote up
@PostMapping(value = "/queue/{name}")
public Mono<ResponseEntity<?>> sendMessageToQueue(@PathVariable String name, @RequestBody String payload) {

    // Lookup exchange details
    final DestinationsConfig.DestinationInfo d = destinationsConfig.getQueues()
        .get(name);

    if (d == null) {
        // Destination not found.
        return Mono.just(ResponseEntity.notFound()
            .build());
    }

    return Mono.fromCallable(() -> {

        log.info("[I51] sendMessageToQueue: queue={}, routingKey={}", d.getExchange(), d.getRoutingKey());
        amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload);

        return ResponseEntity.accepted()
            .build();

    });

}
 
Example 5
private Mono<Void> dispatchNewQuota(QuotaRoot quotaRoot, Username username) {
    Mono<Quota<QuotaCountLimit, QuotaCountUsage>> messageQuota = Mono.fromCallable(() -> quotaManager.getMessageQuota(quotaRoot));
    Mono<Quota<QuotaSizeLimit, QuotaSizeUsage>> storageQuota = Mono.fromCallable(() -> quotaManager.getStorageQuota(quotaRoot));

    Mono<Tuple2<Quota<QuotaCountLimit, QuotaCountUsage>, Quota<QuotaSizeLimit, QuotaSizeUsage>>> quotasMono =
        messageQuota.zipWith(storageQuota)
            .subscribeOn(Schedulers.elastic());

    return quotasMono
        .flatMap(quotas -> eventBus.dispatch(
            EventFactory.quotaUpdated()
                .randomEventId()
                .user(username)
                .quotaRoot(quotaRoot)
                .quotaCount(quotas.getT1())
                .quotaSize(quotas.getT2())
                .instant(Instant.now())
                .build(),
            NO_REGISTRATION_KEYS));
}
 
Example 6
/**
 * Adds all labels from the request object to the target member. Labels that exist are
 * overridden. Returns the updated object.
 */
public Mono<ClusterMembershipRevision> updateMemberLabels(UpdateMemberLabelsRequest request) {
    if (!request.getMemberId().equals(localMemberId)) {
        return Mono.error(ClusterMembershipServiceException.localOnly(request.getMemberId()));
    }
    if (request.getLabelsMap().isEmpty()) {
        return Mono.fromCallable(() -> toGrpcClusterMembershipRevision(service.getLocalClusterMember(), isLocalLeader()));
    }
    return service.updateSelf(current ->
            com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision.<ClusterMember>newBuilder()
                    .withCurrent(current.toBuilder()
                            .withLabels(CollectionsExt.merge(current.getLabels(), request.getLabelsMap()))
                            .build()
                    )
                    .withCode("updated")
                    .withMessage("Added labels: " + request.getLabelsMap())
                    .withTimestamp(clock.wallTime())
                    .build()
    ).map(c -> toGrpcClusterMembershipRevision(c, isLocalLeader()));
}
 
Example 7
public Mono<MachineQueryResult> getMachines(QueryRequest request) {
    return Mono.fromCallable(() -> {
        // Copy first as `machinesById` is volatile and may change at any time.
        Map<String, Machine> machines = machinesById;
        return MachineQueryResult.newBuilder()
                .addAllItems(machines.values())
                .setPagination(Pagination.newBuilder()
                        .setCurrentPage(Page.newBuilder()
                                .setPageSize(machines.size())
                                .build()
                        )
                        .setTotalItems(machines.size())
                        .setHasMore(false)
                        .build()
                )
                .build();
    });
}
 
Example 8
@Override
public Mono<ACLDiff> updateACL(Mailbox mailbox, MailboxACL.ACLCommand mailboxACLCommand) {
    return Mono.fromCallable(() -> {
        MailboxACL oldACL = mailbox.getACL();
        MailboxACL newACL = mailbox.getACL().apply(mailboxACLCommand);
        mailboxesByPath.get(mailbox.generateAssociatedPath()).setACL(newACL);
        return ACLDiff.computeDiff(oldACL, newACL);
    });
}
 
Example 9
Source Project: requery   File: ReactorEntityStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <E extends T> Mono<E> update(final E entity, final Attribute<?, ?>... attributes) {
    return Mono.fromCallable(new Callable<E>() {
        @Override
        public E call() throws Exception {
            return delegate.update(entity, attributes);
        }
    });
}
 
Example 10
Source Project: reactor-core   File: MonoOperatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Mono<I> sourceCallable(OperatorScenario<I, Mono<I>, O, Mono<O>> scenario) {
	if(scenario.producerCount() == 0){
		return (Mono<I>)Mono.fromRunnable(() -> {});
	}
	return Mono.fromCallable(() -> scenario.producingMapper.apply(0));
}
 
Example 11
@Override
public Mono<ACLDiff> setACL(Mailbox mailbox, MailboxACL mailboxACL) {
    return Mono.fromCallable(() -> {
        MailboxACL oldAcl = mailbox.getACL();
        MaildirFolder folder = maildirStore.createMaildirFolder(mailbox);
        folder.setACL(mailboxACL);
        mailbox.setACL(mailboxACL);
        return ACLDiff.computeDiff(oldAcl, mailboxACL);
    });
}
 
Example 12
@Test
public void onlyConsidersContextDuringSubscribe() {
	Mono<TraceContext> fromMono = Mono.fromCallable(this.currentTraceContext::get);

	try (Scope ws = this.currentTraceContext.newScope(context)) {
		then(fromMono.map(context -> context).block()).isNotNull();
	}
}
 
Example 13
@Override
public Publisher<Employee> readEmployee(Integer empId) {
	
	Callable<Employee> task = () -> employeeDaoImpl.getEmployee(empId);
	Publisher<Employee> publishedEmployee = Mono.fromCallable(task);
	return publishedEmployee;
}
 
Example 14
Source Project: java-sdk   File: DaprClientGrpc.java    License: MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> Mono<T> invokeBinding(
    String name, String operation, Object data, Map<String, String> metadata, Class<T> clazz) {
  try {
    if (name == null || name.trim().isEmpty()) {
      throw new IllegalArgumentException("Binding name cannot be null or empty.");
    }

    if (operation == null || operation.trim().isEmpty()) {
      throw new IllegalArgumentException("Binding operation cannot be null or empty.");
    }

    byte[] byteData = objectSerializer.serialize(data);
    DaprProtos.InvokeBindingRequest.Builder builder = DaprProtos.InvokeBindingRequest.newBuilder()
        .setName(name).setOperation(operation);
    if (byteData != null) {
      builder.setData(ByteString.copyFrom(byteData));
    }
    if (metadata != null) {
      builder.putAllMetadata(metadata);
    }
    DaprProtos.InvokeBindingRequest envelope = builder.build();
    return Mono.fromCallable(() -> {
      ListenableFuture<DaprProtos.InvokeBindingResponse> futureResponse = client.invokeBinding(envelope);
      return objectSerializer.deserialize(futureResponse.get().getData().toByteArray(), clazz);
    });
  } catch (Exception ex) {
    return Mono.error(ex);
  }
}
 
Example 15
public Mono<Machine> getMachine(Id request) {
    return Mono.fromCallable(() -> {
        Machine machine = machinesById.get(request.getId());
        if (machine == null) {
            throw new IllegalArgumentException(String.format("Machine with id %s not found", request.getId()));
        }
        return machine;
    });
}
 
Example 16
Source Project: james-project   File: MailboxFactory.java    License: Apache License 2.0 4 votes vote down vote up
private Mono<MessageManager> mailbox(MailboxId mailboxId) {
    return Mono.fromCallable(() -> mailboxFactory.mailboxManager.getMailbox(mailboxId, session));
}
 
Example 17
Source Project: james-project   File: MessageMapper.java    License: Apache License 2.0 4 votes vote down vote up
default Mono<MailboxCounters> getMailboxCountersReactive(Mailbox mailbox) {
    return Mono.fromCallable(() -> getMailboxCounters(mailbox));
}
 
Example 18
private Mono<Channel> tryBorrowFromPool() {
    return Mono.fromCallable(this::borrowFromPool);
}
 
Example 19
@Override
public Mono<Duration> getRemaining() {
    return Mono.fromCallable(() -> Duration.ofNanos(limitedUntil - System.nanoTime()));
}
 
Example 20
/**
 * socket responder handler as SocketAcceptor bean.
 * To validate connection, please use RSocketListenerCustomizer and add AcceptorInterceptor by addSocketAcceptorInterceptor api
 *
 * @param serviceCaller  service caller
 * @param eventProcessor event processor
 * @return handler factor
 */
@Bean
@ConditionalOnMissingBean(type = {"brave.Tracing", "com.alibaba.rsocket.listen.RSocketResponderHandlerFactory"})
public RSocketResponderHandlerFactory rsocketResponderHandlerFactory(@Autowired LocalReactiveServiceCaller serviceCaller,
                                                                     @Autowired @Qualifier("reactiveCloudEventProcessor") TopicProcessor<CloudEventImpl> eventProcessor) {
    return (setupPayload, requester) -> Mono.fromCallable(() -> new RSocketResponderHandler(serviceCaller, eventProcessor, requester, setupPayload));
}