Java Code Examples for reactor.core.publisher.Flux#empty()
The following examples show how to use
reactor.core.publisher.Flux#empty() .
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: ServerSentEventHttpMessageWriter.java From java-technology-stack with MIT License | 6 votes |
@SuppressWarnings("unchecked") private <T> Flux<DataBuffer> encodeData(@Nullable T data, ResolvableType valueType, MediaType mediaType, DataBufferFactory factory, Map<String, Object> hints) { if (data == null) { return Flux.empty(); } if (data instanceof String) { String text = (String) data; return Flux.from(encodeText(StringUtils.replace(text, "\n", "\ndata:") + "\n", mediaType, factory)); } if (this.encoder == null) { return Flux.error(new CodecException("No SSE encoder configured and the data is not String.")); } return ((Encoder<T>) this.encoder) .encode(Mono.just(data), factory, valueType, mediaType, hints) .concatWith(encodeText("\n", mediaType, factory)); }
Example 2
Source File: TopicMessageServiceImpl.java From hedera-mirror-node with Apache License 2.0 | 6 votes |
private Flux<TopicMessage> incomingMessages(TopicContext topicContext) { if (topicContext.isComplete()) { return Flux.empty(); } TopicMessageFilter filter = topicContext.getFilter(); TopicMessage last = topicContext.getLastTopicMessage(); long limit = filter.hasLimit() ? filter.getLimit() - topicContext.getCount().get() : 0; Instant startTime = last != null ? last.getConsensusTimestampInstant().plusNanos(1) : filter.getStartTime(); TopicMessageFilter newFilter = filter.toBuilder() .limit(limit) .startTime(startTime) .build(); return topicListener.listen(newFilter) .takeUntilOther(pastEndTime(topicContext)) .concatMap(t -> missingMessages(topicContext, t)); }
Example 3
Source File: GrpcAgentReplicatorEventStream.java From titus-control-plane with Apache License 2.0 | 6 votes |
private Flux<ReplicatorEvent<AgentSnapshot, AgentEvent>> processSnapshotUpdate(AgentEvent event) { logger.debug("Processing agent snapshot update event: {}", event); AgentSnapshot lastSnapshot = lastAgentSnapshotRef.get(); Optional<AgentSnapshot> newSnapshot; if (event instanceof AgentInstanceGroupUpdateEvent) { newSnapshot = lastSnapshot.updateInstanceGroup(((AgentInstanceGroupUpdateEvent) event).getAgentInstanceGroup()); } else if (event instanceof AgentInstanceGroupRemovedEvent) { newSnapshot = lastSnapshot.removeInstanceGroup(((AgentInstanceGroupRemovedEvent) event).getInstanceGroupId()); } else if (event instanceof AgentInstanceUpdateEvent) { newSnapshot = lastSnapshot.updateInstance(((AgentInstanceUpdateEvent) event).getAgentInstance()); } else if (event instanceof AgentInstanceRemovedEvent) { newSnapshot = lastSnapshot.removeInstance(((AgentInstanceRemovedEvent) event).getAgentInstanceId()); } else { newSnapshot = Optional.empty(); } if (newSnapshot.isPresent()) { lastAgentSnapshotRef.set(newSnapshot.get()); return Flux.just(new ReplicatorEvent<>(newSnapshot.get(), event, titusRuntime.getClock().wallTime())); } return Flux.empty(); }
Example 4
Source File: CtrlRscAutoTieBreakerHelper.java From linstor-server with GNU General Public License v3.0 | 6 votes |
private Flux<ApiCallRc> setTiebreakerFlagInTransaction(Resource tiebreakerRef, ResponseContext contextRef) { try { tiebreakerRef.getStateFlags().enableFlags(peerCtx.get(), Resource.Flags.TIE_BREAKER); ctrlTransactionHelper.commit(); } catch (AccessDeniedException accDeniedExc) { throw new ApiAccessDeniedException( accDeniedExc, "marking resource as tiebreaker " + tiebreakerRef, ApiConsts.FAIL_ACC_DENIED_RSC ); } catch (DatabaseException exc) { throw new ApiDatabaseException(exc); } return Flux.empty(); }
Example 5
Source File: ElasticSearchSearcher.java From james-project with Apache License 2.0 | 6 votes |
private Flux<MessageSearchIndex.SearchResult> extractContentFromHit(SearchHit hit) { DocumentField mailboxId = hit.field(JsonMessageConstants.MAILBOX_ID); DocumentField uid = hit.field(JsonMessageConstants.UID); Optional<DocumentField> id = retrieveMessageIdField(hit); if (mailboxId != null && uid != null) { Number uidAsNumber = uid.getValue(); return Flux.just( new MessageSearchIndex.SearchResult( id.map(field -> messageIdFactory.fromString(field.getValue())), mailboxIdFactory.fromString(mailboxId.getValue()), MessageUid.of(uidAsNumber.longValue()))); } else { LOGGER.warn("Can not extract UID, MessageID and/or MailboxId for search result {}", hit.getId()); return Flux.empty(); } }
Example 6
Source File: CtrlAuthenticator.java From linstor-server with GNU General Public License v3.0 | 6 votes |
private Flux<ApiCallRc> processAuthResponse(Node node, ByteArrayInputStream inputStream) { Flux<ApiCallRc> authResponseFlux; Peer peer = getPeerPrivileged(node); try { authResponseFlux = intAuthResponse .executeReactive( peer, inputStream, true ); } catch (IOException ioExc) { errorReporter.reportError( ioExc, apiCtx, peer, "An IO exception occurred while parsing the authentication response" ); authResponseFlux = Flux.empty(); } return authResponseFlux; }
Example 7
Source File: VertxClientHttpResponseTest.java From vertx-spring-boot with Apache License 2.0 | 5 votes |
@Test public void shouldGetStatusCode() { given(mockDelegate.statusCode()).willReturn(200); VertxClientHttpResponse response = new VertxClientHttpResponse(mockDelegate, Flux.empty()); HttpStatus status = response.getStatusCode(); assertThat(status).isEqualTo(HttpStatus.OK); }
Example 8
Source File: CtrlVlmDfnModifyApiCallHandler.java From linstor-server with GNU General Public License v3.0 | 5 votes |
private Flux<ApiCallRc> resizeDrbdInTransaction(ResourceName rscName, VolumeNumber vlmNr) { VolumeDefinition vlmDfn = ctrlApiDataLoader.loadVlmDfn(rscName, vlmNr, false); Flux<ApiCallRc> flux; if (vlmDfn == null) { flux = Flux.empty(); } else { Optional<Volume> drbdResizeVlm = streamVolumesPrivileged(vlmDfn) .filter(this::isDrbdDiskful) .findAny(); drbdResizeVlm.ifPresent(this::markVlmDrbdResize); ctrlTransactionHelper.commit(); Flux<ApiCallRc> nextStep = finishResize(rscName, vlmNr); flux = ctrlSatelliteUpdateCaller.updateSatellites(vlmDfn.getResourceDefinition(), nextStep) .transform( updateResponses -> CtrlResponseUtils.combineResponses( updateResponses, rscName, getNodeNames(drbdResizeVlm), "Resized DRBD resource {1} on {0}", null ) ) .concatWith(nextStep); } return flux; }
Example 9
Source File: CtrlVlmDfnDeleteApiCallHandler.java From linstor-server with GNU General Public License v3.0 | 5 votes |
private Flux<ApiCallRc> deleteDataInTransaction(ResourceName rscName, VolumeNumber vlmNr) { VolumeDefinition vlmDfn = ctrlApiDataLoader.loadVlmDfn(rscName, vlmNr, false); Flux<ApiCallRc> flux; if (vlmDfn == null) { flux = Flux.empty(); } else { UUID vlmDfnUuid = vlmDfn.getUuid(); String descriptionFirstLetterCaps = firstLetterCaps(getVlmDfnDescriptionInline(vlmDfn)); deletePrivileged(vlmDfn); ctrlTransactionHelper.commit(); flux = Flux.just(ApiCallRcImpl.singletonApiCallRc(ApiCallRcImpl .entryBuilder(ApiConsts.DELETED, descriptionFirstLetterCaps + " deleted.") .setDetails(descriptionFirstLetterCaps + " UUID was: " + vlmDfnUuid) .build() )); } return flux; }
Example 10
Source File: GrpcJobReplicatorEventStream.java From titus-control-plane with Apache License 2.0 | 5 votes |
private Flux<ReplicatorEvent<JobSnapshot, JobManagerEvent<?>>> onEvent(JobManagerEvent<?> event) { try { if (lastJobSnapshotRef.get() != null) { return processCacheUpdate(event); } if (event.equals(JobManagerEvent.snapshotMarker())) { return buildInitialCache(); } if (event instanceof JobUpdateEvent) { JobUpdateEvent jobUpdateEvent = (JobUpdateEvent) event; Job job = jobUpdateEvent.getCurrent(); if (job.getStatus().getState() != JobState.Finished) { snapshotEvents.add(event); } } else if (event instanceof TaskUpdateEvent) { TaskUpdateEvent taskUpdateEvent = (TaskUpdateEvent) event; Task task = taskUpdateEvent.getCurrentTask(); if (task.getStatus().getState() != TaskState.Finished) { snapshotEvents.add(event); } } } catch (Exception e) { logger.warn("Unexpected error when handling the job change notification: {}", event, e); return Flux.error(e); // Return error to force the cache reconnect. } return Flux.empty(); }
Example 11
Source File: EurekaContainerHealthService.java From titus-control-plane with Apache License 2.0 | 5 votes |
private Flux<ContainerHealthEvent> handleJobManagerEvent(JobManagerEvent event, ConcurrentMap<String, ContainerHealthEvent> state) { if (event instanceof JobUpdateEvent) { JobUpdateEvent jobUpdateEvent = (JobUpdateEvent) event; return jobUpdateEvent.getPrevious() .map(previous -> handleJobEnabledStatusUpdate(jobUpdateEvent.getCurrent(), previous, state)) .orElse(Flux.empty()); } else if (event instanceof TaskUpdateEvent) { TaskUpdateEvent taskEvent = (TaskUpdateEvent) event; return handleTaskStateUpdate(taskEvent.getCurrentJob(), taskEvent.getCurrentTask(), state).map(Flux::just).orElse(Flux.empty()); } return Flux.empty(); }
Example 12
Source File: CloudControllerRestClientImpl.java From cf-java-client-sap with Apache License 2.0 | 5 votes |
private Flux<? extends Resource<ApplicationEntity>> getApplicationResourcesByNames(Collection<String> names) { if (names.isEmpty()) { return Flux.empty(); } IntFunction<ListSpaceApplicationsRequest> pageRequestSupplier = page -> ListSpaceApplicationsRequest.builder() .spaceId(getTargetSpaceGuid().toString()) .addAllNames(names) .page(page) .build(); return PaginationUtils.requestClientV2Resources(page -> delegate.spaces() .listApplications(pageRequestSupplier.apply(page))); }
Example 13
Source File: StringDecoderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void decodeToMonoWithEmptyFlux() { Flux<DataBuffer> input = Flux.empty(); testDecodeToMono(input, String.class, step -> step .expectComplete() .verify()); }
Example 14
Source File: R011_LetsMeetFlux.java From reactor-workshop with GNU General Public License v3.0 | 5 votes |
@Test public void emptyFlux() throws Exception { //given final Flux<String> reactor = Flux.empty(); //when final List<String> value = reactor.collectList().block(); //then assertThat(value).isEmpty(); }
Example 15
Source File: ZookeeperReactiveDiscoveryClient.java From spring-cloud-zookeeper with Apache License 2.0 | 5 votes |
private Function<String, Publisher<org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>>> getInstancesFromZookeeper() { return service -> { try { return Flux.fromIterable(serviceDiscovery.queryForInstances(service)); } catch (Exception e) { logger.error("Error getting instances from zookeeper. Possibly, no service has registered.", e); return Flux.empty(); } }; }
Example 16
Source File: ImageService.java From Learning-Spring-Boot-2.0-Second-Edition with MIT License | 5 votes |
public Flux<Image> findAllImages() { try { return Flux.fromIterable( Files.newDirectoryStream(Paths.get(UPLOAD_ROOT))) .map(path -> new Image(path.hashCode(), path.getFileName().toString())); } catch (IOException e) { return Flux.empty(); } }
Example 17
Source File: LiveHttpRequest.java From styx with Apache License 2.0 | 4 votes |
/** * Creates a new {@link Builder} object with default attributes. */ public Builder() { this.url = Url.Builder.url("/").build(); this.headers = new HttpHeaders.Builder(); this.body = new ByteStream(Flux.empty()); }
Example 18
Source File: HouseSnapshots.java From reactor-workshop with GNU General Public License v3.0 | 4 votes |
/** * TODO Implement, make sure it's lazy */ public Flux<HouseSnapshot> stream() { return Flux.empty(); }
Example 19
Source File: CommonMessageProcessor.java From linstor-server with GNU General Public License v3.0 | 4 votes |
private Flux<?> handleDataMessage( final Message msg, final TcpConnector connector, final Peer peer, long peerSeq ) throws IllegalMessageStateException, IOException { Flux<?> flux = Flux.empty(); byte[] msgData = msg.getData(); ByteArrayInputStream msgDataIn = new ByteArrayInputStream(msgData); MsgHeaderOuterClass.MsgHeader header = MsgHeaderOuterClass.MsgHeader.parseDelimitedFrom(msgDataIn); if (header != null) { MsgType msgType = header.getMsgType(); switch (msgType) { case ONEWAY: // fall-through case API_CALL: flux = callApi(connector, peer, header, msgDataIn, msgType == MsgType.API_CALL, peerSeq); break; case ANSWER: handleAnswer(peer, header, msgDataIn, peerSeq); break; case COMPLETE: handleComplete(peer, header, peerSeq); break; default: errorLog.logError( "Message of unknown type " + msgType + " received" ); break; } } else { errorLog.logError( "Message didn't contain a header: " + msg.toString() + " from " + peer.getId() ); } return flux; }
Example 20
Source File: QueryFlow.java From r2dbc-mysql with Apache License 2.0 | 4 votes |
/** * Execute multiple bindings of a prepared statement with one-by-one. Query execution terminates with * the last {@link CompleteMessage} or a {@link ErrorMessage}. The {@link ErrorMessage} will emit an * exception and cancel subsequent bindings execution. * <p> * It will not close this prepared statement. * * @param client the {@link Client} to exchange messages with. * @param context the connection context. * @param sql the original statement for exception tracing. * @param identifier the statement identifier want to execute. * @param deprecateEof EOF has been deprecated. * @param fetchSize the size of fetching, if it less than or equal to {@literal 0} means fetch all rows. * @param bindings the data of bindings. * @return the messages received in response to this exchange, and will be completed * by {@link CompleteMessage} when it is last result for each binding. */ static Flux<Flux<ServerMessage>> execute( Client client, ConnectionContext context, String sql, PreparedIdentifier identifier, boolean deprecateEof, int fetchSize, List<Binding> bindings ) { switch (bindings.size()) { case 1: // Most case. return Flux.defer(() -> execute0(client, context, sql, identifier, deprecateEof, bindings.get(0), fetchSize) .windowUntil(RESULT_DONE)); case 0: return Flux.empty(); default: Iterator<Binding> iterator = bindings.iterator(); EmitterProcessor<Binding> processor = EmitterProcessor.create(1, true); Runnable complete = () -> { if (processor.isCancelled() || processor.isTerminated()) { return; } try { if (iterator.hasNext()) { if (identifier.isClosed()) { // User cancelled fetching, discard subsequent bindings. Binding.clearSubsequent(iterator); processor.onComplete(); } else { processor.onNext(iterator.next()); } } else { processor.onComplete(); } } catch (Throwable e) { processor.onError(e); } }; processor.onNext(iterator.next()); // One binding may be leak when a emitted Result has been ignored, but Result should never be ignored. // Subsequent bindings will auto-clear if subscribing has been cancelled. return processor.concatMap(it -> execute0(client, context, sql, identifier, deprecateEof, it, fetchSize).doOnComplete(complete)) .doOnCancel(() -> Binding.clearSubsequent(iterator)) .doOnError(ignored -> Binding.clearSubsequent(iterator)) .windowUntil(RESULT_DONE); } }