Java Code Examples for reactor.core.publisher.UnicastProcessor#create()

The following examples show how to use reactor.core.publisher.UnicastProcessor#create() . 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: 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 3
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 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: 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 7
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 8
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 9
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 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: 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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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();
}