org.reactivestreams.Publisher Java Examples

The following examples show how to use org.reactivestreams.Publisher. 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: RedissonReactiveZSetCommands.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<NumericResponse<ZUnionStoreCommand, Long>> zUnionStore(Publisher<ZUnionStoreCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Destination key must not be null!");
        Assert.notEmpty(command.getSourceKeys(), "Source keys must not be null or empty!");

        byte[] keyBuf = toByteArray(command.getKey());
        List<Object> args = new ArrayList<Object>(command.getSourceKeys().size() * 2 + 5);
        args.add(keyBuf);
        args.add(command.getSourceKeys().size());
        args.addAll(command.getSourceKeys().stream().map(e -> toByteArray(e)).collect(Collectors.toList()));
        if (!command.getWeights().isEmpty()) {
            args.add("WEIGHTS");
            for (Double weight : command.getWeights()) {
                args.add(BigDecimal.valueOf(weight).toPlainString());
            }
        }
        if (command.getAggregateFunction().isPresent()) {
            args.add("AGGREGATE");
            args.add(command.getAggregateFunction().get().name());
        }
        Mono<Long> m = write(keyBuf, LongCodec.INSTANCE, ZUNIONSTORE, args.toArray());
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example #2
Source File: FrameFragmenterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@DisplayName("fragments frame with only metadata")
@Test
void fragmentMetadata() {
  ByteBuf rr =
      RequestStreamFrameCodec.encode(
          allocator, 1, true, 10, Unpooled.wrappedBuffer(metadata), Unpooled.EMPTY_BUFFER);

  Publisher<ByteBuf> fragments =
      FrameFragmenter.fragmentFrame(allocator, 1024, rr, FrameType.REQUEST_STREAM);

  StepVerifier.create(Flux.from(fragments).doOnError(Throwable::printStackTrace))
      .expectNextCount(1)
      .assertNext(
          byteBuf -> {
            Assert.assertEquals(FrameType.NEXT, FrameHeaderCodec.frameType(byteBuf));
            Assert.assertEquals(1, FrameHeaderCodec.streamId(byteBuf));
            Assert.assertTrue(FrameHeaderCodec.hasFollows(byteBuf));
          })
      .expectNextCount(2)
      .assertNext(
          byteBuf -> {
            Assert.assertEquals(FrameType.NEXT, FrameHeaderCodec.frameType(byteBuf));
            Assert.assertFalse(FrameHeaderCodec.hasFollows(byteBuf));
          })
      .verifyComplete();
}
 
Example #3
Source File: RedissonReactiveGeoCommands.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<NumericResponse<GeoAddCommand, Long>> geoAdd(Publisher<GeoAddCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getGeoLocations(), "Locations must not be null!");

        byte[] keyBuf = toByteArray(command.getKey());
        
        List<Object> args = new ArrayList<Object>();
        args.add(keyBuf);
        for (GeoLocation<ByteBuffer> location : command.getGeoLocations()) {
            args.add(location.getPoint().getX());
            args.add(location.getPoint().getY());
            args.add(toByteArray(location.getName()));
        }
        
        Mono<Long> m = write(keyBuf, StringCodec.INSTANCE, RedisCommands.GEOADD, args.toArray());
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example #4
Source File: RedissonReactiveStreamCommands.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<ReactiveRedisConnection.CommandResponse<XClaimCommand, Flux<RecordId>>> xClaimJustId(Publisher<XClaimCommand> publisher) {
    return execute(publisher, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getGroupName(), "Group name must not be null!");
        Assert.notNull(command.getNewOwner(), "NewOwner must not be null!");
        Assert.notEmpty(command.getOptions().getIds(), "Ids collection must not be empty!");

        List<Object> params = new ArrayList<>();
        byte[] k = toByteArray(command.getKey());
        params.add(k);
        params.add(command.getGroupName());
        params.add(command.getNewOwner());
        params.add(Objects.requireNonNull(command.getOptions().getIdleTime()).toMillis());
        params.addAll(Arrays.asList(command.getOptions().getIdsAsStringArray()));
        params.add("JUSTID");

        Mono<Map<StreamMessageId, Map<byte[], byte[]>>> m = write(k, ByteArrayCodec.INSTANCE, RedisCommands.XCLAIM, params.toArray());
        return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, Flux.fromStream(v.entrySet().stream()).map(e -> {
            return RecordId.of(e.getKey().toString());
        })));
    });
}
 
Example #5
Source File: MonoZip.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
Mono<R> zipAdditionalSource(Publisher source, BiFunction zipper) {
	Publisher[] oldSources = sources;
	if (oldSources != null && this.zipper instanceof FluxZip.PairwiseZipper) {
		int oldLen = oldSources.length;
		Publisher<?>[] newSources = new Publisher[oldLen + 1];
		System.arraycopy(oldSources, 0, newSources, 0, oldLen);
		newSources[oldLen] = source;

		Function<Object[], R> z =
				((FluxZip.PairwiseZipper<R>) this.zipper).then(zipper);

		return new MonoZip<>(delayError, z, newSources);
	}
	return null;
}
 
Example #6
Source File: LiftFunctionTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void liftParallelFlux() {
	ParallelFlux<Integer> source = Flux.just(1)
	                                   .parallel(2)
	                                   .hide();

	Operators.LiftFunction<Integer, Integer> liftFunction =
			Operators.LiftFunction.liftScannable(null, (s, actual) -> actual);
	Publisher<Integer> liftOperator = liftFunction.apply(source);

	assertThat(liftOperator)
			.isInstanceOf(ParallelFlux.class)
			.isExactlyInstanceOf(ParallelLift.class);

	assertThatCode(() -> liftOperator.subscribe(new BaseSubscriber<Integer>() {}))
			.doesNotThrowAnyException();
}
 
Example #7
Source File: FluxUsingWhen.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(S resource) {
	if (resourceProvided) {
		Operators.onNextDropped(resource, actual.currentContext());
		return;
	}
	resourceProvided = true;

	final Publisher<? extends T> p = deriveFluxFromResource(resource, resourceClosure);
	this.closureSubscriber = prepareSubscriberForResource(resource,
			this.actual,
			this.asyncComplete,
			this.asyncError,
			this.asyncCancel,
			this);

	p.subscribe(closureSubscriber);

	if (!isMonoSource) {
		resourceSubscription.cancel();
	}
}
 
Example #8
Source File: AbstractClientHttpRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Apply {@link #beforeCommit(Supplier) beforeCommit} actions, apply the
 * request headers/cookies, and write the request body.
 * @param writeAction the action to write the request body (may be {@code null})
 * @return a completion publisher
 */
protected Mono<Void> doCommit(@Nullable Supplier<? extends Publisher<Void>> writeAction) {
	if (!this.state.compareAndSet(State.NEW, State.COMMITTING)) {
		return Mono.empty();
	}

	this.commitActions.add(() ->
			Mono.fromRunnable(() -> {
				applyHeaders();
				applyCookies();
				this.state.set(State.COMMITTED);
			}));

	if (writeAction != null) {
		this.commitActions.add(writeAction);
	}

	List<? extends Publisher<Void>> actions = this.commitActions.stream()
			.map(Supplier::get).collect(Collectors.toList());

	return Flux.concat(actions).then();
}
 
Example #9
Source File: RSocketLeaseTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
static Stream<Arguments> interactions() {
  return Stream.of(
      Arguments.of(
          (BiFunction<RSocket, Payload, Publisher<?>>) RSocket::fireAndForget,
          FrameType.REQUEST_FNF),
      Arguments.of(
          (BiFunction<RSocket, Payload, Publisher<?>>) RSocket::requestResponse,
          FrameType.REQUEST_RESPONSE),
      Arguments.of(
          (BiFunction<RSocket, Payload, Publisher<?>>) RSocket::requestStream,
          FrameType.REQUEST_STREAM),
      Arguments.of(
          (BiFunction<RSocket, Payload, Publisher<?>>)
              (rSocket, payload) -> rSocket.requestChannel(Mono.just(payload)),
          FrameType.REQUEST_CHANNEL));
}
 
Example #10
Source File: PublisherBufferBoundaryAndSize.java    From reactive-streams-commons with Apache License 2.0 5 votes vote down vote up
public PublisherBufferBoundaryAndSize(Publisher<? extends T> source, 
        Publisher<U> other, Supplier<C> bufferSupplier, int maxSize,
        Supplier<? extends Queue<C>> queueSupplier) {
    super(source);
    if (maxSize < 1) {
        throw new IllegalArgumentException("maxSize > 0 required but it was " + maxSize);
    }
    this.other = Objects.requireNonNull(other, "other");
    this.bufferSupplier = Objects.requireNonNull(bufferSupplier, "bufferSupplier");
    this.maxSize = maxSize;
    this.queueSupplier = Objects.requireNonNull(queueSupplier, "queueSupplier");
}
 
Example #11
Source File: FluxWindowTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
static <T> void expect(AssertSubscriber<Publisher<T>> ts, int index, T... values) {
	toList(ts.values()
	         .get(index)).assertValues(values)
	                     .assertComplete()
	                     .assertNoError();
}
 
Example #12
Source File: MutinyContextEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Transactional
@GET
@Path("/transaction-multi-2")
public Publisher<String> transactionPropagationWithMulti2() {
    Multi<String> ret = Multi.createFrom().item("OK");
    // now delete both entities
    Assertions.assertEquals(2, Person.deleteAll());
    return ret;
}
 
Example #13
Source File: RedissonReactiveStringCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<NumericResponse<AppendCommand, Long>> append(Publisher<AppendCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getValue(), "Value must not be null!");

        byte[] keyBuf = toByteArray(command.getKey());
        byte[] valueBuf = toByteArray(command.getValue());
        
        Mono<Long> m = write(keyBuf, StringCodec.INSTANCE, APPEND, keyBuf, valueBuf);
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example #14
Source File: PremiumCollection.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param relicId The ID of the {@link Relic} to get.
 * @return The {@link Relic} corresponding to the provided {@code relicId}.
 */
public Mono<Relic> getRelicById(String relicId) {
    LOGGER.debug("[Relic {}] Request", relicId);

    final Publisher<Document> request = this.getCollection()
            .find(Filters.eq("_id", relicId))
            .first();

    return Mono.from(request)
            .map(document -> document.toJson(JSON_WRITER_SETTINGS))
            .flatMap(json -> Mono.fromCallable(() -> NetUtils.MAPPER.readValue(json, RelicBean.class)))
            .map(Relic::new)
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(PremiumCollection.NAME).inc());
}
 
Example #15
Source File: RedissonReactiveNumberCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<NumericResponse<KeyCommand, Long>> decr(Publisher<KeyCommand> keys) {
    return execute(keys, key -> {

        Assert.notNull(key.getKey(), "Key must not be null!");

        byte[] keyBuf = toByteArray(key.getKey());
        Mono<Long> m = write(keyBuf, StringCodec.INSTANCE, RedisCommands.DECR, keyBuf);
        return m.map(v -> new NumericResponse<>(key, v));
    });
}
 
Example #16
Source File: OnErrorResumeStageVerification.java    From microprofile-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Integer> createFailedPublisher() {
    return rs.<Integer>failed(new RuntimeException("failed"))
        .onErrorResume(t -> {
            // Re-throw the exception.
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            }
            // Wrap if required.
            throw new RuntimeException(t);
        })
        .buildRs(getEngine());
}
 
Example #17
Source File: DeletedMessageVaultHook.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Void> notifyDelete(DeleteOperation deleteOperation) {
    Preconditions.checkNotNull(deleteOperation);

    return groupMetadataByOwnerAndMessageId(deleteOperation)
        .flatMap(this::appendToTheVault)
        .then();
}
 
Example #18
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public NettyOutbound send(Publisher<? extends ByteBuf> dataStream, Predicate<ByteBuf> predicate) {
	if (!channel().isActive()) {
		return then(Mono.error(AbortedException.beforeSend()));
	}
	if (dataStream instanceof Mono) {
		return then(((Mono<?>)dataStream).flatMap(m -> FutureMono.from(channel().writeAndFlush(m)))
		                                 .doOnDiscard(ByteBuf.class, ByteBuf::release));
	}
	return then(MonoSendMany.byteBufSource(dataStream, channel(), predicate));
}
 
Example #19
Source File: ServerSentEventHttpMessageWriterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private <T> void testWrite(
		Publisher<T> source, MediaType mediaType, MockServerHttpResponse response, Class<T> clazz) {

	Mono<Void> result =
			this.messageWriter.write(source, forClass(clazz), mediaType, response, HINTS);

	StepVerifier.create(result)
			.verifyComplete();
}
 
Example #20
Source File: FluxBufferWhen.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
BufferWhenMainSubscriber(CoreSubscriber<? super BUFFER> actual,
		Supplier<BUFFER> bufferSupplier, Supplier<? extends Queue<BUFFER>> queueSupplier,
		Publisher<? extends OPEN> bufferOpen,
		Function<? super OPEN, ? extends Publisher<? extends CLOSE>> bufferClose) {
	this.actual = actual;
	this.ctx = actual.currentContext();
	this.bufferOpen = bufferOpen;
	this.bufferClose = bufferClose;
	this.bufferSupplier = bufferSupplier;
	this.queue = queueSupplier.get();
	this.buffers = new LinkedHashMap<>();
	this.subscribers = Disposables.composite();
}
 
Example #21
Source File: RedissonReactiveListCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<CommandResponse<RangeCommand, Flux<ByteBuffer>>> lRange(Publisher<RangeCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getRange(), "Range must not be null!");

        byte[] keyBuf = toByteArray(command.getKey());
        Mono<List<byte[]>> m = read(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.LRANGE, 
                keyBuf, command.getRange().getLowerBound().getValue().orElse(0L), 
                        command.getRange().getUpperBound().getValue().orElse(-1L));
        return m.map(v -> new CommandResponse<>(command, Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e))));
    });
}
 
Example #22
Source File: ReactorNettyWebSocketSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> send(Publisher<WebSocketMessage> messages) {
	Flux<WebSocketFrame> frames = Flux.from(messages)
			.doOnNext(message -> {
				if (logger.isTraceEnabled()) {
					logger.trace(getLogPrefix() + "Sending " + message);
				}
			})
			.map(this::toFrame);
	return getDelegate().getOutbound()
			.options(NettyPipeline.SendOptions::flushOnEach)
			.sendObject(frames)
			.then();
}
 
Example #23
Source File: InMemoryBackend.java    From immutables with Apache License 2.0 5 votes vote down vote up
private Publisher<WriteResult> insert(StandardOperations.Insert op) {
  if (op.values().isEmpty()) {
    return Flowable.just(WriteResult.empty());
  }

  final Map<Object, Object> toInsert = op.values().stream().collect(Collectors.toMap(keyExtractor::extract, x -> x));
  toInsert.forEach((k, v) -> {
    Object result = store.putIfAbsent(k, v);
    if (result != null) {
      throw new BackendException(String.format("Duplicate key %s for %s", k, entityType()));
    }
  });

  return Flowable.just(WriteResult.unknown());
}
 
Example #24
Source File: PublisherWindow.java    From reactive-streams-commons with Apache License 2.0 5 votes vote down vote up
public PublisherWindow(Publisher<? extends T> source, int size, int skip, 
        Supplier<? extends Queue<T>> processorQueueSupplier,
        Supplier<? extends Queue<UnicastProcessor<T>>> overflowQueueSupplier) {
    super(source);
    if (size <= 0) {
        throw new IllegalArgumentException("size > 0 required but it was " + size);
    }
    if (skip <= 0) {
        throw new IllegalArgumentException("skip > 0 required but it was " + skip);
    }
    this.size = size;
    this.skip = skip;
    this.processorQueueSupplier = Objects.requireNonNull(processorQueueSupplier, "processorQueueSupplier");
    this.overflowQueueSupplier = Objects.requireNonNull(overflowQueueSupplier, "overflowQueueSupplier");
}
 
Example #25
Source File: EvaluationStrategyImpl.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public Publisher<BindingSet> evaluate(TupleExpr expr, BindingSet bindings)
        throws QueryEvaluationException
{
    //return RxReactiveStreams.toPublisher(evaluateReactorInternal(expr, bindings));;
    return evaluateReactorInternal(expr, bindings);
            //.subscribeOn(new MDCAwareDispatcher(Environment.dispatcher(Environment.THREAD_POOL)));
}
 
Example #26
Source File: GroupedBySizeAndTimeTckPublisherTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Long> createPublisher(long elements) {
	return Spouts.iterate(0l, i->i+1l)
                    .groupedBySizeAndTime(1,1, TimeUnit.SECONDS)
                    .map(l->l.getOrElse(0,-1l))
                    .limit(elements);

}
 
Example #27
Source File: ContextPropagationMultiInterceptor.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SubscriberImplementation")
@Override
public <T> Subscriber<? super T> onSubscription(Publisher<? extends T> instance, Subscriber<? super T> subscriber) {
    Executor executor = THREAD_CONTEXT.currentContextExecutor();
    return new Subscriber<T>() {

        @Override
        public void onSubscribe(Subscription subscription) {
            executor.execute(() -> subscriber.onSubscribe(subscription));
        }

        @Override
        public void onNext(T item) {
            executor.execute(() -> subscriber.onNext(item));
        }

        @Override
        public void onError(Throwable failure) {
            executor.execute(() -> subscriber.onError(failure));
        }

        @Override
        public void onComplete() {
            executor.execute(subscriber::onComplete);
        }
    };
}
 
Example #28
Source File: RedissonReactiveSetCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<NumericResponse<SUnionStoreCommand, Long>> sUnionStore(Publisher<SUnionStoreCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKeys(), "Keys must not be null!");
        Assert.notNull(command.getKey(), "Destination key must not be null!");

        List<Object> args = new ArrayList<Object>(command.getKeys().size() + 1);
        args.add(toByteArray(command.getKey()));
        args.addAll(command.getKeys().stream().map(v -> toByteArray(v)).collect(Collectors.toList()));

        Mono<Long> m = write((byte[])args.get(0), StringCodec.INSTANCE, RedisCommands.SUNIONSTORE, args.toArray());
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example #29
Source File: RetrofitHelper.java    From C9MJ with Apache License 2.0 5 votes vote down vote up
public static <T> FlowableTransformer<LiveBaseBean<T>, T> handleLiveResult() {
    return upstream -> upstream.flatMap(new Function<LiveBaseBean<T>, Publisher<T>>() {
        @Override
        public Publisher<T> apply(final LiveBaseBean<T> baseBean) throws Exception {
            return subscriber -> {
                if (baseBean.getStatus().equals("ok")) {
                    subscriber.onNext(baseBean.getResult());
                } else {
                    subscriber.onError(new RetrofitException(baseBean.getMsg()));
                }
            };
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
 
Example #30
Source File: TemplateImpl.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<String> publisher() {
    PublisherFactory factory = engine.getPublisherFactory();
    if (factory == null) {
        throw new UnsupportedOperationException();
    }
    return factory.createPublisher(this);
}