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

The following examples show how to use reactor.core.publisher.Mono#fromCallable() . 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: R020_MonoSubscribing.java    From reactor-workshop with GNU General Public License v3.0 8 votes vote down vote up
/**
 * 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
Source File: CancelWithoutDemandCodecTests.java    From spring-analysis-note with MIT License 7 votes vote down vote up
@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
Source File: StubbedDirectKubeApiServerIntegrator.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@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 File: ReactorMasterMachineGrpcService.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
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 5
Source File: ReactorClusterMembershipGrpcService.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
Source File: ListeningCurrentQuotaUpdater.java    From james-project with Apache License 2.0 6 votes vote down vote up
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 7
Source File: AmqpReactiveController.java    From tutorials with 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 8
Source File: InMemoryMailboxMapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@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 File: ReactorEntityStore.java    From requery with 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 File: MonoOperatorTest.java    From reactor-core with 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
Source File: MaildirMailboxMapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@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
Source File: ScopePassingSpanSubscriberSpringBootTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@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
Source File: EmployeeStreamServiceImpl.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public Publisher<Employee> readEmployee(Integer empId) {
	
	Callable<Employee> task = () -> employeeDaoImpl.getEmployee(empId);
	Publisher<Employee> publishedEmployee = Mono.fromCallable(task);
	return publishedEmployee;
}
 
Example 14
Source File: DaprClientGrpc.java    From java-sdk with 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
Source File: ReactorMasterMachineGrpcService.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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 File: ReactorRabbitMQChannelPool.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Mono<Channel> tryBorrowFromPool() {
    return Mono.fromCallable(this::borrowFromPool);
}
 
Example 17
Source File: MessageMapper.java    From james-project with Apache License 2.0 4 votes vote down vote up
default Mono<MailboxCounters> getMailboxCountersReactive(Mailbox mailbox) {
    return Mono.fromCallable(() -> getMailboxCounters(mailbox));
}
 
Example 18
Source File: UnboundedGlobalRateLimiter.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Mono<Duration> getRemaining() {
    return Mono.fromCallable(() -> Duration.ofNanos(limitedUntil - System.nanoTime()));
}
 
Example 19
Source File: MailboxFactory.java    From james-project with 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 20
Source File: RSocketAutoConfiguration.java    From alibaba-rsocket-broker with Apache License 2.0 3 votes vote down vote up
/**
 * 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));
}