Java Code Examples for io.netty.handler.codec.http.LastHttpContent#EMPTY_LAST_CONTENT

The following examples show how to use io.netty.handler.codec.http.LastHttpContent#EMPTY_LAST_CONTENT . 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: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpgradeEmptyEnd() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
    LastHttpContent end = LastHttpContent.EMPTY_LAST_CONTENT;
    assertTrue(ch.writeOutbound(end));

    Http2DataFrame emptyFrame = ch.readOutbound();
    try {
        assertThat(emptyFrame.content().readableBytes(), is(0));
        assertTrue(emptyFrame.isEndStream());
    } finally {
        emptyFrame.release();
    }

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example 2
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeEmptyEndAsClient() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    LastHttpContent end = LastHttpContent.EMPTY_LAST_CONTENT;
    assertTrue(ch.writeOutbound(end));

    Http2DataFrame emptyFrame = ch.readOutbound();
    try {
        assertThat(emptyFrame.content().readableBytes(), is(0));
        assertTrue(emptyFrame.isEndStream());
    } finally {
        emptyFrame.release();
    }

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example 3
Source File: WebsocketServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onInboundNext(ChannelHandlerContext ctx, Object frame) {
	if (frame instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) frame).isFinalFragment()) {
		if (log.isDebugEnabled()) {
			log.debug(format(channel(), "CloseWebSocketFrame detected. Closing Websocket"));
		}
		CloseWebSocketFrame close = (CloseWebSocketFrame) frame;
		sendCloseNow(new CloseWebSocketFrame(true,
				close.rsv(),
				close.content()), f -> terminate()); // terminate() will invoke onInboundComplete()
		return;
	}
	if (!this.proxyPing && frame instanceof PingWebSocketFrame) {
		//"FutureReturnValueIgnored" this is deliberate
		ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) frame).content()));
		ctx.read();
		return;
	}
	if (frame != LastHttpContent.EMPTY_LAST_CONTENT) {
		super.onInboundNext(ctx, frame);
	}
}
 
Example 4
Source File: ConfigHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeAuthFailureBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
        new HttpResponseStatus(401, "Unauthorized"));
    HttpContent responseChunk = LastHttpContent.EMPTY_LAST_CONTENT;

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.ACCESS_ERROR, event.status());
    assertEquals("Unauthorized", event.config());
    assertTrue(requestQueue.isEmpty());
}
 
Example 5
Source File: ConfigHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeSuccessFlushResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
        new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = LastHttpContent.EMPTY_LAST_CONTENT;

    FlushRequest requestMock = mock(FlushRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    FlushResponse event = (FlushResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("OK", event.content());
    assertTrue(requestQueue.isEmpty());
}
 
Example 6
Source File: HttpPostRequestEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private HttpContent lastChunk() {
    isLastChunk = true;
    if (currentBuffer == null) {
        isLastChunkSent = true;
        // LastChunk with no more data
        return LastHttpContent.EMPTY_LAST_CONTENT;
    }
    // NextChunk as last non empty from buffer
    ByteBuf buffer = currentBuffer;
    currentBuffer = null;
    return new DefaultHttpContent(buffer);
}
 
Example 7
Source File: BadClientSilencer.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
    // This handler is the last inbound handler.
    // This means msg has not been handled by any previous handler.
    ctx.close();

    if (msg != LastHttpContent.EMPTY_LAST_CONTENT) {
        onUnknownMessage(msg);
    }
}
 
Example 8
Source File: BadClientSilencer.java    From redant with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
    // This handler is the last inbound handler.
    // This means msg has not been handled by any previous handler.
    ctx.close();

    if (msg != LastHttpContent.EMPTY_LAST_CONTENT) {
        onUnknownMessage(msg);
    }
}
 
Example 9
Source File: LastHttpContentHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void lastHttpContentReceived_shouldSetAttribute() {
    LastHttpContent lastHttpContent = LastHttpContent.EMPTY_LAST_CONTENT;
    contentHandler.channelRead(handlerContext, lastHttpContent);

    assertThat(channel.attr(LAST_HTTP_CONTENT_RECEIVED_KEY).get()).isTrue();
}
 
Example 10
Source File: Http1ObjectEncoder.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public final ChannelFuture doWriteData(int id, int streamId, HttpData data, boolean endStream) {
    if (!isWritable(id)) {
        ReferenceCountUtil.safeRelease(data);
        return newClosedSessionFuture();
    }

    final int length = data.length();
    if (length == 0) {
        ReferenceCountUtil.safeRelease(data);
        final HttpContent content = endStream ? LastHttpContent.EMPTY_LAST_CONTENT : EMPTY_CONTENT;
        final ChannelFuture future = write(id, content, endStream);
        ch.flush();
        return future;
    }

    try {
        if (!protocol.isTls() || length <= MAX_TLS_DATA_LENGTH) {
            // Cleartext connection or data.length() <= MAX_TLS_DATA_LENGTH
            return doWriteUnsplitData(id, data, endStream);
        } else {
            // TLS or data.length() > MAX_TLS_DATA_LENGTH
            return doWriteSplitData(id, data, endStream);
        }
    } catch (Throwable t) {
        return newFailedFuture(t);
    }
}
 
Example 11
Source File: Http1ObjectEncoder.java    From armeria with Apache License 2.0 5 votes vote down vote up
private LastHttpContent convertTrailers(HttpHeaders inputHeaders) {
    if (inputHeaders.isEmpty()) {
        return LastHttpContent.EMPTY_LAST_CONTENT;
    }

    final LastHttpContent lastContent = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, false);
    final io.netty.handler.codec.http.HttpHeaders outputHeaders = lastContent.trailingHeaders();
    convertTrailers(inputHeaders, outputHeaders);
    return lastContent;
}
 
Example 12
Source File: NettyConnector.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * HTTP upgrade response will be decode by Netty as 2 objects:
 * - 1 HttpObject corresponding to the 101 SWITCHING PROTOCOL headers
 * - 1 EMPTY_LAST_CONTENT
 *
 * The HTTP upgrade is successful whne the 101 SWITCHING PROTOCOL has been received (handshakeComplete = true)
 * but the latch is count down only when the following EMPTY_LAST_CONTENT is also received.
 * Otherwise this ChannelHandler would be removed too soon and the ActiveMQChannelHandler would handle the
 * EMPTY_LAST_CONTENT (while it is expecitng only ByteBuf).
 */
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
   if (logger.isDebugEnabled()) {
      logger.debug("Received msg=" + msg);
   }
   if (msg instanceof HttpResponse) {
      HttpResponse response = (HttpResponse) msg;
      if (response.status().code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code() && response.headers().get(HttpHeaderNames.UPGRADE).equals(ACTIVEMQ_REMOTING)) {
         String accept = response.headers().get(SEC_ACTIVEMQ_REMOTING_ACCEPT);
         String expectedResponse = createExpectedResponse(MAGIC_NUMBER, ctx.channel().attr(REMOTING_KEY).get());

         if (expectedResponse.equals(accept)) {
            // HTTP upgrade is successful but let's wait to receive the EMPTY_LAST_CONTENT to count down the latch
            handshakeComplete = true;
         } else {
            // HTTP upgrade failed
            ActiveMQClientLogger.LOGGER.httpHandshakeFailed(msg);
            ctx.close();
            latch.countDown();
         }
         return;
      }
   } else if (msg == LastHttpContent.EMPTY_LAST_CONTENT && handshakeComplete) {
      // remove the http handlers and flag the activemq channel handler as active
      pipeline.remove(httpClientCodec);
      pipeline.remove(this);
      ActiveMQChannelHandler channelHandler = pipeline.get(ActiveMQChannelHandler.class);
      channelHandler.active = true;
   }
   if (!handshakeComplete) {
      ActiveMQClientLogger.LOGGER.httpHandshakeFailed(msg);
      ctx.close();
   }
   latch.countDown();
}
 
Example 13
Source File: ChunkedInputs.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public @Nullable HttpContent readChunk(ByteBufAllocator allocator) throws Exception {
    if (hasSentTerminatingChunk) {
        return null;
    }
    ByteBuf nextChunk = readNextChunk();
    if (nextChunk != null) {
        return new DefaultHttpContent(nextChunk);
    }
    // chunked transfer encoding must be terminated by a final chunk of length zero
    hasSentTerminatingChunk = true;
    return LastHttpContent.EMPTY_LAST_CONTENT;
}
 
Example 14
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onInboundNext(ChannelHandlerContext ctx, Object msg) {
	if (msg instanceof FullHttpResponse) {
		started = true;
		channel().pipeline()
		         .remove(HttpObjectAggregator.class);
		FullHttpResponse response = (FullHttpResponse) msg;

		setNettyResponse(response);

		if (notRedirected(response)) {


			try {
				handshaker.finishHandshake(channel(), response);
				listener().onStateChange(this, HttpClientState.RESPONSE_RECEIVED);
			}
			catch (Exception e) {
				onInboundError(e);
			}
			finally {
				//Release unused content (101 status)
				response.content()
				        .release();
			}

		}
		else {
			response.content()
			        .release();
			listener().onUncaughtException(this, redirecting);
		}
		return;
	}
	if (!this.proxyPing && msg instanceof PingWebSocketFrame) {
		//"FutureReturnValueIgnored" this is deliberate
		ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) msg).content()));
		ctx.read();
		return;
	}
	if (msg instanceof CloseWebSocketFrame &&
			((CloseWebSocketFrame)msg).isFinalFragment()) {
		if (log.isDebugEnabled()) {
			log.debug(format(channel(), "CloseWebSocketFrame detected. Closing Websocket"));
		}
		CloseWebSocketFrame close = (CloseWebSocketFrame) msg;
		sendCloseNow(new CloseWebSocketFrame(true,
				close.rsv(),
				close.content()));
		onInboundComplete();
	}
	else if (msg != LastHttpContent.EMPTY_LAST_CONTENT) {
		super.onInboundNext(ctx, msg);
	}
}
 
Example 15
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
protected void onInboundNext(ChannelHandlerContext ctx, Object msg) {
	if (msg instanceof HttpRequest) {
		try {
			listener().onStateChange(this, HttpServerState.REQUEST_RECEIVED);
		}
		catch (Exception e) {
			onInboundError(e);
			ReferenceCountUtil.release(msg);
			return;
		}
		if (msg instanceof FullHttpRequest) {
			FullHttpRequest request = (FullHttpRequest) msg;
			if (request.content().readableBytes() > 0) {
				super.onInboundNext(ctx, msg);
			}
			else {
				request.release();
			}
			if (isHttp2()) {
				//force auto read to enable more accurate close selection now inbound is done
				channel().config().setAutoRead(true);
				onInboundComplete();
			}
		}
		return;
	}
	if (msg instanceof HttpContent) {
		if (msg != LastHttpContent.EMPTY_LAST_CONTENT) {
			super.onInboundNext(ctx, msg);
		}
		if (msg instanceof LastHttpContent) {
			//force auto read to enable more accurate close selection now inbound is done
			channel().config().setAutoRead(true);
			onInboundComplete();
		}
	}
	else {
		super.onInboundNext(ctx, msg);
	}
}