reactor.core.publisher.SynchronousSink Java Examples

The following examples show how to use reactor.core.publisher.SynchronousSink. 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: DataBufferUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void accept(SynchronousSink<DataBuffer> sink) {
	boolean release = true;
	DataBuffer dataBuffer = this.dataBufferFactory.allocateBuffer(this.bufferSize);
	try {
		int read;
		ByteBuffer byteBuffer = dataBuffer.asByteBuffer(0, dataBuffer.capacity());
		if ((read = this.channel.read(byteBuffer)) >= 0) {
			dataBuffer.writePosition(read);
			release = false;
			sink.next(dataBuffer);
		}
		else {
			sink.complete();
		}
	}
	catch (IOException ex) {
		sink.error(ex);
	}
	finally {
		if (release) {
			release(dataBuffer);
		}
	}
}
 
Example #2
Source File: Jaxb2XmlDecoder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void accept(XMLEvent event, SynchronousSink<List<XMLEvent>> sink) {
	if (event.isStartElement()) {
		if (this.barrier == Integer.MAX_VALUE) {
			QName startElementName = event.asStartElement().getName();
			if (this.desiredName.equals(startElementName)) {
				this.events = new ArrayList<>();
				this.barrier = this.elementDepth;
			}
		}
		this.elementDepth++;
	}
	if (this.elementDepth > this.barrier) {
		Assert.state(this.events != null, "No XMLEvent List");
		this.events.add(event);
	}
	if (event.isEndElement()) {
		this.elementDepth--;
		if (this.elementDepth == this.barrier) {
			this.barrier = Integer.MAX_VALUE;
			Assert.state(this.events != null, "No XMLEvent List");
			sink.next(this.events);
		}
	}
}
 
Example #3
Source File: Files.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public FileState consumeNext(SynchronousSink<ByteBuf> sink) {
  if (inputStream == null) {
    InputStream in = getClass().getClassLoader().getResourceAsStream(fileName);
    if (in == null) {
      sink.error(new FileNotFoundException(fileName));
      return this;
    }
    this.inputStream = new BufferedInputStream(in);
    this.chunkBytes = new byte[chunkSizeBytes];
  }
  try {
    int consumedBytes = inputStream.read(chunkBytes);
    if (consumedBytes == -1) {
      sink.complete();
    } else {
      sink.next(Unpooled.copiedBuffer(chunkBytes, 0, consumedBytes));
    }
  } catch (IOException e) {
    sink.error(e);
  }
  return this;
}
 
Example #4
Source File: HttpClientBeanPostProcessorTest.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
void mapConnect_should_setup_reactor_context_no_currentTraceContext() {
	TracingMapConnect tracingMapConnect = new TracingMapConnect(() -> null);

	Mono<Connection> original = Mono.just(connection)
			.handle(new BiConsumer<Connection, SynchronousSink<Connection>>() {
				@Override
				public void accept(Connection t, SynchronousSink<Connection> ctx) {
					assertThat(ctx.currentContext().getOrEmpty(TraceContext.class))
							.isEmpty();
					assertThat(ctx.currentContext().get(PendingSpan.class))
							.isNotNull();
				}
			});

	// Wrap and run the assertions
	tracingMapConnect.apply(original).log().subscribe();
}
 
Example #5
Source File: HttpClientBeanPostProcessorTest.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
void mapConnect_should_setup_reactor_context_currentTraceContext() {
	TracingMapConnect tracingMapConnect = new TracingMapConnect(() -> traceContext);

	Mono<Connection> original = Mono.just(connection)
			.handle(new BiConsumer<Connection, SynchronousSink<Connection>>() {
				@Override
				public void accept(Connection t, SynchronousSink<Connection> ctx) {
					assertThat(ctx.currentContext().get(TraceContext.class))
							.isSameAs(traceContext);
					assertThat(ctx.currentContext().get(PendingSpan.class))
							.isNotNull();
				}
			});

	// Wrap and run the assertions
	tracingMapConnect.apply(original).log().subscribe();
}
 
Example #6
Source File: DataBufferUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void accept(SynchronousSink<DataBuffer> sink) {
	boolean release = true;
	DataBuffer dataBuffer = this.dataBufferFactory.allocateBuffer(this.bufferSize);
	try {
		int read;
		ByteBuffer byteBuffer = dataBuffer.asByteBuffer(0, dataBuffer.capacity());
		if ((read = this.channel.read(byteBuffer)) >= 0) {
			dataBuffer.writePosition(read);
			release = false;
			sink.next(dataBuffer);
		}
		else {
			sink.complete();
		}
	}
	catch (IOException ex) {
		sink.error(ex);
	}
	finally {
		if (release) {
			release(dataBuffer);
		}
	}
}
 
Example #7
Source File: MySqlResult.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private <T> void processRow(RowMessage message, SynchronousSink<T> sink, BiFunction<Row, RowMetadata, ? extends T> f) {
    MySqlRowMetadata rowMetadata = this.rowMetadata;

    if (rowMetadata == null) {
        ReferenceCountUtil.safeRelease(message);
        sink.error(new IllegalStateException("No MySqlRowMetadata available"));
        return;
    }

    FieldValue[] fields;
    T t;

    try {
        fields = message.decode(isBinary, rowMetadata.unwrap());
    } finally {
        // Release row messages' reader.
        ReferenceCountUtil.safeRelease(message);
    }

    try {
        // Can NOT just sink.next(f.apply(...)) because of finally release
        t = f.apply(new MySqlRow(fields, rowMetadata, codecs, isBinary, context), rowMetadata);
    } finally {
        // Release decoded field values.
        for (FieldValue field : fields) {
            ReferenceCountUtil.safeRelease(field);
        }
    }

    sink.next(t);
}
 
Example #8
Source File: FrameReassembler.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
void reassembleFrame(ByteBuf frame, SynchronousSink<ByteBuf> sink) {
  try {
    FrameType frameType = FrameHeaderCodec.frameType(frame);
    int streamId = FrameHeaderCodec.streamId(frame);
    switch (frameType) {
      case CANCEL:
      case ERROR:
        cancelAssemble(streamId);
    }

    if (!frameType.isFragmentable()) {
      sink.next(frame);
      return;
    }

    boolean hasFollows = FrameHeaderCodec.hasFollows(frame);

    if (hasFollows) {
      handleFollowsFlag(frame, streamId, frameType);
    } else {
      handleNoFollowsFlag(frame, sink, streamId);
    }

  } catch (Throwable t) {
    logger.error("error reassemble frame", t);
    sink.error(t);
  }
}
 
Example #9
Source File: FrameFragmenter.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
static Publisher<ByteBuf> fragmentFrame(
    ByteBufAllocator allocator, int mtu, final ByteBuf frame, FrameType frameType) {
  ByteBuf metadata = getMetadata(frame, frameType);
  ByteBuf data = getData(frame, frameType);
  int streamId = FrameHeaderCodec.streamId(frame);
  return Flux.generate(
          new Consumer<SynchronousSink<ByteBuf>>() {
            boolean first = true;

            @Override
            public void accept(SynchronousSink<ByteBuf> sink) {
              ByteBuf byteBuf;
              if (first) {
                first = false;
                byteBuf =
                    encodeFirstFragment(
                        allocator, mtu, frame, frameType, streamId, metadata, data);
              } else {
                byteBuf = encodeFollowsFragment(allocator, mtu, streamId, metadata, data);
              }

              sink.next(byteBuf);
              if (!metadata.isReadable() && !data.isReadable()) {
                sink.complete();
              }
            }
          })
      .doFinally(signalType -> ReferenceCountUtil.safeRelease(frame));
}
 
Example #10
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(ServerMessage message, SynchronousSink<ServerMessage> sink) {
    if (message instanceof ErrorMessage) {
        sink.error(ExceptionFactory.createException((ErrorMessage) message, this.sql));
    } else {
        sink.next(message);
    }
}
 
Example #11
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(ServerMessage message, SynchronousSink<ServerMessage> sink) {
    if (message instanceof ErrorMessage) {
        sink.error(ExceptionFactory.createException((ErrorMessage) message, sql));
    } else {
        sink.next(message);
    }
}
 
Example #12
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(ServerMessage message, SynchronousSink<ServerMessage> sink) {
    if (next) {
        return;
    }
    next = true;

    if (message instanceof ErrorMessage) {
        sink.error(ExceptionFactory.createException((ErrorMessage) message, sql));
    } else {
        sink.next(message);
    }
}
 
Example #13
Source File: AppCacheManifestTransformer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void accept(SynchronousSink<LineInfo> sink) {
	if (this.scanner.hasNext()) {
		String line = this.scanner.nextLine();
		LineInfo current = new LineInfo(line, this.previous);
		sink.next(current);
		this.previous = current;
	}
	else {
		sink.complete();
	}
}
 
Example #14
Source File: MySqlResult.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private <T> void handleResult(ServerMessage message, SynchronousSink<T> sink, BiFunction<Row, RowMetadata, ? extends T> f) {
    if (message instanceof SyntheticMetadataMessage) {
        DefinitionMetadataMessage[] metadataMessages = ((SyntheticMetadataMessage) message).unwrap();
        if (metadataMessages.length == 0) {
            return;
        }
        this.rowMetadata = MySqlRowMetadata.create(metadataMessages);
    } else if (message instanceof RowMessage) {
        processRow((RowMessage) message, sink, f);
    } else {
        ReferenceCountUtil.safeRelease(message);
    }
}
 
Example #15
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static void inboundHandle(Object msg, SynchronousSink<ServerMessage> sink) {
    if (msg instanceof ServerMessage) {
        if (msg instanceof ReferenceCounted) {
            ((ReferenceCounted) msg).retain();
        }
        sink.next((ServerMessage) msg);
    } else {
        // ReferenceCounted will released by Netty.
        sink.error(new IllegalStateException("Impossible inbound type: " + msg.getClass()));
    }
}
 
Example #16
Source File: AppCacheManifestTransformer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void accept(SynchronousSink<LineInfo> sink) {
	if (this.scanner.hasNext()) {
		String line = this.scanner.nextLine();
		LineInfo current = new LineInfo(line, this.previous);
		sink.next(current);
		this.previous = current;
	}
	else {
		sink.complete();
	}
}
 
Example #17
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(ServerMessage message, SynchronousSink<ServerMessage> sink) {
    if (message instanceof ErrorMessage) {
        sink.error(ExceptionFactory.createException((ErrorMessage) message, this.sql));
    } else {
        sink.next(message);
    }
}
 
Example #18
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(ServerMessage message, SynchronousSink<ServerMessage> sink) {
    if (message instanceof ErrorMessage) {
        sink.error(ExceptionFactory.createException((ErrorMessage) message, sql));
    } else {
        sink.next(message);
    }
}
 
Example #19
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(ServerMessage message, SynchronousSink<ServerMessage> sink) {
    if (next) {
        return;
    }
    next = true;

    if (message instanceof ErrorMessage) {
        sink.error(ExceptionFactory.createException((ErrorMessage) message, sql));
    } else {
        sink.next(message);
    }
}
 
Example #20
Source File: MySqlResult.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private <T> void processRow(RowMessage message, SynchronousSink<T> sink, BiFunction<Row, RowMetadata, ? extends T> f) {
    MySqlRowMetadata rowMetadata = this.rowMetadata;

    if (rowMetadata == null) {
        ReferenceCountUtil.safeRelease(message);
        sink.error(new IllegalStateException("No MySqlRowMetadata available"));
        return;
    }

    FieldValue[] fields;
    T t;

    try {
        fields = message.decode(isBinary, rowMetadata.unwrap());
    } finally {
        // Release row messages' reader.
        ReferenceCountUtil.safeRelease(message);
    }

    try {
        // Can NOT just sink.next(f.apply(...)) because of finally release
        t = f.apply(new MySqlRow(fields, rowMetadata, codecs, isBinary, context), rowMetadata);
    } finally {
        // Release decoded field values.
        for (FieldValue field : fields) {
            ReferenceCountUtil.safeRelease(field);
        }
    }

    sink.next(t);
}
 
Example #21
Source File: MySqlResult.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private <T> void handleResult(ServerMessage message, SynchronousSink<T> sink, BiFunction<Row, RowMetadata, ? extends T> f) {
    if (message instanceof SyntheticMetadataMessage) {
        DefinitionMetadataMessage[] metadataMessages = ((SyntheticMetadataMessage) message).unwrap();
        if (metadataMessages.length == 0) {
            return;
        }
        this.rowMetadata = MySqlRowMetadata.create(metadataMessages);
    } else if (message instanceof RowMessage) {
        processRow((RowMessage) message, sink, f);
    } else {
        ReferenceCountUtil.safeRelease(message);
    }
}
 
Example #22
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static void inboundHandle(Object msg, SynchronousSink<ServerMessage> sink) {
    if (msg instanceof ServerMessage) {
        if (msg instanceof ReferenceCounted) {
            ((ReferenceCounted) msg).retain();
        }
        sink.next((ServerMessage) msg);
    } else {
        // ReferenceCounted will released by Netty.
        sink.error(new IllegalStateException("Impossible inbound type: " + msg.getClass()));
    }
}
 
Example #23
Source File: R024_FluxGenerate.java    From reactor-workshop with GNU General Public License v3.0 4 votes vote down vote up
private void readLine(BufferedReader file, SynchronousSink<String> sink) {
	//TODO Implement, remember about end of file,
}
 
Example #24
Source File: FluxReactiveSeq.java    From cyclops with Apache License 2.0 4 votes vote down vote up
public static <T> ReactiveSeq<T> generate(Consumer<SynchronousSink<T>> generator) {
    return reactiveSeq(Flux.generate(generator));
}
 
Example #25
Source File: FluxReactiveSeq.java    From cyclops with Apache License 2.0 4 votes vote down vote up
public static <T, S> ReactiveSeq<T> generate(Callable<S> stateSupplier, BiFunction<S, SynchronousSink<T>, S> generator) {
    return reactiveSeq(Flux.generate(stateSupplier,generator));
}
 
Example #26
Source File: FluxReactiveSeq.java    From cyclops with Apache License 2.0 4 votes vote down vote up
public static <T, S> ReactiveSeq<T> generate(Callable<S> stateSupplier, BiFunction<S, SynchronousSink<T>, S> generator, Consumer<? super S> stateConsumer) {
    return reactiveSeq(Flux.generate(stateSupplier,generator,stateConsumer));
}
 
Example #27
Source File: ReactorUtils.java    From james-project with Apache License 2.0 4 votes vote down vote up
public static <T> BiConsumer<Optional<T>, SynchronousSink<T>> publishIfPresent() {
    return (element, sink) -> element.ifPresent(sink::next);
}