io.netty.buffer.EmptyByteBuf Java Examples

The following examples show how to use io.netty.buffer.EmptyByteBuf. 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: PublisherAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    executeFuture = new CompletableFuture<>();
    fullHttpResponse = mock(DefaultHttpContent.class);

    when(fullHttpResponse.content()).thenReturn(new EmptyByteBuf(ByteBufAllocator.DEFAULT));
    requestContext = new RequestContext(channelPool,
                                        eventLoopGroup,
                                        AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
                                        null);

    channel = new MockChannel();
    channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
    channel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
    channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture);
    when(ctx.channel()).thenReturn(channel);

    nettyResponseHandler = ResponseHandler.getInstance();
    DefaultHttpResponse defaultFullHttpResponse = mock(DefaultHttpResponse.class);
    when(defaultFullHttpResponse.headers()).thenReturn(EmptyHttpHeaders.INSTANCE);
    when(defaultFullHttpResponse.status()).thenReturn(HttpResponseStatus.CREATED);
    when(defaultFullHttpResponse.protocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
    nettyResponseHandler.channelRead0(ctx, defaultFullHttpResponse);
}
 
Example #2
Source File: NettyServerStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void closeAfterClientHalfCloseShouldSucceed() throws Exception {
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
          .status(new AsciiString("200"))
          .set(new AsciiString("content-type"), new AsciiString("application/grpc"))
          .set(new AsciiString("grpc-status"), new AsciiString("0")));

  // Client half-closes. Listener gets halfClosed()
  stream().transportState()
      .inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);

  verify(serverListener).halfClosed();

  // Server closes. Status sent
  stream().close(Status.OK, trailers);
  assertNull("no message expected", listenerMessageQueue.poll());

  ArgumentCaptor<SendResponseHeadersCommand> cmdCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
  SendResponseHeadersCommand cmd = cmdCap.getValue();
  assertThat(cmd.stream()).isSameAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(cmd.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(cmd.endOfStream()).isTrue();

  // Sending and receiving complete. Listener gets closed()
  stream().transportState().complete();
  verify(serverListener).closed(Status.OK);
  assertNull("no message expected", listenerMessageQueue.poll());
}
 
Example #3
Source File: NettyServerStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void abortStreamAfterClientHalfCloseShouldCallClose() {
  Status status = Status.INTERNAL.withCause(new Throwable());
  // Client half-closes. Listener gets halfClosed()
  stream().transportState().inboundDataReceived(
      new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);
  verify(serverListener).halfClosed();
  // Abort from the transport layer
  stream().transportState().transportReportStatus(status);
  verify(serverListener).closed(same(status));
  assertNull("no message expected", listenerMessageQueue.poll());
}
 
Example #4
Source File: RecyclableUtil.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static boolean release(Object obj) {
    if(obj == null){
        return false;
    }
    if(obj instanceof EmptyByteBuf){
        return true;
    }

    if(obj instanceof ReferenceCounted) {
        ReferenceCounted counted = (ReferenceCounted)obj;
        try {
            int refCnt = counted.refCnt();
            if (refCnt > 0) {
                counted.release();
                return true;
            }else {
                return false;
            }
        }catch (IllegalStateException e){
            throw e;
        }
    }
    if(obj instanceof Recyclable){
        ((Recyclable) obj).recycle();
        return true;
    }
    return false;
}
 
Example #5
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void convertContentChunksToRawString_and_convertContentChunksToRawBytes_works_with_EmptyByteBuf_chunks() throws IOException {
    // given
    Charset contentCharset = CharsetUtil.UTF_8;
    String chunk1Content = UUID.randomUUID().toString();
    String chunk2Content = UUID.randomUUID().toString();
    byte[] chunk1Bytes = chunk1Content.getBytes(contentCharset);
    byte[] chunk2Bytes = chunk2Content.getBytes(contentCharset);
    ByteBuf chunk1ByteBuf = Unpooled.copiedBuffer(chunk1Bytes);
    ByteBuf chunk2ByteBuf = Unpooled.copiedBuffer(chunk2Bytes);
    Collection<HttpContent> chunkCollection = Arrays.asList(
            new DefaultHttpContent(chunk1ByteBuf),
            new DefaultHttpContent(new EmptyByteBuf(ByteBufAllocator.DEFAULT)),
            new DefaultHttpContent(chunk2ByteBuf),
            new DefaultHttpContent(new EmptyByteBuf(ByteBufAllocator.DEFAULT))
    );

    // when
    String resultString = HttpUtils.convertContentChunksToRawString(contentCharset, chunkCollection);
    byte[] resultBytes = HttpUtils.convertContentChunksToRawBytes(chunkCollection);

    // then
    String expectedResultString = chunk1Content + chunk2Content;
    assertThat(resultString, is(expectedResultString));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(chunk1Bytes);
    baos.write(chunk2Bytes);
    assertThat(resultBytes, is(baos.toByteArray()));
}
 
Example #6
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void convertContentChunksToRawBytes_returns_null_if_total_bytes_is_zero() {
    // given
    Collection<HttpContent> chunkCollection = Arrays.asList(new DefaultHttpContent(new EmptyByteBuf(ByteBufAllocator.DEFAULT)),
            new DefaultHttpContent(new EmptyByteBuf(ByteBufAllocator.DEFAULT)));

    // when
    byte[] resultBytes = HttpUtils.convertContentChunksToRawBytes(chunkCollection);

    // then
    assertThat(resultBytes, nullValue());
}
 
Example #7
Source File: ChannelOperationsHandler.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
final public void channelRead(ChannelHandlerContext ctx, Object msg) {
	if (msg == null || msg == Unpooled.EMPTY_BUFFER || msg instanceof EmptyByteBuf) {
		return;
	}
	try {
		ChannelOperations<?, ?> ops = ChannelOperations.get(ctx.channel());
		if (ops != null) {
			ops.onInboundNext(ctx, msg);
		}
		else {
			if (log.isDebugEnabled()) {
				if (msg instanceof DecoderResultProvider) {
					DecoderResult decoderResult = ((DecoderResultProvider) msg).decoderResult();
					if (decoderResult.isFailure()) {
						log.debug(format(ctx.channel(), "Decoding failed: " + msg + " : "),
								decoderResult.cause());
					}
				}

				log.debug(format(ctx.channel(), "No ChannelOperation attached. Dropping: {}"),
						toPrettyHexDump(msg));
			}
			ReferenceCountUtil.release(msg);
		}
	}
	catch (Throwable err) {
		safeRelease(msg);
		log.error(format(ctx.channel(), "Error was received while reading the incoming data." +
				" The connection will be closed."), err);
		//"FutureReturnValueIgnored" this is deliberate
		ctx.close();
		exceptionCaught(ctx, err);
	}
}
 
Example #8
Source File: MQTTPublishManager.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a message either on behalf of the client or on behalf of the broker (Will Messages)
 * @param messageId
 * @param topic
 * @param qos
 * @param payload
 * @param retain
 * @param internal if true means on behalf of the broker (skips authorisation) and does not return ack.
 * @throws Exception
 */
void sendInternal(int messageId, String topic, int qos, ByteBuf payload, boolean retain, boolean internal) throws Exception {
   synchronized (lock) {
      Message serverMessage = MQTTUtil.createServerMessageFromByteBuf(session, topic, retain, qos, payload);

      if (qos > 0) {
         serverMessage.setDurable(MQTTUtil.DURABLE_MESSAGES);
      }

      if (qos < 2 || !state.getPubRec().contains(messageId)) {
         if (qos == 2 && !internal)
            state.getPubRec().add(messageId);

         Transaction tx = session.getServerSession().newTransaction();
         try {
            if (internal) {
               session.getServer().getPostOffice().route(serverMessage, tx, true);
            } else {
               session.getServerSession().send(tx, serverMessage, true, false);
            }

            if (retain) {
               boolean reset = payload instanceof EmptyByteBuf || payload.capacity() == 0;
               session.getRetainMessageManager().handleRetainedMessage(serverMessage, topic, reset, tx);
            }
            tx.commit();
         } catch (Throwable t) {
            logger.warn(t.getMessage(), t);
            tx.rollback();
            throw t;
         }
         createMessageAck(messageId, qos, internal);
      }
   }
}
 
Example #9
Source File: RequestMessageByteHandler.java    From mongowp with Apache License 2.0 5 votes vote down vote up
@Override
protected void decodeLittleEndian(
    ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects
) throws Exception {
  if (byteBuf instanceof EmptyByteBuf) {
    //TODO: This is a workaround. Check how to prevent calling decode on channel inactive
    return;
  }

  // Header
  final RequestBaseMessage requestBaseMessage = BaseMessageDecoder.decode(
      channelHandlerContext, byteBuf);
  byteBuf.skipBytes(Ints.BYTES);  // Ignore responseTo field in header
  int requestOpCodeInt = byteBuf.readInt();
  RequestOpCode requestOpCode = RequestOpCode.getByOpcode(requestOpCodeInt);
  if (null == requestOpCode) {
    LOGGER.warn(INVALID_OPCODE_MESSAGE + requestOpCodeInt);
    throw new IllegalOperationException(requestOpCodeInt);
  }

  // Body
  MessageDecoder<?> messageDecoder = decoderLocator.getByOpCode(requestOpCode);
  if (null == messageDecoder) {
    LOGGER.error(OPERATION_NOT_IMPLEMENTED + requestOpCode);
    throw new UnsupportedOperationException(OPERATION_NOT_IMPLEMENTED + requestOpCode);
  }

  objects.add(messageDecoder.decode(byteBuf, requestBaseMessage));
}
 
Example #10
Source File: NettyServerStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void closeAfterClientHalfCloseShouldSucceed() throws Exception {
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
          .status(new AsciiString("200"))
          .set(new AsciiString("content-type"), new AsciiString("application/grpc"))
          .set(new AsciiString("grpc-status"), new AsciiString("0")));

  // Client half-closes. Listener gets halfClosed()
  stream().transportState()
      .inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);

  verify(serverListener).halfClosed();

  // Server closes. Status sent
  stream().close(Status.OK, trailers);
  assertNull("no message expected", listenerMessageQueue.poll());

  ArgumentCaptor<SendResponseHeadersCommand> cmdCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
  SendResponseHeadersCommand cmd = cmdCap.getValue();
  assertThat(cmd.stream()).isSameInstanceAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(cmd.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(cmd.endOfStream()).isTrue();

  // Sending and receiving complete. Listener gets closed()
  stream().transportState().complete();
  verify(serverListener).closed(Status.OK);
  assertNull("no message expected", listenerMessageQueue.poll());
}
 
Example #11
Source File: NettyServerStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void abortStreamAfterClientHalfCloseShouldCallClose() {
  Status status = Status.INTERNAL.withCause(new Throwable());
  // Client half-closes. Listener gets halfClosed()
  stream().transportState().inboundDataReceived(
      new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);
  verify(serverListener).halfClosed();
  // Abort from the transport layer
  stream().transportState().transportReportStatus(status);
  verify(serverListener).closed(same(status));
  assertNull("no message expected", listenerMessageQueue.poll());
}
 
Example #12
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 3 votes vote down vote up
/**
 * Caches the request body in a ServerWebExchange attribute. The attribute is
 * {@link #CACHED_REQUEST_BODY_ATTR}. If this method is called from a location that
 * can not mutate the ServerWebExchange (such as a Predicate), setting
 * cacheDecoratedRequest to true will put a {@link ServerHttpRequestDecorator} in an
 * attribute {@link #CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR} for adaptation later.
 * @param exchange the available ServerWebExchange.
 * @param cacheDecoratedRequest if true, the ServerHttpRequestDecorator will be
 * cached.
 * @param function a function that accepts a ServerHttpRequest. It can be the created
 * ServerHttpRequestDecorator or the originial if there is no body.
 * @param <T> generic type for the return {@link Mono}.
 * @return Mono of type T created by the function parameter.
 */
private static <T> Mono<T> cacheRequestBody(ServerWebExchange exchange,
		boolean cacheDecoratedRequest,
		Function<ServerHttpRequest, Mono<T>> function) {
	ServerHttpResponse response = exchange.getResponse();
	NettyDataBufferFactory factory = (NettyDataBufferFactory) response
			.bufferFactory();
	// Join all the DataBuffers so we have a single DataBuffer for the body
	return DataBufferUtils.join(exchange.getRequest().getBody())
			.defaultIfEmpty(
					factory.wrap(new EmptyByteBuf(factory.getByteBufAllocator())))
			.map(dataBuffer -> decorate(exchange, dataBuffer, cacheDecoratedRequest))
			.switchIfEmpty(Mono.just(exchange.getRequest())).flatMap(function);
}
 
Example #13
Source File: Packet.java    From JRakNet with MIT License 3 votes vote down vote up
/**
 * Creates a packet using the specified {@link ByteBuf}
 * 
 * @param buffer
 *            the {@link ByteBuf} to read from and write to, a
 *            <code>null</code> value will have a new buffer be used
 *            instead.
 * @throws IllegalArgumentException
 *             if the <code>buffer</code> is an {@link EmptyByteBuf}.
 */
public Packet(ByteBuf buffer) throws IllegalArgumentException {
	if (buffer instanceof EmptyByteBuf) {
		throw new IllegalArgumentException("No content");
	}
	this.buffer = buffer == null ? Unpooled.buffer() : buffer;
	this.input = new PacketDataInputStream(this);
	this.output = new PacketDataOutputStream(this);
}