reactor.core.publisher.UnicastProcessor Java Examples

The following examples show how to use reactor.core.publisher.UnicastProcessor. 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: MultipartHttpMessageWriterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // SPR-16402
public void singleSubscriberWithStrings() {
	UnicastProcessor<String> processor = UnicastProcessor.create();
	Flux.just("foo", "bar", "baz").subscribe(processor);

	MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
	bodyBuilder.asyncPart("name", processor, String.class);

	Mono<MultiValueMap<String, HttpEntity<?>>> result = Mono.just(bodyBuilder.build());

	this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, Collections.emptyMap())
			.block(Duration.ofSeconds(5));

	// Make sure body is consumed to avoid leak reports
	this.response.getBodyAsString().block(Duration.ofSeconds(5));
}
 
Example #2
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testChannelRequestServerSideCancellation() {
  MonoProcessor<Payload> cancelled = MonoProcessor.create();
  UnicastProcessor<Payload> request = UnicastProcessor.create();
  request.onNext(EmptyPayload.INSTANCE);
  rule.socket.requestChannel(request).subscribe(cancelled);
  int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL);
  rule.connection.addToReceivedBuffer(CancelFrameCodec.encode(rule.alloc(), streamId));
  rule.connection.addToReceivedBuffer(PayloadFrameCodec.encodeComplete(rule.alloc(), streamId));
  Flux.first(
          cancelled,
          Flux.error(new IllegalStateException("Channel request not cancelled"))
              .delaySubscription(Duration.ofSeconds(1)))
      .blockFirst();

  Assertions.assertThat(request.isDisposed()).isTrue();
  Assertions.assertThat(rule.connection.getSent())
      .hasSize(1)
      .first()
      .matches(bb -> frameType(bb) == REQUEST_CHANNEL)
      .matches(ReferenceCounted::release);
  rule.assertHasNoLeaks();
}
 
Example #3
Source File: RabbitMQTerminationSubscriber.java    From james-project with Apache License 2.0 6 votes vote down vote up
public void start() {
    sender.declareExchange(ExchangeSpecification.exchange(EXCHANGE_NAME)).block();
    sender.declare(QueueSpecification.queue(queueName).durable(false).autoDelete(true)).block();
    sender.bind(BindingSpecification.binding(EXCHANGE_NAME, ROUTING_KEY, queueName)).block();
    sendQueue = UnicastProcessor.create();
    sendQueueHandle = sender
        .send(sendQueue)
        .subscribeOn(Schedulers.elastic())
        .subscribe();

    listenerReceiver = receiverProvider.createReceiver();
    listener = DirectProcessor.create();
    listenQueueHandle = listenerReceiver
        .consumeAutoAck(queueName)
        .subscribeOn(Schedulers.elastic())
        .map(this::toEvent)
        .handle(publishIfPresent())
        .subscribe(listener::onNext);
}
 
Example #4
Source File: R090_UnicastProcessor.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void overflowBeforeSubscribing() throws Exception {
    //given
    final UnicastProcessor<Long> proc = UnicastProcessor
            .create(
                    new ArrayBlockingQueue<>(10),
                    x -> log.warn("Dropped {}", x),
                    () -> {
                    });


    //when
    pushSomeEvents(proc, 0, 11);

    //then
    proc.subscribe(
            x -> log.info("Got {}", x),
            e -> log.error("Error", e));
}
 
Example #5
Source File: MultipartHttpMessageWriterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test // SPR-16402
public void singleSubscriberWithResource() throws IOException {
	UnicastProcessor<Resource> processor = UnicastProcessor.create();
	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	Mono.just(logo).subscribe(processor);

	MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
	bodyBuilder.asyncPart("logo", processor, Resource.class);

	Mono<MultiValueMap<String, HttpEntity<?>>> result = Mono.just(bodyBuilder.build());

	Map<String, Object> hints = Collections.emptyMap();
	this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block();

	MultiValueMap<String, Part> requestParts = parse(hints);
	assertEquals(1, requestParts.size());

	Part part = requestParts.getFirst("logo");
	assertEquals("logo", part.name());
	assertTrue(part instanceof FilePart);
	assertEquals("logo.jpg", ((FilePart) part).filename());
	assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType());
	assertEquals(logo.getFile().length(), part.headers().getContentLength());
}
 
Example #6
Source File: WebsocketPublisher.java    From reactor-guice with Apache License 2.0 6 votes vote down vote up
public Mono<Object> sendMessage(HttpServerRequest request, HttpServerResponse response, WebSocketServerHandle handleObject, Object requestAttributeObject) {
    // return
    return response.header("content-type", "text/plain")
            .sendWebsocket((in, out) -> {
                // return
                return out.withConnection(
                        connect -> {
                            Channel channel = connect.channel();
                            connect.onDispose().subscribe(null, null, () -> {
                                handleObject.onClose(null, channel);
                            });
                            channel.attr(RequestAttribute.REQUEST_ATTRIBUTE).set((RequestAttribute) requestAttributeObject);
                            handleObject.onConnect(channel);
                            in.aggregateFrames().receiveFrames().subscribe(
                                    frame->handleObject.handleEvent(frame, channel)
                            );
                        })
                        .sendString(UnicastProcessor.create());
            })
            .map(s->s);
}
 
Example #7
Source File: MultipartHttpMessageWriterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-16402
public void singleSubscriberWithResource() throws IOException {
	UnicastProcessor<Resource> processor = UnicastProcessor.create();
	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	Mono.just(logo).subscribe(processor);

	MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
	bodyBuilder.asyncPart("logo", processor, Resource.class);

	Mono<MultiValueMap<String, HttpEntity<?>>> result = Mono.just(bodyBuilder.build());

	Map<String, Object> hints = Collections.emptyMap();
	this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block();

	MultiValueMap<String, Part> requestParts = parse(hints);
	assertEquals(1, requestParts.size());

	Part part = requestParts.getFirst("logo");
	assertEquals("logo", part.name());
	assertTrue(part instanceof FilePart);
	assertEquals("logo.jpg", ((FilePart) part).filename());
	assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType());
	assertEquals(logo.getFile().length(), part.headers().getContentLength());
}
 
Example #8
Source File: MultipartHttpMessageWriterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-16402
public void singleSubscriberWithStrings() {
	UnicastProcessor<String> processor = UnicastProcessor.create();
	Flux.just("foo", "bar", "baz").subscribe(processor);

	MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
	bodyBuilder.asyncPart("name", processor, String.class);

	Mono<MultiValueMap<String, HttpEntity<?>>> result = Mono.just(bodyBuilder.build());

	Map<String, Object> hints = Collections.emptyMap();
	this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block();
}
 
Example #9
Source File: SimpleReactorExample.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 5 votes vote down vote up
@Test
public void testHotPublisher(){
  UnicastProcessor<String> hotSource = UnicastProcessor.create();
  Flux<Category> hotPublisher = hotSource.publish()
      .autoConnect().map((String t) -> Category.builder().name(t).build());
  hotPublisher.subscribe(category -> System.out.println("Subscriber 1: "+ category.getName()));
  hotSource.onNext("sports");
  hotSource.onNext("cars");
  hotPublisher.subscribe(category -> System.out.println("Subscriber 2: "+category.getName()));
  hotSource.onNext("games");
  hotSource.onNext("electronics");
  hotSource.onComplete();
}
 
Example #10
Source File: MemoryWorkQueue.java    From james-project with Apache License 2.0 5 votes vote down vote up
public MemoryWorkQueue(TaskManagerWorker worker) {
    this.worker = worker;
    this.tasks = UnicastProcessor.create();
    this.subscription = tasks
        .subscribeOn(Schedulers.elastic())
        .limitRate(1)
        .concatMap(this::dispatchTaskToWorker)
        .subscribe();
}
 
Example #11
Source File: RabbitMQWorkQueue.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void listenToCancelRequests() {
    String queueName = CANCEL_REQUESTS_QUEUE_NAME_PREFIX + UUID.randomUUID().toString();

    sender.declareExchange(ExchangeSpecification.exchange(CANCEL_REQUESTS_EXCHANGE_NAME)).block();
    sender.declare(QueueSpecification.queue(queueName).durable(false).autoDelete(true)).block();
    sender.bind(BindingSpecification.binding(CANCEL_REQUESTS_EXCHANGE_NAME, CANCEL_REQUESTS_ROUTING_KEY, queueName)).block();
    registerCancelRequestsListener(queueName);

    sendCancelRequestsQueue = UnicastProcessor.create();
    sendCancelRequestsQueueHandle = sender
        .send(sendCancelRequestsQueue.map(this::makeCancelRequestMessage))
        .subscribeOn(Schedulers.elastic())
        .subscribe();
}
 
Example #12
Source File: R090_UnicastProcessor.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void overflow() throws Exception {
    //given
    final UnicastProcessor<Long> proc = UnicastProcessor
            .create(
                    new ArrayBlockingQueue<>(10),
                    x -> log.warn("Dropped {}", x),
                    () -> {
                    });

    //when
    pushSomeEvents(proc, 0, 11);

    //then
}
 
Example #13
Source File: R090_UnicastProcessor.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void twoSubscribers() throws Exception {
    //given
    final UnicastProcessor<Long> proc = UnicastProcessor
            .create(
                    new ArrayBlockingQueue<>(10),
                    x -> log.warn("Dropped {}", x),
                    () -> {
                    });


    //when
    pushSomeEvents(proc, 0, 11);

    //then
    proc
            .subscribeOn(Schedulers.elastic())
            .subscribe(
                    x -> log.info("Got {}", x),
                    e -> log.error("Error", e));
    proc
            .subscribeOn(Schedulers.elastic())
            .subscribe(
                    x -> log.info("Got {}", x),
                    e -> log.error("Error", e));

    TimeUnit.SECONDS.sleep(1);
}
 
Example #14
Source File: SimpleReactorExample.java    From Spring-5.0-By-Example with MIT License 5 votes vote down vote up
@Test
public void testHotPublisher(){
  UnicastProcessor<String> hotSource = UnicastProcessor.create();
  Flux<Category> hotPublisher = hotSource.publish()
      .autoConnect().map((String t) -> Category.builder().name(t).build());
  hotPublisher.subscribe(category -> System.out.println("Subscriber 1: "+ category.getName()));
  hotSource.onNext("sports");
  hotSource.onNext("cars");
  hotPublisher.subscribe(category -> System.out.println("Subscriber 2: "+category.getName()));
  hotSource.onNext("games");
  hotSource.onNext("electronics");
  hotSource.onComplete();
}
 
Example #15
Source File: ConstantLoadJobExecutableGenerator.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public ConstantLoadJobExecutableGenerator(String owner, JobDescriptor<?> jobSpec, ExecutionPlan plan, int numberOfJobs) {
    this.executable = new Executable(owner, jobSpec, plan);
    this.executionPlans = UnicastProcessor.<Executable>create().serialize();
    for (int i = 0; i < numberOfJobs; i++) {
        this.executionPlans.onNext(executable);
    }
}
 
Example #16
Source File: MultipleInputOutputFunctionTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Bean
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Function<Flux<Integer>, Tuple2<Flux<String>, Flux<String>>> singleInputMultipleOutputs() {
	return flux -> {
		Flux<Integer> connectedFlux = flux.publish().autoConnect(2);
		UnicastProcessor even = UnicastProcessor.create();
		UnicastProcessor odd = UnicastProcessor.create();
		Flux<Integer> evenFlux = connectedFlux.filter(number -> number % 2 == 0).doOnNext(number -> even.onNext("EVEN: " + number));
		Flux<Integer> oddFlux = connectedFlux.filter(number -> number % 2 != 0).doOnNext(number -> odd.onNext("ODD: " + number));

		return Tuples.of(Flux.from(even).doOnSubscribe(x -> evenFlux.subscribe()), Flux.from(odd).doOnSubscribe(x -> oddFlux.subscribe()));
	};
}
 
Example #17
Source File: TaskProcessingWithServerSideNotificationsExample.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
TasksAcceptor(
    UnicastProcessor<Task> tasksToProcess,
    ConcurrentMap<String, BlockingQueue<Task>> idToCompletedTasksMap,
    ConcurrentMap<String, RSocket> idToRSocketMap) {
  this.tasksToProcess = tasksToProcess;
  this.idToCompletedTasksMap = idToCompletedTasksMap;
  this.idToRSocketMap = idToRSocketMap;
}
 
Example #18
Source File: TaskProcessingWithServerSideNotificationsExample.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public RSocketTaskHandler(
    ConcurrentMap<String, RSocket> idToRSocketMap,
    UnicastProcessor<Task> tasksToProcess,
    String id,
    RSocket sendingSocket) {
  this.id = id;
  this.sendingSocket = sendingSocket;
  this.idToRSocketMap = idToRSocketMap;
  this.tasksToProcess = tasksToProcess;
}
 
Example #19
Source File: InstanceEventPublisher.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
protected InstanceEventPublisher() {
	UnicastProcessor<InstanceEvent> unicastProcessor = UnicastProcessor.create();
	this.publishedFlux = unicastProcessor.publish().autoConnect(0);
	this.sink = unicastProcessor.sink();
}
 
Example #20
Source File: AbstractEventHandlerTest.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
private TestEventHandler(Publisher<InstanceEvent> publisher) {
	super(publisher, InstanceRegisteredEvent.class);
	UnicastProcessor<InstanceEvent> processor = UnicastProcessor.create();
	this.sink = processor.sink();
	this.flux = processor;
}
 
Example #21
Source File: TcpIntegrationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 15_000L)
public void testTwoConcurrentStreams() throws InterruptedException {
  ConcurrentHashMap<String, UnicastProcessor<Payload>> map = new ConcurrentHashMap<>();
  UnicastProcessor<Payload> processor1 = UnicastProcessor.create();
  map.put("REQUEST1", processor1);
  UnicastProcessor<Payload> processor2 = UnicastProcessor.create();
  map.put("REQUEST2", processor2);

  handler =
      new RSocket() {
        @Override
        public Flux<Payload> requestStream(Payload payload) {
          return map.get(payload.getDataUtf8());
        }
      };

  RSocket client = buildClient();

  Flux<Payload> response1 = client.requestStream(DefaultPayload.create("REQUEST1"));
  Flux<Payload> response2 = client.requestStream(DefaultPayload.create("REQUEST2"));

  CountDownLatch nextCountdown = new CountDownLatch(2);
  CountDownLatch completeCountdown = new CountDownLatch(2);

  response1
      .subscribeOn(Schedulers.newSingle("1"))
      .subscribe(c -> nextCountdown.countDown(), t -> {}, completeCountdown::countDown);

  response2
      .subscribeOn(Schedulers.newSingle("2"))
      .subscribe(c -> nextCountdown.countDown(), t -> {}, completeCountdown::countDown);

  processor1.onNext(DefaultPayload.create("RESPONSE1A"));
  processor2.onNext(DefaultPayload.create("RESPONSE2A"));

  nextCountdown.await();

  processor1.onComplete();
  processor2.onComplete();

  completeCountdown.await();
}
 
Example #22
Source File: TaskProcessingWithServerSideNotificationsExample.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  UnicastProcessor<Task> tasksProcessor =
      UnicastProcessor.create(Queues.<Task>unboundedMultiproducer().get());
  ConcurrentMap<String, BlockingQueue<Task>> idToCompletedTasksMap = new ConcurrentHashMap<>();
  ConcurrentMap<String, RSocket> idToRSocketMap = new ConcurrentHashMap<>();
  BackgroundWorker backgroundWorker =
      new BackgroundWorker(tasksProcessor, idToCompletedTasksMap, idToRSocketMap);

  RSocketServer.create(new TasksAcceptor(tasksProcessor, idToCompletedTasksMap, idToRSocketMap))
      .bindNow(TcpServerTransport.create(9991));

  Logger logger = LoggerFactory.getLogger("RSocket.Client.ID[Test]");

  Mono<RSocket> rSocketMono =
      RSocketConnector.create()
          .setupPayload(DefaultPayload.create("Test"))
          .acceptor(
              SocketAcceptor.forFireAndForget(
                  p -> {
                    logger.info("Received Processed Task[{}]", p.getDataUtf8());
                    p.release();
                    return Mono.empty();
                  }))
          .connect(TcpClientTransport.create(9991));

  RSocket rSocketRequester1 = rSocketMono.block();

  for (int i = 0; i < 10; i++) {
    rSocketRequester1.fireAndForget(DefaultPayload.create("task" + i)).block();
  }

  Thread.sleep(4000);

  rSocketRequester1.dispose();
  logger.info("Disposed");

  Thread.sleep(4000);

  RSocket rSocketRequester2 = rSocketMono.block();

  logger.info("Reconnected");

  Thread.sleep(10000);
}
 
Example #23
Source File: StatsdMeterRegistryTest.java    From micrometer with Apache License 2.0 4 votes vote down vote up
private UnicastProcessor<String> lineProcessor() {
    return UnicastProcessor.create(Queues.<String>unboundedMultiproducer().get());
}
 
Example #24
Source File: TcpConnectorPeer.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
protected TcpConnectorPeer(
    ErrorReporter errorReporterRef,
    CommonSerializer commonSerializerRef,
    String peerIdRef,
    TcpConnector connectorRef,
    SelectionKey key,
    AccessContext accCtx,
    Node nodeRef
)
{
    errorReporter = errorReporterRef;
    commonSerializer = commonSerializerRef;
    peerId = peerIdRef;
    connector = connectorRef;
    node = nodeRef;
    msgOutQueue = new LinkedList<>();

    // Do not use createMessage() here!
    // The SslTcpConnectorPeer has not initialized SSLEngine instance yet,
    // so a NullPointerException would be thrown in createMessage().
    // After initialization of the sslEngine, msgIn will be overwritten with
    // a reference to a valid instance.
    msgIn = new MessageData(false);

    selKey = key;
    peerAccCtx = accCtx;
    attachment = null;

    internalPingMsg = new TcpHeaderOnlyMessage(MessageTypes.PING);
    internalPongMsg = new TcpHeaderOnlyMessage(MessageTypes.PONG);

    serializerId = new AtomicLong(0);
    serializerLock = new ReentrantReadWriteLock(true);

    satelliteStateLock = new ReentrantReadWriteLock(true);
    if (node != null)
    {
        satelliteState = new SatelliteState();
    }

    finishedMsgInQueue = new LinkedList<>();

    UnicastProcessor<Tuple2<Long, Publisher<?>>> processor = UnicastProcessor.create();
    incomingMessageSink = processor.sink();
    processor
        .transform(OrderingFlux::order)
        .flatMap(Function.identity(), Integer.MAX_VALUE)
        .subscribe(
            ignored ->
            {
                // do nothing
            },
            exc -> errorReporterRef.reportError(
                exc, null, null, "Uncaught exception in processor for peer '" + this + "'")
        );
}
 
Example #25
Source File: GenericEvent.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void triggerEvent(ObjectIdentifier objectIdentifier, T value)
{
    Flux<T> stream = null;
    FluxSink<T> sink;
    Set<FluxSink<Tuple2<ObjectIdentifier, Flux<T>>>> waiterSet = null;

    lock.lock();
    try
    {
        sink = sinks.get(objectIdentifier);
        if (sink == null)
        {
            UnicastProcessor<T> processor = UnicastProcessor.create();
            ConnectableFlux<T> publisher = processor.replay(1);
            publisher.connect();

            // Publish events signals on the main scheduler to detach the execution from this thread,
            // so that we don't react to events in the thread-local context where the event is triggered.
            stream = publisher.publishOn(scheduler);
            streams.put(objectIdentifier, stream);
            try
            {
                eventStreamStore.addEventStream(new EventIdentifier(null, objectIdentifier));
            }
            catch (LinStorDataAlreadyExistsException exc)
            {
                throw new ImplementationError(exc);
            }

            sink = processor.sink();
            sinks.put(objectIdentifier, sink);

            List<ObjectIdentifier> matchingWaitObjects = matchingObjects(objectIdentifier);

            waiterSet = new HashSet<>();
            for (ObjectIdentifier waitObject : matchingWaitObjects)
            {
                Set<FluxSink<Tuple2<ObjectIdentifier, Flux<T>>>> waitersForObject = waiters.get(waitObject);
                if (waitersForObject != null)
                {
                    waiterSet.addAll(waitersForObject);
                }
            }
        }
    }
    finally
    {
        lock.unlock();
    }

    if (waiterSet != null)
    {
        for (FluxSink<Tuple2<ObjectIdentifier, Flux<T>>> waiter : waiterSet)
        {
            waiter.next(Tuples.of(objectIdentifier, stream));
        }
    }

    sink.next(value);
}
 
Example #26
Source File: AbstractEventHandlerTest.java    From Moss with Apache License 2.0 4 votes vote down vote up
private TestEventHandler(Publisher<InstanceEvent> publisher) {
    super(publisher, InstanceRegisteredEvent.class);
    UnicastProcessor<InstanceEvent> processor = UnicastProcessor.create();
    this.sink = processor.sink();
    this.flux = processor;
}
 
Example #27
Source File: InstanceEventPublisher.java    From Moss with Apache License 2.0 4 votes vote down vote up
protected InstanceEventPublisher() {
    UnicastProcessor<InstanceEvent> unicastProcessor = UnicastProcessor.create();
    this.publishedFlux = unicastProcessor.publish().autoConnect(0);
    this.sink = unicastProcessor.sink();
}