java.util.concurrent.Flow.Subscriber Java Examples

The following examples show how to use java.util.concurrent.Flow.Subscriber. 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: Exec.java    From enmasse with Apache License 2.0 6 votes vote down vote up
/**
 * read method
 *
 * @return return future string of output
 */
public Future<String> read() {
    return CompletableFuture.supplyAsync(() -> {
        try (Scanner scanner = new Scanner(is)) {
            log.debug("Reading stream {}", is);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                data.append(line);
                if (appendLineSeparator) {
                    data.append(System.getProperty("line.separator"));
                }
                subscribers.forEach(sub -> sub.onNext(line));
            }
            scanner.close();
            return data.toString();
        } catch (Exception e) {
            subscribers.forEach(sub -> sub.onError(e));
            throw new CompletionException(e);
        } finally {
            subscribers.forEach(Subscriber::onComplete);
        }
    }, runnable -> new Thread(runnable).start());
}
 
Example #2
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private Publisher<Integer> newMockFlowPublisher(
        BiConsumer<Subscriber<? super Integer>, Subscription> subscriberTerminator) {
    @SuppressWarnings("unchecked")
    Publisher<Integer> flowPublisher = mock(Publisher.class);
    doAnswer(invocation -> {
        Subscriber<? super Integer> subscriber = invocation.getArgument(0);
        Subscription subscription = mock(Subscription.class);
        doAnswer(invocation1 -> {
            subscriberTerminator.accept(subscriber, subscription);
            return null;
        }).when(subscription).request(anyLong());
        subscriber.onSubscribe(subscription);
        return null;
    }).when(flowPublisher).subscribe(any());
    return flowPublisher;
}
 
Example #3
Source File: IncrementingPublisher.java    From demo-java-x with MIT License 5 votes vote down vote up
private Sub createNewSubscriptionFor(Subscriber<? super Integer> subscriber) {
	int startValue = subscriptions.stream()
			.mapToInt(sub -> sub.nextValue.get())
			.min()
			.orElse(0);
	return new Sub(subscriber, startValue);
}
 
Example #4
Source File: NumberPublisher.java    From Reactive-Programming-With-Java-9 with MIT License 5 votes vote down vote up
public NumberSubscription(ExecutorService executor,Subscriber<? super Long> subscriber,long start_range,long stop_range) {
	// TODO Auto-generated constructor stub
	this.executor = executor;
	this.subscriber=subscriber;
	this.start_range=start_range;
	this.stop_range=stop_range;
}
 
Example #5
Source File: AdaptedBlackBoxSubscriberVerificationTest.java    From java-async-util with Apache License 2.0 5 votes vote down vote up
@Override
public Subscriber<Integer> createFlowSubscriber() {
  return new FlowAdapter.SubscribingIterator<Integer>() {
    @Override
    public void onSubscribe(final Flow.Subscription subscription) {
      super.onSubscribe(subscription);
      consume();
    }
  };
}
 
Example #6
Source File: NumberPublisher.java    From Reactive-Programming-With-Java-9 with MIT License 5 votes vote down vote up
public NumberSubscription(ExecutorService executor,Subscriber<? super Long> subscriber,long start_range,long stop_range) {
	// TODO Auto-generated constructor stub
	this.executor = executor;
	this.subscriber=subscriber;
	this.start_range=start_range;
	this.stop_range=stop_range;
}
 
Example #7
Source File: FlowAdapter.java    From java-async-util with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(final Flow.Subscriber<? super T> subscriber) {
  if ((boolean) SUBSCRIBED_HANDLE.getAndSet(this, true)) {
    subscriber.onError(new IllegalStateException(
        "Publisher " + this + " does not support multiple subscribers"));
    return;
  }
  subscriber.onSubscribe(new IteratorBackedSubscription<>(this.asyncIterator, subscriber));
}
 
Example #8
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private Subscriber<Integer> subscribeToFlowPublisher(final Publisher<Integer> flowPublisher) {
    @SuppressWarnings("unchecked")
    Subscriber<Integer> subscriber = mock(Subscriber.class);
    flowPublisher.subscribe(subscriber);
    ArgumentCaptor<Subscription> subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class);
    verify(subscriber).onSubscribe(subscriptionCaptor.capture());
    subscriptionCaptor.getValue().request(1);
    return subscriber;
}
 
Example #9
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void toFlowFromSourceCancel() {
    PublisherSource.Subscription srcSubscription = mock(PublisherSource.Subscription.class);
    PublisherSource<Integer> source = s -> s.onSubscribe(srcSubscription);
    Subscriber<Integer> subscriber = toFlowPublisherFromSourceAndSubscribe(source);
    ArgumentCaptor<Subscription> flowSubscriptionCaptor = ArgumentCaptor.forClass(Subscription.class);
    verify(subscriber).onSubscribe(flowSubscriptionCaptor.capture());
    flowSubscriptionCaptor.getValue().cancel();
    verify(srcSubscription).cancel();
}
 
Example #10
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void toFlowCancel() {
    TestPublisher<Integer> stPublisher = new TestPublisher<>();
    Subscriber<Integer> subscriber = toFlowPublisherAndSubscribe(stPublisher);
    TestSubscription subscription = new TestSubscription();
    stPublisher.onSubscribe(subscription);
    assertThat("Source not subscribed.", stPublisher.isSubscribed(), is(true));
    ArgumentCaptor<Subscription> subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class);
    verify(subscriber).onSubscribe(subscriptionCaptor.capture());
    subscriptionCaptor.getValue().cancel();
    assertThat("Subscription not cancelled.", subscription.isCancelled(), is(true));
}
 
Example #11
Source File: AbstractClient.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private void setLinkAttachedProbe() {
    var linkAttachedProbe = linkAttachedProbeFactory().get();
    executor.setStdErrProcessor(new Subscriber<String>() {

        @Override
        public void onSubscribe(Subscription subscription) {
            //empty
        }

        @Override
        public void onNext(String item) {
            if (!linkAttached.isDone()) {
                if (linkAttachedProbe.test(item)) {
                    log.info("Client is attached!!");
                    linkAttached.complete(null);
                }
            }
        }

        @Override
        public void onError(Throwable throwable) {
            linkAttached.completeExceptionally(throwable);
        }

        @Override
        public void onComplete() {
            linkAttached.complete(null);
        }
    });
}
 
Example #12
Source File: IncrementingPublisher.java    From demo-java-x with MIT License 4 votes vote down vote up
public Sub(Subscriber<? super Integer> subscriber, int startValue) {
	this.subscriber = subscriber;
	this.nextValue = new AtomicInteger(startValue);
	this.canceled = new AtomicBoolean(false);
}
 
Example #13
Source File: AdaptedWhiteBoxSubscriberVerificationTest.java    From java-async-util with Apache License 2.0 4 votes vote down vote up
@Override
protected Subscriber<Integer> createFlowSubscriber(
    final WhiteboxSubscriberProbe<Integer> probe) {
  final Subscriber<Integer> backing = new FlowAdapter.SubscribingIterator<>();
  return new Subscriber<Integer>() {
    @Override
    public void onSubscribe(final Subscription s) {
      backing.onSubscribe(s);

      probe.registerOnSubscribe(new SubscriberPuppet() {

        @Override
        public void triggerRequest(final long elements) {
          s.request(elements);
        }

        @Override
        public void signalCancel() {
          s.cancel();
        }
      });
    }

    @Override
    public void onNext(final Integer integer) {
      backing.onNext(integer);
      probe.registerOnNext(integer);
    }

    @Override
    public void onError(final Throwable throwable) {
      backing.onError(throwable);
      probe.registerOnError(throwable);
    }

    @Override
    public void onComplete() {
      backing.onComplete();
      probe.registerOnComplete();
    }
  };
}
 
Example #14
Source File: IncrementingPublisher.java    From demo-java-x with MIT License 4 votes vote down vote up
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
	Sub subscription = createNewSubscriptionFor(subscriber);
	registerSubscription(subscription);
	subscriber.onSubscribe(subscription);
}
 
Example #15
Source File: Exec.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public void setStdErrProcessor(Subscriber<String> stdErrProcessor) {
    this.stdErrProcessor = stdErrProcessor;
}
 
Example #16
Source File: ReactivePost.java    From demo-java-x with MIT License 4 votes vote down vote up
private LoggingSubscriber(Subscriber<? super ByteBuffer> subscriber) {
	this.subscriber = subscriber;
}
 
Example #17
Source File: Exec.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(Subscriber<? super String> subscriber) {
    subscriber.onSubscribe(null);
    subscribers.add(subscriber);
}
 
Example #18
Source File: ReactivePost.java    From demo-java-x with MIT License 4 votes vote down vote up
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
	log("Subscriber registered: " + subscriber);
	publisher.subscribe(new LoggingSubscriber(subscriber));
}
 
Example #19
Source File: StreamPublisherTest.java    From jenetics with Apache License 2.0 4 votes vote down vote up
@Test
public void creation() throws InterruptedException {
	final var lock = new ReentrantLock();
	final var finished = lock.newCondition();
	final var running = new AtomicBoolean(true);
	final var generation = new AtomicLong();


	final Stream<Long> stream = _engine.stream()
		.limit(33)
		.map(EvolutionResult::generation);

	try (var publisher = new StreamPublisher<Long>()) {
		publisher.subscribe(new Subscriber<>() {
			private Subscription _subscription;
			@Override
			public void onSubscribe(final Subscription subscription) {
				_subscription = subscription;
				_subscription.request(1);
			}
			@Override
			public void onNext(final Long g) {
				generation.set(g);
				_subscription.request(1);
			}
			@Override
			public void onError(final Throwable throwable) {
			}
			@Override
			public void onComplete() {
				lock.lock();
				try {
					running.set(false);
					finished.signal();
				} finally {
					lock.unlock();
				}
			}
		});

		publisher.attach(stream);

		lock.lock();
		try {
			while (running.get()) {
				finished.await();
			}
		} finally {
			lock.unlock();
		}
	}

	Assert.assertEquals(generation.get(), 33);
}
 
Example #20
Source File: StreamPublisherTest.java    From jenetics with Apache License 2.0 4 votes vote down vote up
@Test
public void publishLimitedStream() throws InterruptedException {
	final int generations = 20;
	final var publisher = new StreamPublisher<EvolutionResult<IntegerGene, Integer>>();
	final var stream = _engine.stream().limit(generations);

	final var lock = new ReentrantLock();
	final var finished = lock.newCondition();
	final AtomicBoolean running = new AtomicBoolean(true);
	final AtomicBoolean completed = new AtomicBoolean(false);

	final AtomicInteger count = new AtomicInteger();
	publisher.subscribe(new Subscriber<>() {
		private Subscription _subscription;
		@Override
		public void onSubscribe(final Subscription subscription) {
			_subscription = requireNonNull(subscription);
			_subscription.request(1);
		}
		@Override
		public void onNext(final EvolutionResult<IntegerGene, Integer> er) {
			count.incrementAndGet();
			_subscription.request(1);
		}
		@Override
		public void onComplete() {
			lock.lock();
			try {
				running.set(false);
				completed.set(true);
				finished.signal();
			} finally {
				lock.unlock();
			}
		}
		@Override
		public void onError(final Throwable throwable) {}
	});

	publisher.attach(stream);

	lock.lock();
	try {
		while (running.get()) {
			finished.await();
		}
	} finally {
		lock.unlock();
	}

	publisher.close();

	Assert.assertEquals(count.get(), generations);
	Assert.assertTrue(completed.get());
}
 
Example #21
Source File: NumberPublisher.java    From Reactive-Programming-With-Java-9 with MIT License 4 votes vote down vote up
@Override
public void subscribe(Subscriber<? super Long> subscriber) {
	// TODO Auto-generated method stub
	subscriber.onSubscribe(new NumberSubscription(executor,subscriber,start_range,stop_range));

}
 
Example #22
Source File: StreamPublisherTest.java    From jenetics with Apache License 2.0 4 votes vote down vote up
@Test
public void publishClosingPublisher() throws InterruptedException {
	final int generations = 20;
	final var publisher = new StreamPublisher<EvolutionResult<IntegerGene, Integer>>();
	final var stream = _engine.stream();

	final var lock = new ReentrantLock();
	final var finished = lock.newCondition();
	final AtomicBoolean running = new AtomicBoolean(true);
	final AtomicBoolean completed = new AtomicBoolean(false);

	final AtomicInteger count = new AtomicInteger();
	publisher.subscribe(new Subscriber<>() {
		private Subscription _subscription;
		@Override
		public void onSubscribe(final Subscription subscription) {
			_subscription = requireNonNull(subscription);
			_subscription.request(1);
		}
		@Override
		public void onNext(final EvolutionResult<IntegerGene, Integer> er) {
			count.incrementAndGet();
			lock.lock();
			try {
				running.set(er.generation() < generations);
				finished.signal();
			} finally {
				lock.unlock();
			}
			_subscription.request(1);
		}
		@Override
		public void onComplete() {
			lock.lock();
			try {
				completed.set(true);
				finished.signalAll();
			} finally {
				lock.unlock();
			}
		}
		@Override
		public void onError(final Throwable throwable) {}
	});

	publisher.attach(stream);

	lock.lock();
	try {
		while (running.get()) {
			finished.await();
		}
	} finally {
		lock.unlock();
	}

	publisher.close();

	lock.lock();
	try {
		while (!completed.get()) {
			finished.await();
		}
	} finally {
		lock.unlock();
	}

	Assert.assertEquals(count.get(), generations);
	Assert.assertTrue(completed.get());
}
 
Example #23
Source File: NumberPublisher.java    From Reactive-Programming-With-Java-9 with MIT License 4 votes vote down vote up
@Override
public void subscribe(Subscriber<? super Long> subscriber) {
	// TODO Auto-generated method stub
	subscriber.onSubscribe(new NumberSubscription(executor,subscriber,start_range,stop_range));

}
 
Example #24
Source File: Lesson3.java    From Java-Concurrency-Multithreading-in-Practice with MIT License 4 votes vote down vote up
public synchronized void subscribe(Subscriber<? super WeatherForecast> subscriber) {
	subscriber.onSubscribe(new OnDemandWeatherForecastSubscription(subscriber, executor));
}
 
Example #25
Source File: FlowAdapter.java    From java-async-util with Apache License 2.0 4 votes vote down vote up
IteratorBackedSubscription(final AsyncIterator<T> iterator,
    final Flow.Subscriber<? super T> subscriber) {
  this.iterator = Objects.requireNonNull(iterator);
  this.subscriber = Objects.requireNonNull(subscriber);
}
 
Example #26
Source File: FlowAdapter.java    From java-async-util with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(final Flow.Subscriber<? super T> subscriber) {
  subscriber
      .onSubscribe(
          new IteratorBackedSubscription<>(this.asyncIteratorSupplier.get(), subscriber));
}
 
Example #27
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private Subscriber<Integer> toFlowPublisherFromSourceAndSubscribe(final PublisherSource<Integer> source) {
    Publisher<Integer> flowPublisher = toFlowPublisher(source);
    return subscribeToFlowPublisher(flowPublisher);
}
 
Example #28
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private Subscriber<Integer> toFlowPublisherAndSubscribe(
        final io.servicetalk.concurrent.api.Publisher<Integer> stPublisher) {
    Publisher<Integer> flowPublisher = toFlowPublisher(stPublisher);
    return subscribeToFlowPublisher(flowPublisher);
}
 
Example #29
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private void verifyFlowError(final Subscriber<Integer> subscriber) {
    verify(subscriber).onSubscribe(any());
    verify(subscriber).onError(DELIBERATE_EXCEPTION);
    verifyNoMoreInteractions(subscriber);
}
 
Example #30
Source File: JdkFlowAdaptersTest.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private void verifyFlowSuccess(final Subscriber<Integer> subscriber) {
    verify(subscriber).onSubscribe(any());
    verify(subscriber).onNext(1);
    verify(subscriber).onComplete();
    verifyNoMoreInteractions(subscriber);
}