Java Code Examples for org.reactivestreams.Publisher

The following examples show how to use org.reactivestreams.Publisher. These examples are extracted from open source projects. 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 Project: redisson   Author: redisson   File: RedissonReactiveGeoCommands.java    License: 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 #2
Source Project: rsocket-java   Author: rsocket   File: FrameFragmenterTest.java    License: 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 Project: redisson   Author: redisson   File: RedissonReactiveStreamCommands.java    License: 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 #4
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractClientHttpRequest.java    License: 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 #5
Source Project: redisson   Author: redisson   File: RedissonReactiveZSetCommands.java    License: 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 #6
Source Project: reactor-core   Author: reactor   File: FluxUsingWhen.java    License: 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 #7
Source Project: reactor-core   Author: reactor   File: MonoZip.java    License: 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 #8
Source Project: reactor-core   Author: reactor   File: LiftFunctionTest.java    License: 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 #9
Source Project: rsocket-java   Author: rsocket   File: RSocketLeaseTest.java    License: 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 Project: Shadbot   Author: Shadorc   File: PremiumCollection.java    License: 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 #11
Source Project: redisson   Author: redisson   File: RedissonReactiveNumberCommands.java    License: 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 #12
Source Project: reactor-netty   Author: reactor   File: ChannelOperations.java    License: 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 #13
Source Project: java-technology-stack   Author: codeEngraver   File: ServerSentEventHttpMessageWriterTests.java    License: 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 #14
Source Project: redisson   Author: redisson   File: RedissonReactiveStringCommands.java    License: 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 #15
Source Project: reactive-streams-commons   Author: reactor   File: PublisherBufferBoundaryAndSize.java    License: 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 #16
Source Project: redisson   Author: redisson   File: RedissonReactiveListCommands.java    License: 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 #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: ReactorNettyWebSocketSession.java    License: 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 #18
Source Project: reactive-streams-commons   Author: reactor   File: PublisherWindow.java    License: 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 #19
Source Project: smallrye-mutiny   Author: smallrye   File: ContextPropagationMultiInterceptor.java    License: 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 #20
Source Project: C9MJ   Author: 452MJ   File: RetrofitHelper.java    License: 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 #21
Source Project: quarkus   Author: quarkusio   File: TemplateImpl.java    License: 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);
}
 
Example #22
Source Project: reactor-core   Author: reactor   File: FluxWindowTest.java    License: 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 #23
@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 #24
Source Project: reactor-core   Author: reactor   File: FluxBufferWhen.java    License: 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 #25
Source Project: redisson   Author: redisson   File: RedissonReactiveSetCommands.java    License: 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 #26
Source Project: semagrow   Author: semagrow   File: EvaluationStrategyImpl.java    License: 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 #27
Source Project: cyclops   Author: aol   File: GroupedBySizeAndTimeTckPublisherTest.java    License: 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 #28
Source Project: immutables   Author: immutables   File: InMemoryBackend.java    License: 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 #29
Source Project: james-project   Author: apache   File: DeletedMessageVaultHook.java    License: 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 #30
Source Project: quarkus   Author: quarkusio   File: MutinyContextEndpoint.java    License: 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;
}