reactor.core.publisher.FluxSink Java Examples

The following examples show how to use reactor.core.publisher.FluxSink. 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: ReactorCallAdapter.java    From retrofit2-reactor-adapter with Apache License 2.0 9 votes vote down vote up
@Override public Object adapt(Call<R> call) {
  Consumer<FluxSink<Response<R>>> consumer = isAsync
      ? new EnqueueSinkConsumer<>(call)
      : new ExecuteSinkConsumer<>(call);
  Flux<Response<R>> responseFlux = Flux.create(consumer, LATEST);

  Flux<?> flux;
  if (isResult) {
    flux = new ResultFlux<>(responseFlux);
  } else if (isBody) {
    flux = new BodyFlux<>(responseFlux);
  } else {
    flux = responseFlux;
  }

  if (scheduler != null) {
    flux = flux.subscribeOn(scheduler);
  }

  if (isMono) {
    return flux.single();
  }
  return flux;
}
 
Example #2
Source File: ElementsStream.java    From redisson with Apache License 2.0 6 votes vote down vote up
private static <V> void take(final Callable<RFuture<V>> factory, final FluxSink<V> emitter, final AtomicLong counter, final AtomicReference<RFuture<V>> futureRef) {
    RFuture<V> future;
    try {
        future = factory.call();
    } catch (Exception e) {
        emitter.error(e);
        return;
    }
    futureRef.set(future);
    future.onComplete((res, e) -> {
        if (e != null) {
            emitter.error(e);
            return;
        }
        
        emitter.next(res);
        if (counter.decrementAndGet() == 0) {
            emitter.complete();
        }
        
        take(factory, emitter, counter, futureRef);
    });
}
 
Example #3
Source File: OriginsReloadCommandHandler.java    From styx with Apache License 2.0 6 votes vote down vote up
private void reload(FluxSink<? super HttpResponse> subscriber) {
    backendServicesRegistry.reload()
        .handle((result, exception) -> {
            if (exception == null) {
                if (result.outcome() == RELOADED) {
                    subscriber.next(okResponse("Origins reloaded successfully.\n"));
                    subscriber.complete();
                } else if (result.outcome() == UNCHANGED) {
                    subscriber.next(okResponse(format("Origins were not reloaded because %s.\n", result.message())));
                    subscriber.complete();
                } else {
                    subscriber.error(mapError(result));
                }
            } else {
                subscriber.next(errorResponse(exception));
                subscriber.complete();
            }
            return null;
        });
}
 
Example #4
Source File: GrpcMetaProcessor.java    From milkman with MIT License 6 votes vote down vote up
protected void fetchServiceList(FluxSink<String> sink, GrpcRequestContainer request) {
	ManagedChannel channel = createChannel(request);
    var client = ServerReflectionClient.create(channel);

    
    Futures.addCallback(client.listServices(), new FutureCallback<>() {

		@Override
		public void onSuccess(ImmutableList<String> result) {
			result.forEach(sink::next);
			channel.shutdown();
			sink.complete();
		}

		@Override
		public void onFailure(Throwable t) {
			t.printStackTrace();
			channel.shutdown();
			sink.error(t);
		}
	}, executor);
}
 
Example #5
Source File: GenericEvent.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private FluxSink<T> removeStream(ObjectIdentifier objectIdentifier)
{
    FluxSink<T> sink;

    lock.lock();
    try
    {
        sink = sinks.remove(objectIdentifier);
        if (sink != null)
        {
            eventStreamStore.removeEventStream(new EventIdentifier(null, objectIdentifier));
            streams.remove(objectIdentifier);
        }
    }
    finally
    {
        lock.unlock();
    }

    return sink;
}
 
Example #6
Source File: TcpConnectorPeer.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void connectionClosing()
{
    connected = false;
    authenticated = false;

    // deactivate all interest in READ or WRITE operations
    setOpInterest(0);

    synchronized (openRpcs)
    {
        // preventing ConcurrentModificationException with "#apiCall's fluxSink.onDispose(...openRpcs.remove(...))
        Set<FluxSink<ByteArrayInputStream>> copyOpenRpcsSet = new HashSet<>(openRpcs.values());
        for (FluxSink<ByteArrayInputStream> rpcSink : copyOpenRpcsSet)
        {
            rpcSink.error(new PeerNotConnectedException());
        }
        openRpcs.clear(); // basically no-op, more for documentation purpose
    }
}
 
Example #7
Source File: AbstractServiceBaseReactor.java    From rest-example with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all the entities.
 *
 * @return Flux that will receive the found entities or error.
 */
@Transactional(readOnly = true)
public Flux<E> findAll() {
    return Flux.create((Consumer<FluxSink<E>>) theFluxSink -> {
        try {
            LOGGER.info("Retrieving all entities.");

            final List<E> theAllEntities = mRepository.findAll();
            for (final E theEntity : theAllEntities) {
                theFluxSink.next(theEntity);
            }
            theFluxSink.complete();
        } catch (final Throwable theException) {
            theFluxSink.error(theException);
        }
    })
        .subscribeOn(Schedulers.parallel());
}
 
Example #8
Source File: DeviceManagerImpl.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private void markPendingRscDispatch(
    UpdateNotification updateNotification,
    Set<ResourceName> rscSet
)
{
    List<FluxSink<ApiCallRc>> responseSink = updateNotification == null ?
        Collections.emptyList() :
        updateNotification.getResponseSinks();
    for (ResourceName rscName : rscSet)
    {
        List<FluxSink<ApiCallRc>> responseSinks =
            pendingDispatchRscs.computeIfAbsent(rscName, ignored -> new ArrayList<>());
        responseSinks.addAll(responseSink);
    }
    pendingResponseSinks.addAll(responseSink);
}
 
Example #9
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testBackPressure() throws Exception {
    Flux<Integer> numberGenerator = Flux.create(x -> {
        System.out.println("Requested Events :" + x.requestedFromDownstream());
        int number = 1;
        while (number < 100) {
            x.next(number);
            number++;
        }
        x.complete();
    }, FluxSink.OverflowStrategy.ERROR);

    StepVerifier.create(numberGenerator, 1L)
            .thenConsumeWhile(x -> x >= 0)
            .expectError()
            .verifyThenAssertThat()
            .hasDroppedElements();
}
 
Example #10
Source File: CommandHelper.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * Return a Publisher of type T out of the the hystrix command.
 *
 * @param clazz the wanted stream type.
 * @param mapper the object mapper used to parse objects.
 * @param command the hystrix command to deal with.
 * @param <T> the type of objects to stream.
 * @return a Publisher<T></T> out of the hystrix command response body.
 */
public static <T> Publisher<T> toPublisher(final Class<T> clazz, final ObjectMapper mapper,
        final HystrixCommand<InputStream> command) {
    AtomicInteger count = new AtomicInteger(0);
    return Flux.create(sink -> {
        final Observable<InputStream> observable = command.toObservable();
        observable
                .map(i -> {
                    try {
                        return mapper.readerFor(clazz).<T> readValues(i);
                    } catch (IOException e) {
                        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
                    }
                }) //
                .doOnCompleted(() -> LOGGER.debug("Completed command '{}' (emits '{}') with '{}' records.",
                        command.getClass().getName(), clazz.getName(), count.get())) //
                .toBlocking() //
                .forEach(s -> {
                    while (s.hasNext()) {
                        sink.next(s.next());
                        count.incrementAndGet();
                    }
                    sink.complete();
                });
    }, FluxSink.OverflowStrategy.BUFFER);
}
 
Example #11
Source File: ProcessorRequestQueueFactory.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public <T> RequestQueue<T> create() {
    return new RequestQueue<T>() {

        private final FluxProcessor<Object, Object> processor = processorSupplier.get();
        private final FluxSink<Object> sink = processor.sink(FluxSink.OverflowStrategy.BUFFER);

        @Override
        public void push(T request) {
            sink.next(request);
        }

        @SuppressWarnings("unchecked")
        @Override
        public Flux<T> requests() {
            return (Flux<T>) Flux.create(sink -> processor.subscribe(sink::next), overflowStrategy);
        }
    };
}
 
Example #12
Source File: StatsdFunctionTimer.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdFunctionTimer(Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction,
                    TimeUnit totalTimeFunctionUnit, TimeUnit baseTimeUnit,
                    StatsdLineBuilder lineBuilder, FluxSink<String> sink) {
    super(id, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit, baseTimeUnit);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
Example #13
Source File: FluxSinkApplication.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
Consumer<String> distributeEvent(final List<FluxSink<ServerSentEvent<Map>>> subscribers) {
  return message -> subscribers.forEach(fluxSink -> fluxSink.next(ServerSentEvent.<Map>builder()
                                                                      .id(UUID.randomUUID().toString())
                                                                      .data(singletonMap("payload", message))
                                                                      //.data(HashMap.of(
                                                                      //    "payload", message,
                                                                      //    "at", Instant.now()
                                                                      //).toJavaMap())
                                                                      .event("message")
                                                                      .build()));
}
 
Example #14
Source File: StatsdTimer.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdTimer(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, Clock clock,
            DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector, TimeUnit baseTimeUnit, long stepMillis) {
    super(id, clock, distributionStatisticConfig, pauseDetector, baseTimeUnit, false);
    this.max = new StepDouble(clock, stepMillis);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
Example #15
Source File: ReactorHeadTransformer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private boolean drainBuffer(FluxSink<T> emitter, Queue<Object> buffer) {
    for (Object next = buffer.poll(); !emitter.isCancelled() && next != null; next = buffer.poll()) {
        if (next == END_OF_STREAM_MARKER) {
            return false;
        }
        if (next instanceof ErrorWrapper) {
            emitter.error(((ErrorWrapper) next).cause);
            return false;
        }
        emitter.next((T) next);
    }
    return true;
}
 
Example #16
Source File: StatsdDistributionSummary.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdDistributionSummary(Meter.Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, Clock clock,
                          DistributionStatisticConfig distributionStatisticConfig, double scale) {
    super(id, clock, distributionStatisticConfig, scale, false);
    this.max = new TimeWindowMax(clock, distributionStatisticConfig);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
Example #17
Source File: StatsdGauge.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdGauge(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, @Nullable T obj, ToDoubleFunction<T> value, boolean alwaysPublish) {
    super(id);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
    this.ref = new WeakReference<>(obj);
    this.value = value;
    this.alwaysPublish = alwaysPublish;
}
 
Example #18
Source File: HttpSendFileTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
TestCompletionHandler(AsynchronousFileChannel channel, FluxSink<ByteBuf> sink,
					  ByteBufAllocator allocator, int chunk) {
	this.channel = channel;
	this.sink = sink;
	this.allocator = allocator;
	this.chunk = chunk;
}
 
Example #19
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
CommentService(ObjectMapper mapper) {
	this.mapper = mapper;
	this.flux = Flux.<Comment>create(
		emitter -> this.webSocketCommentSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
		.publish()
		.autoConnect();
}
 
Example #20
Source File: RequestsToOriginMetricsCollectorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
private EmbeddedChannel buildEmbeddedChannel() {
    ApplicationMetrics appMetrics = new ApplicationMetrics(this.origin.applicationId(), this.metricRegistry);
    OriginMetrics originMetrics = new OriginMetrics(appMetrics, originPrefix(this.origin));

    return new EmbeddedChannel(
            new HttpClientCodec(),
            new RequestsToOriginMetricsCollector(originMetrics),
            new NettyToStyxResponsePropagator(mock(FluxSink.class), this.origin)
    );
}
 
Example #21
Source File: CommentController.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
public CommentController(MeterRegistry meterRegistry) {
	this.meterRegistry = meterRegistry;
	this.flux = Flux.<Message<Comment>>create(
		emitter -> this.commentSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
		.publish()
		.autoConnect();
}
 
Example #22
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
public OutboundChatService() {
	this.flux = Flux.<Message<String>>create(
		emitter -> this.chatMessageSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
		.publish()
		.autoConnect();
}
 
Example #23
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
CommentService(ObjectMapper mapper) {
	this.mapper = mapper;
	this.flux = Flux.<Comment>create(
		emitter -> this.webSocketCommentSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
		.publish()
		.autoConnect();
}
 
Example #24
Source File: HttpRequestOperation.java    From styx with Apache License 2.0 5 votes vote down vote up
private void addProxyBridgeHandlers(NettyConnection nettyConnection, FluxSink<LiveHttpResponse> sink) {
    Origin origin = nettyConnection.getOrigin();
    Channel channel = nettyConnection.channel();
    channel.pipeline().addLast(IDLE_HANDLER_NAME, new IdleStateHandler(0, 0, responseTimeoutMillis, MILLISECONDS));
    originStatsFactory.ifPresent(
            originStatsFactory -> channel.pipeline()
                    .addLast(RequestsToOriginMetricsCollector.NAME,
                            new RequestsToOriginMetricsCollector(originStatsFactory.originStats(origin))));
    channel.pipeline().addLast(
            NettyToStyxResponsePropagator.NAME,
            new NettyToStyxResponsePropagator(sink, origin, responseTimeoutMillis, MILLISECONDS, request));
}
 
Example #25
Source File: HttpRequestOperation.java    From styx with Apache License 2.0 5 votes vote down vote up
private WriteRequestToOrigin(FluxSink<LiveHttpResponse> responseFromOriginFlux, NettyConnection nettyConnection, LiveHttpRequest request,
                             RequestBodyChunkSubscriber requestBodyChunkSubscriber) {
    this.responseFromOriginFlux = responseFromOriginFlux;
    this.nettyConnection = nettyConnection;
    this.request = request;
    this.requestBodyChunkSubscriber = requestBodyChunkSubscriber;
}
 
Example #26
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
CommentService(ObjectMapper mapper) {
	this.mapper = mapper;
	this.flux = Flux.<Comment>create(
		emitter -> this.webSocketCommentSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
			.publish()
			.autoConnect();
}
 
Example #27
Source File: CommentController.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
public CommentController(MeterRegistry meterRegistry) {
	this.meterRegistry = meterRegistry;
	this.flux = Flux.<Message<Comment>>create(
		emitter -> this.commentSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
		.publish()
		.autoConnect();
}
 
Example #28
Source File: NettyToStyxResponsePropagator.java    From styx with Apache License 2.0 5 votes vote down vote up
NettyToStyxResponsePropagator(FluxSink<LiveHttpResponse> sink,
                              Origin origin,
                              long idleTimeout,
                              TimeUnit timeUnit,
                              LiveHttpRequest request) {
    this.sink = sink;
    this.origin = origin;
    this.idleTimeoutMillis = timeUnit.toMillis(idleTimeout);
    this.request = request;
}
 
Example #29
Source File: NettyToStyxResponsePropagatorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReleaseAlreadyReadBufferInCaseOfChannelGetsInactive() throws Exception {
    FluxSink subscriber = mock(FluxSink.class);
    EmbeddedChannel channel = new EmbeddedChannel(new NettyToStyxResponsePropagator(subscriber, SOME_ORIGIN));
    channel.writeInbound(new DefaultHttpResponse(HTTP_1_1, OK));

    HttpContent httpContentOne = newHttpContent("first chunk");
    channel.writeInbound(httpContentOne);

    channel.pipeline().fireChannelInactive();

    assertThat(httpContentOne.refCnt(), is(0));
}
 
Example #30
Source File: CommentController.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
public CommentController(MeterRegistry meterRegistry) {
	this.meterRegistry = meterRegistry;
	this.flux = Flux.<Message<Comment>>create(
		emitter -> this.commentSink = emitter,
		FluxSink.OverflowStrategy.IGNORE)
		.publish()
		.autoConnect();
}