migrate java8: use lambda and method reference (#8781)

Motivation:

We can use lambdas now as we use Java8.

Modification:

use lambda function for all package, #8751 only migrate transport package.

Result:

Code cleanup.
This commit is contained in:
田欧 2019-01-29 21:06:05 +08:00 committed by Norman Maurer
parent 185efa5b7c
commit 6222101924
192 changed files with 2727 additions and 4999 deletions

View File

@ -28,109 +28,59 @@ public interface ByteBufProcessor extends ByteProcessor {
* @deprecated Use {@link ByteProcessor#FIND_NUL}.
*/
@Deprecated
ByteBufProcessor FIND_NUL = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != 0;
}
};
ByteBufProcessor FIND_NUL = value -> value != 0;
/**
* @deprecated Use {@link ByteProcessor#FIND_NON_NUL}.
*/
@Deprecated
ByteBufProcessor FIND_NON_NUL = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value == 0;
}
};
ByteBufProcessor FIND_NON_NUL = value -> value == 0;
/**
* @deprecated Use {@link ByteProcessor#FIND_CR}.
*/
@Deprecated
ByteBufProcessor FIND_CR = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != '\r';
}
};
ByteBufProcessor FIND_CR = value -> value != '\r';
/**
* @deprecated Use {@link ByteProcessor#FIND_NON_CR}.
*/
@Deprecated
ByteBufProcessor FIND_NON_CR = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value == '\r';
}
};
ByteBufProcessor FIND_NON_CR = value -> value == '\r';
/**
* @deprecated Use {@link ByteProcessor#FIND_LF}.
*/
@Deprecated
ByteBufProcessor FIND_LF = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != '\n';
}
};
ByteBufProcessor FIND_LF = value -> value != '\n';
/**
* @deprecated Use {@link ByteProcessor#FIND_NON_LF}.
*/
@Deprecated
ByteBufProcessor FIND_NON_LF = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value == '\n';
}
};
ByteBufProcessor FIND_NON_LF = value -> value == '\n';
/**
* @deprecated Use {@link ByteProcessor#FIND_CRLF}.
*/
@Deprecated
ByteBufProcessor FIND_CRLF = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != '\r' && value != '\n';
}
};
ByteBufProcessor FIND_CRLF = value -> value != '\r' && value != '\n';
/**
* @deprecated Use {@link ByteProcessor#FIND_NON_CRLF}.
*/
@Deprecated
ByteBufProcessor FIND_NON_CRLF = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value == '\r' || value == '\n';
}
};
ByteBufProcessor FIND_NON_CRLF = value -> value == '\r' || value == '\n';
/**
* @deprecated Use {@link ByteProcessor#FIND_LINEAR_WHITESPACE}.
*/
@Deprecated
ByteBufProcessor FIND_LINEAR_WHITESPACE = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != ' ' && value != '\t';
}
};
ByteBufProcessor FIND_LINEAR_WHITESPACE = value -> value != ' ' && value != '\t';
/**
* @deprecated Use {@link ByteProcessor#FIND_NON_LINEAR_WHITESPACE}.
*/
@Deprecated
ByteBufProcessor FIND_NON_LINEAR_WHITESPACE = new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value == ' ' || value == '\t';
}
};
ByteBufProcessor FIND_NON_LINEAR_WHITESPACE = value -> value == ' ' || value == '\t';
}

View File

@ -1254,12 +1254,7 @@ public final class ByteBufUtil {
/**
* Aborts on a byte which is not a valid ASCII character.
*/
private static final ByteProcessor FIND_NON_ASCII = new ByteProcessor() {
@Override
public boolean process(byte value) {
return value >= 0;
}
};
private static final ByteProcessor FIND_NON_ASCII = value -> value >= 0;
/**
* Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid

View File

@ -2089,16 +2089,13 @@ public abstract class AbstractByteBufTest {
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (errorRef.get() == null && counter.decrementAndGet() > 0) {
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
}
} catch (Throwable cause) {
errorRef.compareAndSet(null, cause);
Thread thread = new Thread(() -> {
try {
while (errorRef.get() == null && counter.decrementAndGet() > 0) {
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
}
} catch (Throwable cause) {
errorRef.compareAndSet(null, cause);
}
});
threads.add(thread);
@ -2358,34 +2355,31 @@ public abstract class AbstractByteBufTest {
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
TestGatheringByteChannel channel = new TestGatheringByteChannel();
new Thread(() -> {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
TestGatheringByteChannel channel = new TestGatheringByteChannel();
while (buf.isReadable()) {
try {
buf.readBytes(channel, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
while (buf.isReadable()) {
try {
buf.readBytes(channel, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
assertArrayEquals(bytes, channel.writtenBytes());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
assertArrayEquals(bytes, channel.writtenBytes());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}).start();
}
@ -2413,34 +2407,31 @@ public abstract class AbstractByteBufTest {
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
new Thread(() -> {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (buf.isReadable()) {
try {
buf.readBytes(out, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
while (buf.isReadable()) {
try {
buf.readBytes(out, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
assertArrayEquals(bytes, out.toByteArray());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
assertArrayEquals(bytes, out.toByteArray());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}).start();
}
@ -2469,33 +2460,30 @@ public abstract class AbstractByteBufTest {
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (cause.get() == null && latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
byte[] array = new byte[8];
buf.readBytes(array);
assertArrayEquals(bytes, array);
Arrays.fill(array, (byte) 0);
buf.getBytes(0, array);
assertArrayEquals(bytes, array);
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
new Thread(() -> {
while (cause.get() == null && latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
byte[] array = new byte[8];
buf.readBytes(array);
assertArrayEquals(bytes, array);
Arrays.fill(array, (byte) 0);
buf.getBytes(0, array);
assertArrayEquals(bytes, array);
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}).start();
}
@ -4643,30 +4631,24 @@ public abstract class AbstractByteBufTest {
final ByteBuf buffer = newBuffer(4);
assertEquals(1, buffer.refCnt());
final AtomicInteger cnt = new AtomicInteger(Integer.MAX_VALUE);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
boolean released;
if (parameter) {
released = buffer.release(buffer.refCnt());
} else {
released = buffer.release();
}
assertTrue(released);
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
cnt.set(buffer.refCnt());
latch.countDown();
}
});
t2.start();
try {
// Keep Thread alive a bit so the ThreadLocal caches are not freed
innerLatch.await();
} catch (InterruptedException ignore) {
// ignore
}
Thread t1 = new Thread(() -> {
boolean released;
if (parameter) {
released = buffer.release(buffer.refCnt());
} else {
released = buffer.release();
}
assertTrue(released);
Thread t2 = new Thread(() -> {
cnt.set(buffer.refCnt());
latch.countDown();
});
t2.start();
try {
// Keep Thread alive a bit so the ThreadLocal caches are not freed
innerLatch.await();
} catch (InterruptedException ignore) {
// ignore
}
});
t1.start();

View File

@ -680,16 +680,13 @@ public class ByteBufUtilTest {
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (errorRef.get() == null && counter.decrementAndGet() > 0) {
assertTrue(ByteBufUtil.isText(buffer, CharsetUtil.ISO_8859_1));
}
} catch (Throwable cause) {
errorRef.compareAndSet(null, cause);
Thread thread = new Thread(() -> {
try {
while (errorRef.get() == null && counter.decrementAndGet() > 0) {
assertTrue(ByteBufUtil.isText(buffer, CharsetUtil.ISO_8859_1));
}
} catch (Throwable cause) {
errorRef.compareAndSet(null, cause);
}
});
threads.add(thread);

View File

@ -257,23 +257,20 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<Poo
final AtomicBoolean threadCachesCreated = new AtomicBoolean(true);
final Runnable task = new Runnable() {
@Override
public void run() {
ByteBuf buf = allocator.newHeapBuffer(1024, 1024);
for (int i = 0; i < buf.capacity(); i++) {
buf.writeByte(0);
}
// Make sure that thread caches are actually created,
// so that down below we are not testing for zero
// thread caches without any of them ever having been initialized.
if (allocator.metric().numThreadLocalCaches() == 0) {
threadCachesCreated.set(false);
}
buf.release();
final Runnable task = () -> {
ByteBuf buf = allocator.newHeapBuffer(1024, 1024);
for (int i = 0; i < buf.capacity(); i++) {
buf.writeByte(0);
}
// Make sure that thread caches are actually created,
// so that down below we are not testing for zero
// thread caches without any of them ever having been initialized.
if (allocator.metric().numThreadLocalCaches() == 0) {
threadCachesCreated.set(false);
}
buf.release();
};
for (int i = 0; i < numArenas; i++) {
@ -368,39 +365,32 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<Poo
throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch cacheLatch = new CountDownLatch(1);
final Thread t = new FastThreadLocalThread(new Runnable() {
final Thread t = new FastThreadLocalThread(() -> {
ByteBuf buf = allocator.newHeapBuffer(1024, 1024);
@Override
public void run() {
ByteBuf buf = allocator.newHeapBuffer(1024, 1024);
// Countdown the latch after we allocated a buffer. At this point the cache must exists.
cacheLatch.countDown();
// Countdown the latch after we allocated a buffer. At this point the cache must exists.
cacheLatch.countDown();
buf.writeZero(buf.capacity());
buf.writeZero(buf.capacity());
try {
latch.await();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
buf.release();
FastThreadLocal.removeAll();
try {
latch.await();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
buf.release();
FastThreadLocal.removeAll();
});
t.start();
// Wait until we allocated a buffer and so be sure the thread was started and the cache exists.
cacheLatch.await();
return new ThreadCache() {
@Override
public void destroy() throws InterruptedException {
latch.countDown();
t.join();
}
return () -> {
latch.countDown();
t.join();
};
}

View File

@ -57,24 +57,14 @@ public class CombinedHttpHeaders extends DefaultHttpHeaders {
private CsvValueEscaper<Object> objectEscaper() {
if (objectEscaper == null) {
objectEscaper = new CsvValueEscaper<Object>() {
@Override
public CharSequence escape(Object value) {
return StringUtil.escapeCsv(valueConverter().convertObject(value), true);
}
};
objectEscaper = value -> StringUtil.escapeCsv(valueConverter().convertObject(value), true);
}
return objectEscaper;
}
private CsvValueEscaper<CharSequence> charSequenceEscaper() {
if (charSequenceEscaper == null) {
charSequenceEscaper = new CsvValueEscaper<CharSequence>() {
@Override
public CharSequence escape(CharSequence value) {
return StringUtil.escapeCsv(value, true);
}
};
charSequenceEscaper = value -> StringUtil.escapeCsv(value, true);
}
return charSequenceEscaper;
}

View File

@ -44,30 +44,24 @@ import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER;
*/
public class DefaultHttpHeaders extends HttpHeaders {
private static final int HIGHEST_INVALID_VALUE_CHAR_MASK = ~15;
private static final ByteProcessor HEADER_NAME_VALIDATOR = new ByteProcessor() {
@Override
public boolean process(byte value) throws Exception {
validateHeaderNameElement(value);
return true;
}
private static final ByteProcessor HEADER_NAME_VALIDATOR = value -> {
validateHeaderNameElement(value);
return true;
};
static final NameValidator<CharSequence> HttpNameValidator = new NameValidator<CharSequence>() {
@Override
public void validateName(CharSequence name) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("empty headers are not allowed [" + name + "]");
static final NameValidator<CharSequence> HttpNameValidator = name -> {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("empty headers are not allowed [" + name + "]");
}
if (name instanceof AsciiString) {
try {
((AsciiString) name).forEachByte(HEADER_NAME_VALIDATOR);
} catch (Exception e) {
PlatformDependent.throwException(e);
}
if (name instanceof AsciiString) {
try {
((AsciiString) name).forEachByte(HEADER_NAME_VALIDATOR);
} catch (Exception e) {
PlatformDependent.throwException(e);
}
} else {
// Go through each character in the name
for (int index = 0; index < name.length(); ++index) {
validateHeaderNameElement(name.charAt(index));
}
} else {
// Go through each character in the name
for (int index = 0; index < name.length(); ++index) {
validateHeaderNameElement(name.charAt(index));
}
}
};

View File

@ -115,15 +115,12 @@ public class DefaultLastHttpContent extends DefaultHttpContent implements LastHt
}
private static final class TrailingHttpHeaders extends DefaultHttpHeaders {
private static final NameValidator<CharSequence> TrailerNameValidator = new NameValidator<CharSequence>() {
@Override
public void validateName(CharSequence name) {
DefaultHttpHeaders.HttpNameValidator.validateName(name);
if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(name)
|| HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(name)
|| HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(name)) {
throw new IllegalArgumentException("prohibited trailing header: " + name);
}
private static final NameValidator<CharSequence> TrailerNameValidator = name -> {
DefaultHttpHeaders.HttpNameValidator.validateName(name);
if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(name)
|| HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(name)
|| HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(name)) {
throw new IllegalArgumentException("prohibited trailing header: " + name);
}
};

View File

@ -251,23 +251,17 @@ public class HttpObjectAggregator
if (oversized instanceof FullHttpMessage ||
!HttpUtil.is100ContinueExpected(oversized) && !HttpUtil.isKeepAlive(oversized)) {
ChannelFuture future = ctx.writeAndFlush(TOO_LARGE_CLOSE.retainedDuplicate());
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
}
ctx.close();
future.addListener((ChannelFutureListener) future1 -> {
if (!future1.isSuccess()) {
logger.debug("Failed to send a 413 Request Entity Too Large.", future1.cause());
}
ctx.close();
});
} else {
ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
ctx.close();
}
ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
ctx.close();
}
});
}

View File

@ -91,26 +91,23 @@ public final class ClientCookieEncoder extends CookieEncoder {
* Sort cookies into decreasing order of path length, breaking ties by sorting into increasing chronological
* order of creation time, as recommended by RFC 6265.
*/
private static final Comparator<Cookie> COOKIE_COMPARATOR = new Comparator<Cookie>() {
@Override
public int compare(Cookie c1, Cookie c2) {
String path1 = c1.path();
String path2 = c2.path();
// Cookies with unspecified path default to the path of the request. We don't
// know the request path here, but we assume that the length of an unspecified
// path is longer than any specified path (i.e. pathless cookies come first),
// because setting cookies with a path longer than the request path is of
// limited use.
int len1 = path1 == null ? Integer.MAX_VALUE : path1.length();
int len2 = path2 == null ? Integer.MAX_VALUE : path2.length();
int diff = len2 - len1;
if (diff != 0) {
return diff;
}
// Rely on Java's sort stability to retain creation order in cases where
// cookies have same path length.
return -1;
private static final Comparator<Cookie> COOKIE_COMPARATOR = (c1, c2) -> {
String path1 = c1.path();
String path2 = c2.path();
// Cookies with unspecified path default to the path of the request. We don't
// know the request path here, but we assume that the length of an unspecified
// path is longer than any specified path (i.e. pathless cookies come first),
// because setting cookies with a path longer than the request path is of
// limited use.
int len1 = path1 == null ? Integer.MAX_VALUE : path1.length();
int len2 = path2 == null ? Integer.MAX_VALUE : path2.length();
int diff = len2 - len1;
if (diff != 0) {
return diff;
}
// Rely on Java's sort stability to retain creation order in cases where
// cookies have same path length.
return -1;
};
/**

View File

@ -174,26 +174,23 @@ public abstract class WebSocketClientHandshaker {
}
}
channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
ChannelPipeline p = future.channel().pipeline();
ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
}
if (ctx == null) {
promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
"a HttpRequestEncoder or HttpClientCodec"));
return;
}
p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());
promise.setSuccess();
} else {
promise.setFailure(future.cause());
channel.writeAndFlush(request).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
ChannelPipeline p = future.channel().pipeline();
ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
}
if (ctx == null) {
promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
"a HttpRequestEncoder or HttpClientCodec"));
return;
}
p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
});
return promise;
@ -274,12 +271,7 @@ public abstract class WebSocketClientHandshaker {
// Delay the removal of the decoder so the user can setup the pipeline if needed to handle
// WebSocketFrame messages.
// See https://github.com/netty/netty/issues/4533
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
p.remove(codec);
}
});
channel.eventLoop().execute(() -> p.remove(codec));
} else {
if (p.get(HttpRequestEncoder.class) != null) {
// Remove the encoder part of the codec as the user may start writing frames after this method returns.
@ -291,12 +283,7 @@ public abstract class WebSocketClientHandshaker {
// Delay the removal of the decoder so the user can setup the pipeline if needed to handle
// WebSocketFrame messages.
// See https://github.com/netty/netty/issues/4533
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
p.remove(context.handler());
}
});
channel.eventLoop().execute(() -> p.remove(context.handler()));
}
}

View File

@ -31,15 +31,12 @@ class WebSocketClientProtocolHandshakeHandler extends ChannelInboundHandlerAdapt
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
handshaker.handshake(ctx.channel()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
ctx.fireUserEventTriggered(
WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED);
}
handshaker.handshake(ctx.channel()).addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
ctx.fireUserEventTriggered(
WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED);
}
});
}

View File

@ -191,16 +191,13 @@ public abstract class WebSocketServerHandshaker {
encoderName = p.context(HttpResponseEncoder.class).name();
p.addBefore(encoderName, "wsencoder", newWebSocketEncoder());
}
channel.writeAndFlush(response).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ChannelPipeline p = future.channel().pipeline();
p.remove(encoderName);
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
channel.writeAndFlush(response).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
ChannelPipeline p1 = future.channel().pipeline();
p1.remove(encoderName);
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
});
return promise;

View File

@ -81,19 +81,16 @@ class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapt
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
// Kept for compatibility
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
ctx.fireUserEventTriggered(
new WebSocketServerProtocolHandler.HandshakeComplete(
req.uri(), req.headers(), handshaker.selectedSubprotocol()));
}
handshakeFuture.addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
} else {
// Kept for compatibility
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
ctx.fireUserEventTriggered(
new WebSocketServerProtocolHandler.HandshakeComplete(
req.uri(), req.headers(), handshaker.selectedSubprotocol()));
}
});
WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);

View File

@ -115,20 +115,17 @@ public class WebSocketServerExtensionHandler extends ChannelDuplexHandler {
extensionData.name(), extensionData.parameters());
}
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
for (WebSocketServerExtension extension : validExtensions) {
WebSocketExtensionDecoder decoder = extension.newExtensionDecoder();
WebSocketExtensionEncoder encoder = extension.newExtensionEncoder();
ctx.pipeline().addAfter(ctx.name(), decoder.getClass().getName(), decoder);
ctx.pipeline().addAfter(ctx.name(), encoder.getClass().getName(), encoder);
}
promise.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
for (WebSocketServerExtension extension : validExtensions) {
WebSocketExtensionDecoder decoder = extension.newExtensionDecoder();
WebSocketExtensionEncoder encoder = extension.newExtensionEncoder();
ctx.pipeline().addAfter(ctx.name(), decoder.getClass().getName(), decoder);
ctx.pipeline().addAfter(ctx.name(), encoder.getClass().getName(), encoder);
}
ctx.pipeline().remove(ctx.name());
}
ctx.pipeline().remove(ctx.name());
});
if (headerValue != null) {

View File

@ -27,12 +27,7 @@ import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER;
import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER;
public class DefaultSpdyHeaders extends DefaultHeaders<CharSequence, CharSequence, SpdyHeaders> implements SpdyHeaders {
private static final NameValidator<CharSequence> SpdyNameValidator = new NameValidator<CharSequence>() {
@Override
public void validateName(CharSequence name) {
SpdyCodecUtil.validateHeaderName(name);
}
};
private static final NameValidator<CharSequence> SpdyNameValidator = SpdyCodecUtil::validateHeaderName;
public DefaultSpdyHeaders() {
this(true);

View File

@ -109,12 +109,9 @@ public class SpdyFrameCodec extends ByteToMessageDecoder
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
super.handlerAdded(ctx);
this.ctx = ctx;
ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
spdyHeaderBlockDecoder.end();
spdyHeaderBlockEncoder.end();
}
ctx.channel().closeFuture().addListener((ChannelFutureListener) future -> {
spdyHeaderBlockDecoder.end();
spdyHeaderBlockEncoder.end();
});
}

View File

@ -504,12 +504,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler {
// The transfer window size is pre-decremented when sending a data frame downstream.
// Close the session on write failures that leave the transfer window in a corrupt state.
final ChannelHandlerContext context = ctx;
ctx.write(partialDataFrame).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR);
}
ctx.write(partialDataFrame).addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR);
}
});
return;
@ -521,12 +518,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler {
// The transfer window size is pre-decremented when sending a data frame downstream.
// Close the session on write failures that leave the transfer window in a corrupt state.
final ChannelHandlerContext context = ctx;
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR);
}
promise.addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
issueSessionError(context, SpdySessionStatus.INTERNAL_ERROR);
}
});
}
@ -781,12 +775,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler {
// The transfer window size is pre-decremented when sending a data frame downstream.
// Close the session on write failures that leave the transfer window in a corrupt state.
ctx.writeAndFlush(partialDataFrame).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR);
}
ctx.writeAndFlush(partialDataFrame).addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR);
}
});
} else {
@ -802,12 +793,9 @@ public class SpdySessionHandler extends ChannelDuplexHandler {
// The transfer window size is pre-decremented when sending a data frame downstream.
// Close the session on write failures that leave the transfer window in a corrupt state.
ctx.writeAndFlush(spdyDataFrame, pendingWrite.promise).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR);
}
ctx.writeAndFlush(spdyDataFrame, pendingWrite.promise).addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
issueSessionError(ctx, SpdySessionStatus.INTERNAL_ERROR);
}
});
}

View File

@ -147,22 +147,16 @@ public class HttpClientCodecTest {
sChannel.writeAndFlush(Unpooled.wrappedBuffer(("HTTP/1.0 200 OK\r\n" +
"Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" +
"Content-Type: text/html\r\n\r\n").getBytes(CharsetUtil.ISO_8859_1)))
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
sChannel.writeAndFlush(Unpooled.wrappedBuffer(
"<html><body>hello half closed!</body></html>\r\n"
.getBytes(CharsetUtil.ISO_8859_1)))
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
sChannel.shutdownOutput();
}
.addListener((ChannelFutureListener) future -> {
assertTrue(future.isSuccess());
sChannel.writeAndFlush(Unpooled.wrappedBuffer(
"<html><body>hello half closed!</body></html>\r\n"
.getBytes(CharsetUtil.ISO_8859_1)))
.addListener((ChannelFutureListener) future1 -> {
assertTrue(future1.isSuccess());
sChannel.shutdownOutput();
});
});
}
});
}
});
serverChannelLatch.countDown();

View File

@ -64,12 +64,7 @@ public class HttpServerUpgradeHandlerTest {
@Test
public void upgradesPipelineInSameMethodInvocation() {
final HttpServerCodec httpServerCodec = new HttpServerCodec();
final UpgradeCodecFactory factory = new UpgradeCodecFactory() {
@Override
public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
return new TestUpgradeCodec();
}
};
final UpgradeCodecFactory factory = protocol -> new TestUpgradeCodec();
ChannelHandler testInStackFrame = new ChannelDuplexHandler() {
// marker boolean to signal that we're in the `channelRead` method
@ -102,18 +97,8 @@ public class HttpServerUpgradeHandlerTest {
// make sure the pipeline was reformed irrespective of the flush completing.
assertTrue(inReadCall);
writeUpgradeMessage = true;
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
ctx.write(msg, promise);
}
});
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
writeFlushed = true;
}
});
ctx.channel().eventLoop().execute(() -> ctx.write(msg, promise));
promise.addListener((ChannelFutureListener) future -> writeFlushed = true);
}
};

View File

@ -186,12 +186,7 @@ public class CorsHandlerTest {
@Test
public void preflightRequestWithValueGenerator() {
final CorsConfig config = forOrigin("http://localhost:8888")
.preflightResponseHeader("GenHeader", new Callable<String>() {
@Override
public String call() throws Exception {
return "generatedValue";
}
}).build();
.preflightResponseHeader("GenHeader", () -> "generatedValue").build();
final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1");
assertThat(response.headers().get(of("GenHeader")), equalTo("generatedValue"));
assertThat(response.headers().get(VARY), equalTo(ORIGIN.toString()));

View File

@ -277,14 +277,11 @@ public class DefaultHttp2Connection implements Http2Connection {
private void closeStreamsGreaterThanLastKnownStreamId(final int lastKnownStream,
final DefaultEndpoint<?> endpoint) throws Http2Exception {
forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) {
if (stream.id() > lastKnownStream && endpoint.isValidStreamId(stream.id())) {
stream.close();
}
return true;
forEachActiveStream(stream -> {
if (stream.id() > lastKnownStream && endpoint.isValidStreamId(stream.id())) {
stream.close();
}
return true;
});
}
@ -942,12 +939,7 @@ public class DefaultHttp2Connection implements Http2Connection {
if (allowModifications()) {
addToActiveStreams(stream);
} else {
pendingEvents.add(new Event() {
@Override
public void process() {
addToActiveStreams(stream);
}
});
pendingEvents.add(() -> addToActiveStreams(stream));
}
}
@ -955,12 +947,7 @@ public class DefaultHttp2Connection implements Http2Connection {
if (allowModifications() || itr != null) {
removeFromActiveStreams(stream, itr);
} else {
pendingEvents.add(new Event() {
@Override
public void process() {
removeFromActiveStreams(stream, itr);
}
});
pendingEvents.add(() -> removeFromActiveStreams(stream, itr));
}
}

View File

@ -463,13 +463,10 @@ public class DefaultHttp2ConnectionEncoder implements Http2ConnectionEncoder {
}
private void notifyLifecycleManagerOnError(ChannelFuture future, final ChannelHandlerContext ctx) {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if (cause != null) {
lifecycleManager.onError(ctx, true, cause);
}
future.addListener((ChannelFutureListener) future1 -> {
Throwable cause = future1.cause();
if (cause != null) {
lifecycleManager.onError(ctx, true, cause);
}
});
}

View File

@ -31,43 +31,35 @@ import static io.netty.util.AsciiString.isUpperCase;
@UnstableApi
public class DefaultHttp2Headers
extends DefaultHeaders<CharSequence, CharSequence, Http2Headers> implements Http2Headers {
private static final ByteProcessor HTTP2_NAME_VALIDATOR_PROCESSOR = new ByteProcessor() {
@Override
public boolean process(byte value) {
return !isUpperCase(value);
private static final ByteProcessor HTTP2_NAME_VALIDATOR_PROCESSOR = value -> !isUpperCase(value);
static final NameValidator<CharSequence> HTTP2_NAME_VALIDATOR = name -> {
if (name == null || name.length() == 0) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR,
"empty headers are not allowed [%s]", name));
}
};
static final NameValidator<CharSequence> HTTP2_NAME_VALIDATOR = new NameValidator<CharSequence>() {
@Override
public void validateName(CharSequence name) {
if (name == null || name.length() == 0) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR,
"empty headers are not allowed [%s]", name));
if (name instanceof AsciiString) {
final int index;
try {
index = ((AsciiString) name).forEachByte(HTTP2_NAME_VALIDATOR_PROCESSOR);
} catch (Http2Exception e) {
PlatformDependent.throwException(e);
return;
} catch (Throwable t) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, t,
"unexpected error. invalid header name [%s]", name));
return;
}
if (name instanceof AsciiString) {
final int index;
try {
index = ((AsciiString) name).forEachByte(HTTP2_NAME_VALIDATOR_PROCESSOR);
} catch (Http2Exception e) {
PlatformDependent.throwException(e);
return;
} catch (Throwable t) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR, t,
"unexpected error. invalid header name [%s]", name));
return;
}
if (index != -1) {
if (index != -1) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR,
"invalid header name [%s]", name));
}
} else {
for (int i = 0; i < name.length(); ++i) {
if (isUpperCase(name.charAt(i))) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR,
"invalid header name [%s]", name));
}
} else {
for (int i = 0; i < name.length(); ++i) {
if (isUpperCase(name.charAt(i))) {
PlatformDependent.throwException(connectionError(PROTOCOL_ERROR,
"invalid header name [%s]", name));
}
}
}
}
};

View File

@ -641,12 +641,9 @@ public class DefaultHttp2RemoteFlowController implements Http2RemoteFlowControll
final int delta = newWindowSize - initialWindowSize;
initialWindowSize = newWindowSize;
connection.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
state(stream).incrementStreamWindow(delta);
return true;
}
connection.forEachActiveStream(stream -> {
state(stream).incrementStreamWindow(delta);
return true;
});
if (delta > 0 && isChannelWritable()) {

View File

@ -606,12 +606,7 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http
if (future.isDone()) {
checkCloseConnection(future);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
checkCloseConnection(future);
}
});
future.addListener((ChannelFutureListener) this::checkCloseConnection);
}
}
@ -750,12 +745,7 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http
if (future.isDone()) {
closeConnectionOnError(ctx, future);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
closeConnectionOnError(ctx, future);
}
});
future.addListener((ChannelFutureListener) future1 -> closeConnectionOnError(ctx, future1));
}
return future;
}
@ -795,12 +785,7 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http
if (future.isDone()) {
processRstStreamWriteResult(ctx, stream, future);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
processRstStreamWriteResult(ctx, stream, future);
}
});
future.addListener((ChannelFutureListener) future1 -> processRstStreamWriteResult(ctx, stream, future1));
}
return future;
@ -831,12 +816,8 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http
if (future.isDone()) {
processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future);
}
});
future.addListener((ChannelFutureListener) future1 ->
processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future1));
}
return future;
@ -938,11 +919,8 @@ public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http
long timeout, TimeUnit unit) {
this.ctx = ctx;
this.promise = promise;
timeoutTask = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
timeoutTask = ctx.executor().schedule(() -> {
ctx.close(promise);
}, timeout, unit);
}

View File

@ -183,15 +183,12 @@ public class Http2FrameCodec extends Http2ConnectionHandler {
final void forEachActiveStream(final Http2FrameStreamVisitor streamVisitor) throws Http2Exception {
assert ctx.executor().inEventLoop();
connection().forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) {
try {
return streamVisitor.visit((Http2FrameStream) stream.getProperty(streamKey));
} catch (Throwable cause) {
onError(ctx, false, cause);
return false;
}
connection().forEachActiveStream(stream -> {
try {
return streamVisitor.visit((Http2FrameStream) stream.getProperty(streamKey));
} catch (Throwable cause) {
onError(ctx, false, cause);
return false;
}
});
}
@ -381,13 +378,10 @@ public class Http2FrameCodec extends Http2ConnectionHandler {
} else {
numBufferedStreams++;
writePromise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
numBufferedStreams--;
writePromise.addListener((ChannelFutureListener) future -> {
numBufferedStreams--;
notifyHeaderWritePromise(future, promise);
}
notifyHeaderWritePromise(future, promise);
});
}
}

View File

@ -90,20 +90,10 @@ public interface Http2HeadersEncoder {
/**
* Always return {@code false} for {@link SensitivityDetector#isSensitive(CharSequence, CharSequence)}.
*/
SensitivityDetector NEVER_SENSITIVE = new SensitivityDetector() {
@Override
public boolean isSensitive(CharSequence name, CharSequence value) {
return false;
}
};
SensitivityDetector NEVER_SENSITIVE = (name, value) -> false;
/**
* Always return {@code true} for {@link SensitivityDetector#isSensitive(CharSequence, CharSequence)}.
*/
SensitivityDetector ALWAYS_SENSITIVE = new SensitivityDetector() {
@Override
public boolean isSensitive(CharSequence name, CharSequence value) {
return true;
}
};
SensitivityDetector ALWAYS_SENSITIVE = (name, value) -> true;
}

View File

@ -108,12 +108,7 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultHttp2StreamChannel.class);
private static final ChannelFutureListener CHILD_CHANNEL_REGISTRATION_LISTENER = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
registerDone(future);
}
};
private static final ChannelFutureListener CHILD_CHANNEL_REGISTRATION_LISTENER = Http2MultiplexCodec::registerDone;
private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
private static final ClosedChannelException CLOSED_CHANNEL_EXCEPTION = ThrowableUtil.unknownStackTrace(
@ -131,15 +126,10 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
static final FlowControlledFrameSizeEstimator INSTANCE = new FlowControlledFrameSizeEstimator();
static final MessageSizeEstimator.Handle HANDLE_INSTANCE = new MessageSizeEstimator.Handle() {
@Override
public int size(Object msg) {
return msg instanceof Http2DataFrame ?
// Guard against overflow.
(int) min(Integer.MAX_VALUE, ((Http2DataFrame) msg).initialFlowControlledBytes() +
(long) MIN_HTTP2_FRAME_SIZE) : MIN_HTTP2_FRAME_SIZE;
}
};
static final MessageSizeEstimator.Handle HANDLE_INSTANCE = msg -> msg instanceof Http2DataFrame ?
// Guard against overflow.
(int) min(Integer.MAX_VALUE, ((Http2DataFrame) msg).initialFlowControlledBytes() +
(long) MIN_HTTP2_FRAME_SIZE) : MIN_HTTP2_FRAME_SIZE;
@Override
public Handle newHandle() {
@ -361,16 +351,13 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
private void onHttp2GoAwayFrame(ChannelHandlerContext ctx, final Http2GoAwayFrame goAwayFrame) {
try {
forEachActiveStream(new Http2FrameStreamVisitor() {
@Override
public boolean visit(Http2FrameStream stream) {
final int streamId = stream.id();
final DefaultHttp2StreamChannel childChannel = ((Http2MultiplexCodecStream) stream).channel;
if (streamId > goAwayFrame.lastStreamId() && connection().local().isValidStreamId(streamId)) {
childChannel.pipeline().fireUserEventTriggered(goAwayFrame.retainedDuplicate());
}
return true;
forEachActiveStream(stream -> {
final int streamId = stream.id();
final DefaultHttp2StreamChannel childChannel = ((Http2MultiplexCodecStream) stream).channel;
if (streamId > goAwayFrame.lastStreamId() && connection().local().isValidStreamId(streamId)) {
childChannel.pipeline().fireUserEventTriggered(goAwayFrame.retainedDuplicate());
}
return true;
});
} catch (Http2Exception e) {
ctx.fireExceptionCaught(e);
@ -890,12 +877,7 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
promise.setSuccess();
} else if (!(promise instanceof VoidChannelPromise)) { // Only needed if no VoidChannelPromise.
// This means close() was called before so we just register a listener and return
closePromise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
promise.setSuccess();
}
});
closePromise.addListener((ChannelFutureListener) future -> promise.setSuccess());
}
return;
}
@ -959,20 +941,17 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
//
// See:
// https://github.com/netty/netty/issues/4435
invokeLater(new Runnable() {
@Override
public void run() {
if (fireChannelInactive) {
pipeline.fireChannelInactive();
}
// The user can fire `deregister` events multiple times but we only want to fire the pipeline
// event if the channel was actually registered.
if (registered) {
registered = false;
pipeline.fireChannelUnregistered();
}
safeSetSuccess(promise);
invokeLater(() -> {
if (fireChannelInactive) {
pipeline.fireChannelInactive();
}
// The user can fire `deregister` events multiple times but we only want to fire the pipeline
// event if the channel was actually registered.
if (registered) {
registered = false;
pipeline.fireChannelUnregistered();
}
safeSetSuccess(promise);
});
}
@ -1127,12 +1106,8 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
if (future.isDone()) {
firstWriteComplete(future, promise);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
firstWriteComplete(future, promise);
}
});
future.addListener((ChannelFutureListener) future12 ->
firstWriteComplete(future12, promise));
}
return;
}
@ -1149,12 +1124,7 @@ public class Http2MultiplexCodec extends Http2FrameCodec {
if (future.isDone()) {
writeComplete(future, promise);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
writeComplete(future, promise);
}
});
future.addListener((ChannelFutureListener) future1 -> writeComplete(future1, promise));
}
} catch (Throwable t) {
promise.tryFailure(t);

View File

@ -118,12 +118,7 @@ public final class Http2StreamChannelBootstrap {
if (executor.inEventLoop()) {
open0(ctx, promise);
} else {
executor.execute(new Runnable() {
@Override
public void run() {
open0(ctx, promise);
}
});
executor.execute(() -> open0(ctx, promise));
}
}
return promise;
@ -141,22 +136,19 @@ public final class Http2StreamChannelBootstrap {
}
ChannelFuture future = streamChannel.register();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
promise.setSuccess(streamChannel);
} else if (future.isCancelled()) {
promise.cancel(false);
future.addListener((ChannelFutureListener) future1 -> {
if (future1.isSuccess()) {
promise.setSuccess(streamChannel);
} else if (future1.isCancelled()) {
promise.cancel(false);
} else {
if (streamChannel.isRegistered()) {
streamChannel.close();
} else {
if (streamChannel.isRegistered()) {
streamChannel.close();
} else {
streamChannel.unsafe().closeForcibly();
}
promise.setFailure(future.cause());
streamChannel.unsafe().closeForcibly();
}
promise.setFailure(future1.cause());
}
});
}

View File

@ -35,21 +35,18 @@ abstract class AbstractWeightedFairQueueByteDistributorDependencyTest {
}
Answer<Void> writeAnswer(final boolean closeIfNoFrame) {
return new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
Http2Stream stream = in.getArgument(0);
int numBytes = in.getArgument(1);
TestStreamByteDistributorStreamState state = stateMap.get(stream.id());
state.pendingBytes -= numBytes;
state.hasFrame = state.pendingBytes > 0;
state.isWriteAllowed = state.hasFrame;
if (closeIfNoFrame && !state.hasFrame) {
stream.close();
}
distributor.updateStreamableBytes(state);
return null;
return in -> {
Http2Stream stream = in.getArgument(0);
int numBytes = in.getArgument(1);
TestStreamByteDistributorStreamState state = stateMap.get(stream.id());
state.pendingBytes -= numBytes;
state.hasFrame = state.pendingBytes > 0;
state.isWriteAllowed = state.hasFrame;
if (closeIfNoFrame && !state.hasFrame) {
stream.close();
}
distributor.updateStreamableBytes(state);
return null;
};
}

View File

@ -63,12 +63,7 @@ public class CleartextHttp2ServerUpgradeHandlerTest {
http2ConnectionHandler = new Http2ConnectionHandlerBuilder()
.frameListener(frameListener).build();
UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
@Override
public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
return new Http2ServerUpgradeCodec(http2ConnectionHandler);
}
};
UpgradeCodecFactory upgradeCodecFactory = protocol -> new Http2ServerUpgradeCodec(http2ConnectionHandler);
userEvents = new ArrayList<>();
@ -205,12 +200,7 @@ public class CleartextHttp2ServerUpgradeHandlerTest {
protected void initChannel(Channel ch) throws Exception {
}
}).build();
UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
@Override
public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
return new Http2ServerUpgradeCodec(http2Codec);
}
};
UpgradeCodecFactory upgradeCodecFactory = protocol -> new Http2ServerUpgradeCodec(http2Codec);
http2ConnectionHandler = http2Codec;
userEvents = new ArrayList<>();

View File

@ -92,24 +92,18 @@ public class DataCompressionHttp2Test {
@Before
public void setup() throws InterruptedException, Http2Exception {
MockitoAnnotations.initMocks(this);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (invocation.getArgument(4)) {
serverConnection.stream((Integer) invocation.getArgument(1)).close();
}
return null;
doAnswer(invocation -> {
if (invocation.getArgument(4)) {
serverConnection.stream((Integer) invocation.getArgument(1)).close();
}
return null;
}).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class),
anyInt(), anyBoolean());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (invocation.getArgument(7)) {
serverConnection.stream((Integer) invocation.getArgument(1)).close();
}
return null;
doAnswer(invocation -> {
if (invocation.getArgument(7)) {
serverConnection.stream((Integer) invocation.getArgument(1)).close();
}
return null;
}).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class),
anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean());
}
@ -148,12 +142,9 @@ public class DataCompressionHttp2Test {
final Http2Headers headers = new DefaultHttp2Headers().method(GET).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
}
runInChannel(clientChannel, () -> {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
});
awaitServer();
verify(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(headers), eq(0),
@ -169,13 +160,10 @@ public class DataCompressionHttp2Test {
final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
}
runInChannel(clientChannel, () -> {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
});
awaitServer();
assertEquals(text, serverOut.toString(CharsetUtil.UTF_8.name()));
@ -193,13 +181,10 @@ public class DataCompressionHttp2Test {
final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
}
runInChannel(clientChannel, () -> {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
});
awaitServer();
assertEquals(text, serverOut.toString(CharsetUtil.UTF_8.name()));
@ -219,14 +204,11 @@ public class DataCompressionHttp2Test {
final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data1.retain(), 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data2.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
}
runInChannel(clientChannel, () -> {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data1.retain(), 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data2.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
});
awaitServer();
assertEquals(text1 + text2, serverOut.toString(CharsetUtil.UTF_8.name()));
@ -247,13 +229,10 @@ public class DataCompressionHttp2Test {
final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.DEFLATE);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
}
runInChannel(clientChannel, () -> {
clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
clientHandler.flush(ctxClient());
});
awaitServer();
assertEquals(data.readerIndex(0).toString(CharsetUtil.UTF_8),
@ -281,20 +260,17 @@ public class DataCompressionHttp2Test {
}
});
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock in) throws Throwable {
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
doAnswer(in -> {
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
buf.readBytes(serverOut, buf.readableBytes());
buf.readBytes(serverOut, buf.readableBytes());
if (in.getArgument(4)) {
serverConnection.stream((Integer) in.getArgument(1)).close();
}
return processedBytes;
if (in.getArgument(4)) {
serverConnection.stream((Integer) in.getArgument(1)).close();
}
return processedBytes;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), anyInt(),
any(ByteBuf.class), anyInt(), anyBoolean());

View File

@ -130,52 +130,38 @@ public class DefaultHttp2ConnectionDecoderTest {
when(stream.state()).thenReturn(OPEN);
when(stream.open(anyBoolean())).thenReturn(stream);
when(pushStream.id()).thenReturn(PUSH_STREAM_ID);
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock in) throws Throwable {
return (headersReceivedState.get() & STATE_RECV_HEADERS) != 0;
}
}).when(stream).isHeadersReceived();
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock in) throws Throwable {
return (headersReceivedState.get() & STATE_RECV_TRAILERS) != 0;
}
}).when(stream).isTrailersReceived();
doAnswer(new Answer<Http2Stream>() {
@Override
public Http2Stream answer(InvocationOnMock in) throws Throwable {
boolean isInformational = in.getArgument(0);
if (isInformational) {
return stream;
}
for (;;) {
int current = headersReceivedState.get();
int next = current;
if ((current & STATE_RECV_HEADERS) != 0) {
if ((current & STATE_RECV_TRAILERS) != 0) {
throw new IllegalStateException("already sent headers!");
}
next |= STATE_RECV_TRAILERS;
} else {
next |= STATE_RECV_HEADERS;
}
if (headersReceivedState.compareAndSet(current, next)) {
break;
}
}
doAnswer((Answer<Boolean>) in ->
(headersReceivedState.get() & STATE_RECV_HEADERS) != 0).when(stream).isHeadersReceived();
doAnswer((Answer<Boolean>) in ->
(headersReceivedState.get() & STATE_RECV_TRAILERS) != 0).when(stream).isTrailersReceived();
doAnswer((Answer<Http2Stream>) in -> {
boolean isInformational = in.getArgument(0);
if (isInformational) {
return stream;
}
}).when(stream).headersReceived(anyBoolean());
doAnswer(new Answer<Http2Stream>() {
@Override
public Http2Stream answer(InvocationOnMock in) throws Throwable {
Http2StreamVisitor visitor = in.getArgument(0);
if (!visitor.visit(stream)) {
return stream;
for (;;) {
int current = headersReceivedState.get();
int next = current;
if ((current & STATE_RECV_HEADERS) != 0) {
if ((current & STATE_RECV_TRAILERS) != 0) {
throw new IllegalStateException("already sent headers!");
}
next |= STATE_RECV_TRAILERS;
} else {
next |= STATE_RECV_HEADERS;
}
if (headersReceivedState.compareAndSet(current, next)) {
break;
}
return null;
}
return stream;
}).when(stream).headersReceived(anyBoolean());
doAnswer((Answer<Http2Stream>) in -> {
Http2StreamVisitor visitor = in.getArgument(0);
if (!visitor.visit(stream)) {
return stream;
}
return null;
}).when(connection).forEachActiveStream(any(Http2StreamVisitor.class));
when(connection.stream(STREAM_ID)).thenReturn(stream);
when(connection.streamMayHaveExisted(STREAM_ID)).thenReturn(true);
@ -391,30 +377,19 @@ public class DefaultHttp2ConnectionDecoderTest {
final ByteBuf data = dummyData();
final int padding = 10;
final AtomicInteger unprocessed = new AtomicInteger(data.readableBytes() + padding);
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock in) throws Throwable {
return unprocessed.get();
}
}).when(localFlow).unconsumedBytes(eq(stream));
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
int delta = (Integer) in.getArguments()[1];
int newValue = unprocessed.addAndGet(-delta);
if (newValue < 0) {
throw new RuntimeException("Returned too many bytes");
}
return null;
doAnswer((Answer<Integer>) in -> unprocessed.get()).when(localFlow).unconsumedBytes(eq(stream));
doAnswer((Answer<Void>) in -> {
int delta = (Integer) in.getArguments()[1];
int newValue = unprocessed.addAndGet(-delta);
if (newValue < 0) {
throw new RuntimeException("Returned too many bytes");
}
return null;
}).when(localFlow).consumeBytes(eq(stream), anyInt());
// When the listener callback is called, process a few bytes and then throw.
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock in) throws Throwable {
localFlow.consumeBytes(stream, 4);
throw new RuntimeException("Fake Exception");
}
doAnswer((Answer<Integer>) in -> {
localFlow.consumeBytes(stream, 4);
throw new RuntimeException("Fake Exception");
}).when(listener).onDataRead(eq(ctx), eq(STREAM_ID), any(ByteBuf.class), eq(10), eq(true));
try {
decode().onDataRead(ctx, STREAM_ID, data, padding, true);
@ -759,12 +734,8 @@ public class DefaultHttp2ConnectionDecoderTest {
}
private void mockFlowControl(final int processedBytes) throws Http2Exception {
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return processedBytes;
}
}).when(listener).onDataRead(any(ChannelHandlerContext.class), anyInt(),
doAnswer((Answer<Integer>) invocation ->
processedBytes).when(listener).onDataRead(any(ChannelHandlerContext.class), anyInt(),
any(ByteBuf.class), anyInt(), anyBoolean());
}

View File

@ -127,82 +127,55 @@ public class DefaultHttp2ConnectionEncoderTest {
when(channel.unsafe()).thenReturn(unsafe);
ChannelConfig config = new DefaultChannelConfig(channel);
when(channel.config()).thenReturn(config);
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock in) {
return newPromise().setFailure((Throwable) in.getArgument(0));
}
}).when(channel).newFailedFuture(any(Throwable.class));
doAnswer(in -> newPromise()
.setFailure((Throwable) in.getArgument(0))).when(channel).newFailedFuture(any(Throwable.class));
when(writer.configuration()).thenReturn(writerConfig);
when(writerConfig.frameSizePolicy()).thenReturn(frameSizePolicy);
when(frameSizePolicy.maxFrameSize()).thenReturn(64);
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock in) throws Throwable {
return ((ChannelPromise) in.getArguments()[2]).setSuccess();
}
}).when(writer).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class));
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock in) throws Throwable {
((ByteBuf) in.getArguments()[3]).release();
return ((ChannelPromise) in.getArguments()[4]).setSuccess();
}
doAnswer((Answer<ChannelFuture>) in -> ((ChannelPromise) in.getArguments()[2])
.setSuccess()).when(writer).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class));
doAnswer((Answer<ChannelFuture>) in -> {
((ByteBuf) in.getArguments()[3]).release();
return ((ChannelPromise) in.getArguments()[4]).setSuccess();
}).when(writer).writeGoAway(eq(ctx), anyInt(), anyInt(), any(ByteBuf.class), any(ChannelPromise.class));
writtenData = new ArrayList<>();
writtenPadding = new ArrayList<>();
when(writer.writeData(eq(ctx), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean(),
any(ChannelPromise.class))).then(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock in) throws Throwable {
// Make sure we only receive stream closure on the last frame and that void promises
// are used for all writes except the last one.
ChannelPromise promise = (ChannelPromise) in.getArguments()[5];
if (streamClosed) {
fail("Stream already closed");
} else {
streamClosed = (Boolean) in.getArguments()[4];
}
writtenPadding.add((Integer) in.getArguments()[3]);
ByteBuf data = (ByteBuf) in.getArguments()[2];
writtenData.add(data.toString(UTF_8));
// Release the buffer just as DefaultHttp2FrameWriter does
data.release();
// Let the promise succeed to trigger listeners.
return promise.setSuccess();
any(ChannelPromise.class))).then((Answer<ChannelFuture>) in -> {
// Make sure we only receive stream closure on the last frame and that void promises
// are used for all writes except the last one.
ChannelPromise promise = (ChannelPromise) in.getArguments()[5];
if (streamClosed) {
fail("Stream already closed");
} else {
streamClosed = (Boolean) in.getArguments()[4];
}
writtenPadding.add((Integer) in.getArguments()[3]);
ByteBuf data = (ByteBuf) in.getArguments()[2];
writtenData.add(data.toString(UTF_8));
// Release the buffer just as DefaultHttp2FrameWriter does
data.release();
// Let the promise succeed to trigger listeners.
return promise.setSuccess();
});
when(writer.writeHeaders(eq(ctx), anyInt(), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(),
anyInt(), anyBoolean(), any(ChannelPromise.class)))
.then(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable {
ChannelPromise promise = (ChannelPromise) invocationOnMock.getArguments()[8];
if (streamClosed) {
fail("Stream already closed");
} else {
streamClosed = (Boolean) invocationOnMock.getArguments()[5];
}
return promise.setSuccess();
.then((Answer<ChannelFuture>) invocationOnMock -> {
ChannelPromise promise = (ChannelPromise) invocationOnMock.getArguments()[8];
if (streamClosed) {
fail("Stream already closed");
} else {
streamClosed = (Boolean) invocationOnMock.getArguments()[5];
}
return promise.setSuccess();
});
payloadCaptor = ArgumentCaptor.forClass(Http2RemoteFlowController.FlowControlled.class);
doNothing().when(remoteFlow).addFlowControlled(any(Http2Stream.class), payloadCaptor.capture());
when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(ctx.channel()).thenReturn(channel);
doAnswer(new Answer<ChannelPromise>() {
@Override
public ChannelPromise answer(InvocationOnMock in) throws Throwable {
return newPromise();
}
}).when(ctx).newPromise();
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock in) throws Throwable {
return newSucceededFuture();
}
}).when(ctx).newSucceededFuture();
doAnswer((Answer<ChannelPromise>) in -> newPromise()).when(ctx).newPromise();
doAnswer((Answer<ChannelFuture>) in -> newSucceededFuture()).when(ctx).newSucceededFuture();
when(ctx.flush()).thenThrow(new AssertionFailedError("forbidden"));
when(channel.alloc()).thenReturn(PooledByteBufAllocator.DEFAULT);
@ -337,13 +310,10 @@ public class DefaultHttp2ConnectionEncoderTest {
final Throwable cause = new RuntimeException("fake exception");
when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(),
anyInt(), anyBoolean(), any(ChannelPromise.class)))
.then(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable {
ChannelPromise promise = invocationOnMock.getArgument(8);
assertFalse(promise.isVoid());
return promise.setFailure(cause);
}
.then((Answer<ChannelFuture>) invocationOnMock -> {
ChannelPromise promise = invocationOnMock.getArgument(8);
assertFalse(promise.isVoid());
return promise.setFailure(cause);
});
createStream(STREAM_ID, false);
// END_STREAM flag, so that a listener is added to the future.
@ -754,12 +724,9 @@ public class DefaultHttp2ConnectionEncoderTest {
// Fake an encoding error, like HPACK's HeaderListSizeException
when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), eq(EmptyHttp2Headers.INSTANCE), eq(0),
eq(DEFAULT_PRIORITY_WEIGHT), eq(false), eq(0), eq(true), eq(promise)))
.thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) {
promise.setFailure(ex);
return promise;
}
.thenAnswer((Answer<ChannelFuture>) invocation -> {
promise.setFailure(ex);
return promise;
});
writeAllFlowControlledFrames();
@ -781,12 +748,9 @@ public class DefaultHttp2ConnectionEncoderTest {
// Fake an encoding error, like HPACK's HeaderListSizeException
when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), eq(EmptyHttp2Headers.INSTANCE), eq(0),
eq(DEFAULT_PRIORITY_WEIGHT), eq(false), eq(0), eq(true), eq(promise)))
.thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) {
promise.setFailure(ex);
return promise;
}
.thenAnswer((Answer<ChannelFuture>) invocation -> {
promise.setFailure(ex);
return promise;
});
writeAllFlowControlledFrames();
@ -873,14 +837,11 @@ public class DefaultHttp2ConnectionEncoderTest {
}
private void writeAllFlowControlledFrames() {
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
FlowControlled flowControlled = (FlowControlled) invocationOnMock.getArguments()[1];
flowControlled.write(ctx, Integer.MAX_VALUE);
flowControlled.writeComplete();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
FlowControlled flowControlled = (FlowControlled) invocationOnMock.getArguments()[1];
flowControlled.write(ctx, Integer.MAX_VALUE);
flowControlled.writeComplete();
return null;
}).when(remoteFlow).addFlowControlled(any(Http2Stream.class), payloadCaptor.capture());
}

View File

@ -88,19 +88,13 @@ public class DefaultHttp2ConnectionTest {
server = new DefaultHttp2Connection(true);
client = new DefaultHttp2Connection(false);
client.addListener(clientListener);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
assertNotNull(client.stream(((Http2Stream) invocation.getArgument(0)).id()));
return null;
}
doAnswer((Answer<Void>) invocation -> {
assertNotNull(client.stream(((Http2Stream) invocation.getArgument(0)).id()));
return null;
}).when(clientListener).onStreamClosed(any(Http2Stream.class));
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
assertNull(client.stream(((Http2Stream) invocation.getArgument(0)).id()));
return null;
}
doAnswer((Answer<Void>) invocation -> {
assertNull(client.stream(((Http2Stream) invocation.getArgument(0)).id()));
return null;
}).when(clientListener).onStreamRemoved(any(Http2Stream.class));
}
@ -141,13 +135,10 @@ public class DefaultHttp2ConnectionTest {
public void removeIndividualStreamsWhileCloseDoesNotNPE() throws InterruptedException, Http2Exception {
final Http2Stream streamA = client.local().createStream(3, false);
final Http2Stream streamB = client.remote().createStream(2, false);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
streamA.close();
streamB.close();
return null;
}
doAnswer((Answer<Void>) invocation -> {
streamA.close();
streamB.close();
return null;
}).when(clientListener2).onStreamClosed(any(Http2Stream.class));
try {
client.addListener(clientListener2);
@ -167,18 +158,12 @@ public class DefaultHttp2ConnectionTest {
}
final Promise<Void> promise = group.next().newPromise();
final CountDownLatch latch = new CountDownLatch(client.numActiveStreams());
client.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) {
client.close(promise).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(promise.isDone());
latch.countDown();
}
});
return true;
}
client.forEachActiveStream(stream -> {
client.close(promise).addListener((FutureListener<Void>) future -> {
assertTrue(promise.isDone());
latch.countDown();
});
return true;
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@ -195,23 +180,17 @@ public class DefaultHttp2ConnectionTest {
final Promise<Void> promise = group.next().newPromise();
final CountDownLatch latch = new CountDownLatch(1);
try {
client.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
// This close call is basically a noop, because the following statement will throw an exception.
client.close(promise);
// Do an invalid operation while iterating.
remote.createStream(3, false);
return true;
}
client.forEachActiveStream(stream -> {
// This close call is basically a noop, because the following statement will throw an exception.
client.close(promise);
// Do an invalid operation while iterating.
remote.createStream(3, false);
return true;
});
} catch (Http2Exception ignored) {
client.close(promise).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(promise.isDone());
latch.countDown();
}
client.close(promise).addListener((FutureListener<Void>) future -> {
assertTrue(promise.isDone());
latch.countDown();
});
}
assertTrue(latch.await(5, TimeUnit.SECONDS));
@ -590,12 +569,9 @@ public class DefaultHttp2ConnectionTest {
private void testRemoveAllStreams() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Promise<Void> promise = group.next().newPromise();
client.close(promise).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(promise.isDone());
latch.countDown();
}
client.close(promise).addListener((FutureListener<Void>) future -> {
assertTrue(promise.isDone());
latch.countDown();
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}

View File

@ -76,16 +76,13 @@ public class DefaultHttp2FrameWriterTest {
http2HeadersEncoder = new DefaultHttp2HeadersEncoder();
Answer<Object> answer = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock var1) throws Throwable {
Object msg = var1.getArgument(0);
if (msg instanceof ByteBuf) {
outbound.writeBytes((ByteBuf) msg);
}
ReferenceCountUtil.release(msg);
return future;
Answer<Object> answer = var1 -> {
Object msg = var1.getArgument(0);
if (msg instanceof ByteBuf) {
outbound.writeBytes((ByteBuf) msg);
}
ReferenceCountUtil.release(msg);
return future;
};
when(ctx.write(any())).then(answer);
when(ctx.write(any(), any(ChannelPromise.class))).then(answer);

View File

@ -691,12 +691,9 @@ public abstract class DefaultHttp2RemoteFlowControllerTest {
public void flowControlledWriteThrowsAnException() throws Exception {
final Http2RemoteFlowController.FlowControlled flowControlled = mockedFlowControlledThatThrowsOnWrite();
final Http2Stream stream = stream(STREAM_A);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) {
stream.closeLocalSide();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
stream.closeLocalSide();
return null;
}).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class));
int windowBefore = window(STREAM_A);
@ -724,11 +721,8 @@ public abstract class DefaultHttp2RemoteFlowControllerTest {
final Http2RemoteFlowController.FlowControlled flowControlled = mockedFlowControlledThatThrowsOnWrite();
final Http2Stream stream = stream(STREAM_A);
final RuntimeException fakeException = new RuntimeException("error failed");
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) {
throw fakeException;
}
doAnswer((Answer<Void>) invocationOnMock -> {
throw fakeException;
}).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class));
int windowBefore = window(STREAM_A);
@ -757,26 +751,15 @@ public abstract class DefaultHttp2RemoteFlowControllerTest {
mock(Http2RemoteFlowController.FlowControlled.class);
Http2Stream streamA = stream(STREAM_A);
final AtomicInteger size = new AtomicInteger(150);
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
return size.get();
}
}).when(flowControlled).size();
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
size.addAndGet(-50);
return null;
}
doAnswer((Answer<Integer>) invocationOnMock -> size.get()).when(flowControlled).size();
doAnswer((Answer<Void>) invocationOnMock -> {
size.addAndGet(-50);
return null;
}).when(flowControlled).write(any(ChannelHandlerContext.class), anyInt());
final Http2Stream stream = stream(STREAM_A);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) {
throw new RuntimeException("writeComplete failed");
}
doAnswer((Answer<Void>) invocationOnMock -> {
throw new RuntimeException("writeComplete failed");
}).when(flowControlled).writeComplete();
int windowBefore = window(STREAM_A);
@ -807,12 +790,9 @@ public abstract class DefaultHttp2RemoteFlowControllerTest {
when(flowControlled.size()).thenReturn(100);
doThrow(new RuntimeException("write failed"))
.when(flowControlled).write(any(ChannelHandlerContext.class), anyInt());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) {
stream.close();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
stream.close();
return null;
}).when(flowControlled).error(any(ChannelHandlerContext.class), any(Throwable.class));
controller.addFlowControlled(stream, flowControlled);
@ -960,13 +940,10 @@ public abstract class DefaultHttp2RemoteFlowControllerTest {
final Http2RemoteFlowController.FlowControlled flowControlled =
mock(Http2RemoteFlowController.FlowControlled.class);
when(flowControlled.size()).thenReturn(100);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
// Write most of the bytes and then fail
when(flowControlled.size()).thenReturn(10);
throw new RuntimeException("Write failed");
}
doAnswer((Answer<Void>) in -> {
// Write most of the bytes and then fail
when(flowControlled.size()).thenReturn(10);
throw new RuntimeException("Write failed");
}).when(flowControlled).write(any(ChannelHandlerContext.class), anyInt());
return flowControlled;
}

View File

@ -51,28 +51,20 @@ public final class HashCollisionTest {
// More "english words" can be found here:
// https://gist.github.com/Scottmitch/de2f03912778016ecee3c140478f07e0#file-englishwords-txt
Map<Integer, List<CharSequence>> dups = calculateDuplicates(strings, new Function<CharSequence, Integer>() {
@Override
public Integer apply(CharSequence string) {
int h = 0;
for (int i = 0; i < string.length(); ++i) {
// masking with 0x1F reduces the number of overall bits that impact the hash code but makes the hash
// code the same regardless of character case (upper case or lower case hash is the same).
h = h * 31 + (string.charAt(i) & 0x1F);
}
return h;
Map<Integer, List<CharSequence>> dups = calculateDuplicates(strings, string -> {
int h = 0;
for (int i = 0; i < string.length(); ++i) {
// masking with 0x1F reduces the number of overall bits that impact the hash code but makes the hash
// code the same regardless of character case (upper case or lower case hash is the same).
h = h * 31 + (string.charAt(i) & 0x1F);
}
return h;
});
PrintStream writer = System.out;
writer.println("==Old Duplicates==");
printResults(writer, dups);
dups = calculateDuplicates(strings, new Function<CharSequence, Integer>() {
@Override
public Integer apply(CharSequence string) {
return PlatformDependent.hashCodeAscii(string);
}
});
dups = calculateDuplicates(strings, PlatformDependent::hashCodeAscii);
writer.println();
writer.println("==New Duplicates==");
printResults(writer, dups);

View File

@ -180,12 +180,7 @@ final class HpackTestCase {
private static byte[] encode(HpackEncoder hpackEncoder, List<HpackHeaderField> headers, int maxHeaderTableSize,
final boolean sensitive) throws Http2Exception {
Http2Headers http2Headers = toHttp2Headers(headers);
Http2HeadersEncoder.SensitivityDetector sensitivityDetector = new Http2HeadersEncoder.SensitivityDetector() {
@Override
public boolean isSensitive(CharSequence name, CharSequence value) {
return sensitive;
}
};
Http2HeadersEncoder.SensitivityDetector sensitivityDetector = (name, value) -> sensitive;
ByteBuf buffer = Unpooled.buffer();
try {
if (maxHeaderTableSize != -1) {

View File

@ -154,25 +154,19 @@ public class Http2ConnectionHandlerTest {
when(encoder.frameWriter()).thenReturn(frameWriter);
when(encoder.flowController()).thenReturn(remoteFlow);
when(decoder.flowController()).thenReturn(localFlow);
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) throws Throwable {
ByteBuf buf = invocation.getArgument(3);
goAwayDebugCap = buf.toString(UTF_8);
buf.release();
return future;
}
doAnswer((Answer<ChannelFuture>) invocation -> {
ByteBuf buf = invocation.getArgument(3);
goAwayDebugCap = buf.toString(UTF_8);
buf.release();
return future;
}).when(frameWriter).writeGoAway(
any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class));
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) throws Throwable {
Object o = invocation.getArguments()[0];
if (o instanceof ChannelFutureListener) {
((ChannelFutureListener) o).operationComplete(future);
}
return future;
doAnswer((Answer<ChannelFuture>) invocation -> {
Object o = invocation.getArguments()[0];
if (o instanceof ChannelFutureListener) {
((ChannelFutureListener) o).operationComplete(future);
}
return future;
}).when(future).addListener(any(GenericFutureListener.class));
when(future.cause()).thenReturn(fakeException);
when(future.channel()).thenReturn(channel);
@ -182,15 +176,12 @@ public class Http2ConnectionHandlerTest {
when(remote.flowController()).thenReturn(remoteFlowController);
when(connection.local()).thenReturn(local);
when(local.flowController()).thenReturn(localFlowController);
doAnswer(new Answer<Http2Stream>() {
@Override
public Http2Stream answer(InvocationOnMock in) throws Throwable {
Http2StreamVisitor visitor = in.getArgument(0);
if (!visitor.visit(stream)) {
return stream;
}
return null;
doAnswer((Answer<Http2Stream>) in -> {
Http2StreamVisitor visitor = in.getArgument(0);
if (!visitor.visit(stream)) {
return stream;
}
return null;
}).when(connection).forEachActiveStream(any(Http2StreamVisitor.class));
when(connection.stream(NON_EXISTANT_STREAM_ID)).thenReturn(null);
when(connection.numActiveStreams()).thenReturn(1);
@ -205,13 +196,10 @@ public class Http2ConnectionHandlerTest {
when(ctx.voidPromise()).thenReturn(voidPromise);
when(ctx.write(any())).thenReturn(future);
when(ctx.executor()).thenReturn(executor);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock in) throws Throwable {
Object msg = in.getArgument(0);
ReferenceCountUtil.release(msg);
return null;
}
doAnswer(in -> {
Object msg = in.getArgument(0);
ReferenceCountUtil.release(msg);
return null;
}).when(ctx).fireChannelRead(any());
}
@ -261,15 +249,12 @@ public class Http2ConnectionHandlerTest {
Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE;
final AtomicBoolean verified = new AtomicBoolean(false);
final Answer verifier = new Answer() {
@Override
public Object answer(final InvocationOnMock in) throws Throwable {
assertTrue(in.getArgument(0).equals(evt)); // sanity check...
verify(ctx).write(eq(connectionPrefaceBuf()));
verify(encoder).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class));
verified.set(true);
return null;
}
final Answer verifier = in -> {
assertTrue(in.getArgument(0).equals(evt)); // sanity check...
verify(ctx).write(eq(connectionPrefaceBuf()));
verify(encoder).writeSettings(eq(ctx), any(Http2Settings.class), any(ChannelPromise.class));
verified.set(true);
return null;
};
doAnswer(verifier).when(ctx).fireUserEventTriggered(evt);
@ -562,23 +547,16 @@ public class Http2ConnectionHandlerTest {
handler = newHandler();
when(future.isDone()).thenReturn(true);
when(future.isSuccess()).thenReturn(true);
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
GenericFutureListener<ChannelFuture> listener = (GenericFutureListener<ChannelFuture>) args[0];
// Simulate that all streams have become inactive by the time the future completes.
doAnswer(new Answer<Http2Stream>() {
@Override
public Http2Stream answer(InvocationOnMock in) throws Throwable {
return null;
}
}).when(connection).forEachActiveStream(any(Http2StreamVisitor.class));
when(connection.numActiveStreams()).thenReturn(0);
// Simulate the future being completed.
listener.operationComplete(future);
return future;
}
doAnswer((Answer<ChannelFuture>) invocation -> {
Object[] args = invocation.getArguments();
GenericFutureListener<ChannelFuture> listener = (GenericFutureListener<ChannelFuture>) args[0];
// Simulate that all streams have become inactive by the time the future completes.
doAnswer((Answer<Http2Stream>) in -> null).when(connection).forEachActiveStream(
any(Http2StreamVisitor.class));
when(connection.numActiveStreams()).thenReturn(0);
// Simulate the future being completed.
listener.operationComplete(future);
return future;
}).when(future).addListener(any(GenericFutureListener.class));
handler.close(ctx, promise);
if (future.isDone()) {
@ -597,12 +575,9 @@ public class Http2ConnectionHandlerTest {
long errorCode = Http2Error.INTERNAL_ERROR.code();
when(future.isDone()).thenReturn(true);
when(future.isSuccess()).thenReturn(true);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
((GenericFutureListener) invocation.getArgument(0)).operationComplete(future);
return null;
}
doAnswer((Answer<Void>) invocation -> {
((GenericFutureListener) invocation.getArgument(0)).operationComplete(future);
return null;
}).when(future).addListener(any(GenericFutureListener.class));
handler = newHandler();
handler.goAway(ctx, STREAM_ID, errorCode, data, promise);
@ -645,11 +620,8 @@ public class Http2ConnectionHandlerTest {
when(connection.goAwaySent()).thenReturn(true);
when(remote.lastStreamKnownByPeer()).thenReturn(STREAM_ID);
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocationOnMock) {
throw new IllegalStateException();
}
doAnswer((Answer<Boolean>) invocationOnMock -> {
throw new IllegalStateException();
}).when(connection).goAwaySent(anyInt(), anyLong(), any(ByteBuf.class));
handler.goAway(ctx, STREAM_ID + 2, errorCode, data, promise);
assertTrue(promise.isDone());
@ -665,18 +637,15 @@ public class Http2ConnectionHandlerTest {
long errorCode = Http2Error.INTERNAL_ERROR.code();
handler = newHandler();
final Throwable cause = new RuntimeException("fake exception");
doAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) throws Throwable {
ChannelPromise promise = invocation.getArgument(4);
assertFalse(promise.isVoid());
// This is what DefaultHttp2FrameWriter does... I hate mocking :-(.
SimpleChannelPromiseAggregator aggregatedPromise =
new SimpleChannelPromiseAggregator(promise, channel, ImmediateEventExecutor.INSTANCE);
aggregatedPromise.newPromise();
aggregatedPromise.doneAllocatingPromises();
return aggregatedPromise.setFailure(cause);
}
doAnswer((Answer<ChannelFuture>) invocation -> {
ChannelPromise promise = invocation.getArgument(4);
assertFalse(promise.isVoid());
// This is what DefaultHttp2FrameWriter does... I hate mocking :-(.
SimpleChannelPromiseAggregator aggregatedPromise =
new SimpleChannelPromiseAggregator(promise, channel, ImmediateEventExecutor.INSTANCE);
aggregatedPromise.newPromise();
aggregatedPromise.doneAllocatingPromises();
return aggregatedPromise.setFailure(cause);
}).when(frameWriter).writeGoAway(
any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class), any(ChannelPromise.class));
handler.goAway(ctx, STREAM_ID, errorCode, data, newVoidPromise(channel));
@ -742,13 +711,10 @@ public class Http2ConnectionHandlerTest {
final Throwable cause = new RuntimeException("fake exception");
when(stream.id()).thenReturn(STREAM_ID);
when(frameWriter.writeRstStream(eq(ctx), eq(streamId), anyLong(), any(ChannelPromise.class)))
.then(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) throws Throwable {
ChannelPromise promise = invocationOnMock.getArgument(3);
assertFalse(promise.isVoid());
return promise.setFailure(cause);
}
.then((Answer<ChannelFuture>) invocationOnMock -> {
ChannelPromise promise = invocationOnMock.getArgument(3);
assertFalse(promise.isVoid());
return promise.setFailure(cause);
});
handler.resetStream(ctx, streamId, STREAM_CLOSED.code(), newVoidPromise(channel));
verify(frameWriter).writeRstStream(eq(ctx), eq(streamId), anyLong(), any(ChannelPromise.class));

View File

@ -148,50 +148,38 @@ public class Http2ConnectionRoundtripTest {
public void inflightFrameAfterStreamResetShouldNotMakeConnectionUnusable() throws Exception {
bootstrapEnv(1, 1, 2, 1);
final CountDownLatch latch = new CountDownLatch(1);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
ChannelHandlerContext ctx = invocationOnMock.getArgument(0);
http2Server.encoder().writeHeaders(ctx,
(Integer) invocationOnMock.getArgument(1),
(Http2Headers) invocationOnMock.getArgument(2),
0,
false,
ctx.newPromise());
http2Server.flush(ctx);
return null;
}
doAnswer(invocationOnMock -> {
ChannelHandlerContext ctx = invocationOnMock.getArgument(0);
http2Server.encoder().writeHeaders(ctx,
(Integer) invocationOnMock.getArgument(1),
(Http2Headers) invocationOnMock.getArgument(2),
0,
false,
ctx.newPromise());
http2Server.flush(ctx);
return null;
}).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class),
anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
latch.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
latch.countDown();
return null;
}).when(clientListener).onHeadersRead(any(ChannelHandlerContext.class), eq(5), any(Http2Headers.class),
anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean());
// Create a single stream by sending a HEADERS frame to the server.
final short weight = 16;
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, false, newPromise());
http2Client.flush(ctx());
http2Client.encoder().writeRstStream(ctx(), 3, Http2Error.INTERNAL_ERROR.code(), newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, false, newPromise());
http2Client.flush(ctx());
http2Client.encoder().writeRstStream(ctx(), 3, Http2Error.INTERNAL_ERROR.code(), newPromise());
http2Client.flush(ctx());
});
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, weight, false, 0, false, newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, weight, false, 0, false, newPromise());
http2Client.flush(ctx());
});
assertTrue(latch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -204,13 +192,10 @@ public class Http2ConnectionRoundtripTest {
// Create a single stream by sending a HEADERS frame to the server.
final short weight = 16;
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, true,
newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, weight, false, 0, true,
newPromise());
http2Client.flush(ctx());
});
assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -245,68 +230,45 @@ public class Http2ConnectionRoundtripTest {
final Http2Headers headers = dummyHeaders();
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
serverSettingsAckLatch1.countDown();
serverSettingsAckLatch2.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
serverSettingsAckLatch1.countDown();
serverSettingsAckLatch2.countDown();
return null;
}).when(serverListener).onSettingsAckRead(any(ChannelHandlerContext.class));
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
clientSettingsLatch1.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
clientSettingsLatch1.countDown();
return null;
}).when(clientListener).onSettingsRead(any(ChannelHandlerContext.class), any(Http2Settings.class));
// Manually add a listener for when we receive the expected headers on the server.
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
serverRevHeadersLatch.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
serverRevHeadersLatch.countDown();
return null;
}).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(5), eq(headers),
anyInt(), anyShort(), anyBoolean(), eq(0), eq(true));
// Set the maxHeaderListSize to 100 so we may be able to write some headers, but not all. We want to verify
// that we don't corrupt state if some can be written but not all.
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.maxHeaderListSize(100),
serverNewPromise());
http2Server.flush(serverCtx());
}
runInChannel(serverConnectedChannel, () -> {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.maxHeaderListSize(100),
serverNewPromise());
http2Server.flush(serverCtx());
});
assertTrue(serverSettingsAckLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, false, newPromise())
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientHeadersWriteException.set(future.cause());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, false, newPromise())
.addListener((ChannelFutureListener) future -> clientHeadersWriteException.set(future.cause()));
// It is expected that this write should fail locally and the remote peer will never see this.
http2Client.encoder().writeData(ctx(), 3, Unpooled.buffer(), 0, true, newPromise())
.addListener((ChannelFutureListener) future -> {
clientDataWriteException.set(future.cause());
clientDataWrite.countDown();
});
// It is expected that this write should fail locally and the remote peer will never see this.
http2Client.encoder().writeData(ctx(), 3, Unpooled.buffer(), 0, true, newPromise())
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientDataWriteException.set(future.cause());
clientDataWrite.countDown();
}
});
http2Client.flush(ctx());
}
http2Client.flush(ctx());
});
assertTrue(clientDataWrite.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -314,33 +276,24 @@ public class Http2ConnectionRoundtripTest {
assertNotNull("Data on closed stream should fail!", clientDataWriteException.get());
// Set the maxHeaderListSize to the max value so we can send the headers.
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.maxHeaderListSize(Http2CodecUtil.MAX_HEADER_LIST_SIZE),
serverNewPromise());
http2Server.flush(serverCtx());
}
runInChannel(serverConnectedChannel, () -> {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.maxHeaderListSize(Http2CodecUtil.MAX_HEADER_LIST_SIZE),
serverNewPromise());
http2Server.flush(serverCtx());
});
assertTrue(clientSettingsLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
assertTrue(serverSettingsAckLatch2.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, true,
newPromise()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientHeadersWriteException2.set(future.cause());
clientHeadersLatch.countDown();
}
});
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, true,
newPromise()).addListener((ChannelFutureListener) future -> {
clientHeadersWriteException2.set(future.cause());
clientHeadersLatch.countDown();
});
http2Client.flush(ctx());
});
assertTrue(clientHeadersLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -371,69 +324,54 @@ public class Http2ConnectionRoundtripTest {
final byte[] data = new byte[] {1, 2, 3, 4, 5};
final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
serverSettingsAckLatch1.countDown();
serverSettingsAckLatch2.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
serverSettingsAckLatch1.countDown();
serverSettingsAckLatch2.countDown();
return null;
}).when(serverListener).onSettingsAckRead(any(ChannelHandlerContext.class));
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock in) throws Throwable {
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
doAnswer((Answer<Integer>) in -> {
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
buf.readBytes(out, buf.readableBytes());
serverDataLatch.countDown();
return processedBytes;
}
buf.readBytes(out, buf.readableBytes());
serverDataLatch.countDown();
return processedBytes;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3),
any(ByteBuf.class), eq(0), anyBoolean());
final Http2Headers headers = dummyHeaders();
// The server initially reduces the connection flow control window to 0.
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.initialWindowSize(0),
serverNewPromise());
http2Server.flush(serverCtx());
}
runInChannel(serverConnectedChannel, () -> {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.initialWindowSize(0),
serverNewPromise());
http2Server.flush(serverCtx());
});
assertTrue(serverSettingsAckLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
// The client should now attempt to send data, but the window size is 0 so it will be queued in the flow
// controller.
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.encoder().writeData(ctx(), 3, Unpooled.wrappedBuffer(data), 0, true, newPromise());
http2Client.flush(ctx());
clientWriteDataLatch.countDown();
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.encoder().writeData(ctx(), 3, Unpooled.wrappedBuffer(data), 0, true, newPromise());
http2Client.flush(ctx());
clientWriteDataLatch.countDown();
});
assertTrue(clientWriteDataLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
// Now the server opens up the connection window to allow the client to send the pending data.
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.initialWindowSize(data.length),
serverNewPromise());
http2Server.flush(serverCtx());
}
runInChannel(serverConnectedChannel, () -> {
http2Server.encoder().writeSettings(serverCtx(),
new Http2Settings().copyFrom(http2Server.decoder().localSettings())
.initialWindowSize(data.length),
serverNewPromise());
http2Server.flush(serverCtx());
});
assertTrue(serverSettingsAckLatch2.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -454,14 +392,11 @@ public class Http2ConnectionRoundtripTest {
bootstrapEnv(1, 1, 2, 0);
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writePriority(ctx(), 5, 3, (short) 14, false, newPromise());
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writePriority(ctx(), 5, 3, (short) 14, false, newPromise());
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
});
assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -486,15 +421,12 @@ public class Http2ConnectionRoundtripTest {
bootstrapEnv(1, 1, 1, 0);
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.encoder().frameWriter().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.encoder().frameWriter().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
});
assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -525,24 +457,18 @@ public class Http2ConnectionRoundtripTest {
final Http2Headers headers = dummyHeaders();
final int streamId = 3;
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), streamId, headers, CONNECTION_STREAM_ID,
DEFAULT_PRIORITY_WEIGHT, false, 0, false, newPromise());
http2Client.encoder().writeRstStream(ctx(), streamId, Http2Error.CANCEL.code(), newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), streamId, headers, CONNECTION_STREAM_ID,
DEFAULT_PRIORITY_WEIGHT, false, 0, false, newPromise());
http2Client.encoder().writeRstStream(ctx(), streamId, Http2Error.CANCEL.code(), newPromise());
http2Client.flush(ctx());
});
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
if (streamId == (Integer) invocationOnMock.getArgument(1)) {
serverGotRstLatch.countDown();
}
return null;
doAnswer((Answer<Void>) invocationOnMock -> {
if (streamId == (Integer) invocationOnMock.getArgument(1)) {
serverGotRstLatch.countDown();
}
return null;
}).when(serverListener).onRstStreamRead(any(ChannelHandlerContext.class), eq(streamId), anyLong());
assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -552,19 +478,13 @@ public class Http2ConnectionRoundtripTest {
anyShort(), anyBoolean(), anyInt(), eq(false));
// Now have the server attempt to send a headers frame simulating some asynchronous work.
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeHeaders(serverCtx(), streamId, headers, 0, true, serverNewPromise())
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
serverWriteHeadersCauseRef.set(future.cause());
serverWriteHeadersLatch.countDown();
}
});
http2Server.flush(serverCtx());
}
runInChannel(serverConnectedChannel, () -> {
http2Server.encoder().writeHeaders(serverCtx(), streamId, headers, 0, true, serverNewPromise())
.addListener((ChannelFutureListener) future -> {
serverWriteHeadersCauseRef.set(future.cause());
serverWriteHeadersLatch.countDown();
});
http2Server.flush(serverCtx());
});
assertTrue(serverWriteHeadersLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -586,22 +506,14 @@ public class Http2ConnectionRoundtripTest {
// Create a latch to track when the close occurs.
final CountDownLatch closeLatch = new CountDownLatch(1);
clientChannel.closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
closeLatch.countDown();
}
});
clientChannel.closeFuture().addListener((ChannelFutureListener) future -> closeLatch.countDown());
// Create a single stream by sending a HEADERS frame to the server.
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
});
// Wait for the server to create the stream.
@ -632,21 +544,13 @@ public class Http2ConnectionRoundtripTest {
// Create a latch to track when the close occurs.
final CountDownLatch closeLatch = new CountDownLatch(1);
clientChannel.closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
closeLatch.countDown();
}
});
clientChannel.closeFuture().addListener((ChannelFutureListener) future -> closeLatch.countDown());
// Create a single stream by sending a HEADERS frame to the server.
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
});
// Wait for the server to create the stream.
@ -690,37 +594,34 @@ public class Http2ConnectionRoundtripTest {
bootstrapEnv(1, 1, 2, 1);
final ChannelPromise emptyDataPromise = newPromise();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false,
newPromise());
ByteBuf emptyBuf = Unpooled.buffer();
emptyBuf.release();
switch (mode) {
case SINGLE_END_OF_STREAM:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, true, emptyDataPromise);
break;
case SECOND_END_OF_STREAM:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise);
http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, true, newPromise());
break;
case SINGLE_WITH_TRAILERS:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise);
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0,
(short) 16, false, 0, true, newPromise());
break;
case SECOND_WITH_TRAILERS:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise);
http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, newPromise());
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0,
(short) 16, false, 0, true, newPromise());
break;
default:
throw new Error();
}
http2Client.flush(ctx());
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false,
newPromise());
ByteBuf emptyBuf = Unpooled.buffer();
emptyBuf.release();
switch (mode) {
case SINGLE_END_OF_STREAM:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, true, emptyDataPromise);
break;
case SECOND_END_OF_STREAM:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise);
http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, true, newPromise());
break;
case SINGLE_WITH_TRAILERS:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise);
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0,
(short) 16, false, 0, true, newPromise());
break;
case SECOND_WITH_TRAILERS:
http2Client.encoder().writeData(ctx(), 3, emptyBuf, 0, false, emptyDataPromise);
http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, newPromise());
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0,
(short) 16, false, 0, true, newPromise());
break;
default:
throw new Error();
}
http2Client.flush(ctx());
});
try {
@ -739,38 +640,35 @@ public class Http2ConnectionRoundtripTest {
final ChannelPromise dataPromise = newPromise();
final ChannelPromise assertPromise = newPromise();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false,
newPromise());
clientChannel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ReferenceCountUtil.release(msg);
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false,
newPromise());
clientChannel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ReferenceCountUtil.release(msg);
// Ensure we update the window size so we will try to write the rest of the frame while
// processing the flush.
http2Client.encoder().flowController().initialWindowSize(8);
promise.setFailure(new IllegalStateException());
}
});
http2Client.encoder().flowController().initialWindowSize(4);
http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, dataPromise);
assertTrue(http2Client.encoder().flowController()
.hasFlowControlled(http2Client.connection().stream(3)));
http2Client.flush(ctx());
try {
// The Frame should have been removed after the write failed.
assertFalse(http2Client.encoder().flowController()
.hasFlowControlled(http2Client.connection().stream(3)));
assertPromise.setSuccess();
} catch (Throwable error) {
assertPromise.setFailure(error);
// Ensure we update the window size so we will try to write the rest of the frame while
// processing the flush.
http2Client.encoder().flowController().initialWindowSize(8);
promise.setFailure(new IllegalStateException());
}
});
http2Client.encoder().flowController().initialWindowSize(4);
http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, dataPromise);
assertTrue(http2Client.encoder().flowController()
.hasFlowControlled(http2Client.connection().stream(3)));
http2Client.flush(ctx());
try {
// The Frame should have been removed after the write failed.
assertFalse(http2Client.encoder().flowController()
.hasFlowControlled(http2Client.connection().stream(3)));
assertPromise.setSuccess();
} catch (Throwable error) {
assertPromise.setFailure(error);
}
});
@ -790,22 +688,14 @@ public class Http2ConnectionRoundtripTest {
// Create a latch to track when the close occurs.
final CountDownLatch closeLatch = new CountDownLatch(1);
clientChannel.closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
closeLatch.countDown();
}
});
clientChannel.closeFuture().addListener((ChannelFutureListener) future -> closeLatch.countDown());
// Create a single stream by sending a HEADERS frame to the server.
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false,
newPromise());
http2Client.flush(ctx());
});
// Wait for the server to create the stream.
@ -837,24 +727,18 @@ public class Http2ConnectionRoundtripTest {
// Create a single stream by sending a HEADERS frame to the server.
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
});
assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), MAX_VALUE + 1, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), MAX_VALUE + 1, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
});
assertTrue(goAwayLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -871,23 +755,17 @@ public class Http2ConnectionRoundtripTest {
setServerGracefulShutdownTime(10000);
final CountDownLatch clientGoAwayLatch = new CountDownLatch(1);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
clientGoAwayLatch.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
clientGoAwayLatch.countDown();
return null;
}).when(clientListener).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class));
// Create a single stream by sending a HEADERS frame to the server.
final Http2Headers headers = dummyHeaders();
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
false, newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
false, newPromise());
http2Client.flush(ctx());
});
assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -895,12 +773,9 @@ public class Http2ConnectionRoundtripTest {
// Server has received the headers, so the stream is open
assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
runInChannel(serverChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise());
http2Server.flush(serverCtx());
}
runInChannel(serverChannel, () -> {
http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise());
http2Server.flush(serverCtx());
});
// wait for the client to receive the GO_AWAY.
@ -910,20 +785,12 @@ public class Http2ConnectionRoundtripTest {
final AtomicReference<ChannelFuture> clientWriteAfterGoAwayFutureRef = new AtomicReference<>();
final CountDownLatch clientWriteAfterGoAwayLatch = new CountDownLatch(1);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0,
true, newPromise());
clientWriteAfterGoAwayFutureRef.set(f);
http2Client.flush(ctx());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientWriteAfterGoAwayLatch.countDown();
}
});
}
runInChannel(clientChannel, () -> {
ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0,
true, newPromise());
clientWriteAfterGoAwayFutureRef.set(f);
http2Client.flush(ctx());
f.addListener((ChannelFutureListener) future -> clientWriteAfterGoAwayLatch.countDown());
});
// Wait for the client's write operation to complete.
@ -950,12 +817,9 @@ public class Http2ConnectionRoundtripTest {
bootstrapEnv(1, 1, 2, 1, 1);
final CountDownLatch clientGoAwayLatch = new CountDownLatch(1);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
clientGoAwayLatch.countDown();
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
clientGoAwayLatch.countDown();
return null;
}).when(clientListener).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class));
// We want both sides to do graceful shutdown during the test.
@ -965,30 +829,19 @@ public class Http2ConnectionRoundtripTest {
final Http2Headers headers = dummyHeaders();
final AtomicReference<ChannelFuture> clientWriteAfterGoAwayFutureRef = new AtomicReference<>();
final CountDownLatch clientWriteAfterGoAwayLatch = new CountDownLatch(1);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0,
true, newPromise());
clientWriteAfterGoAwayFutureRef.set(f);
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientWriteAfterGoAwayLatch.countDown();
}
});
http2Client.flush(ctx());
return null;
}
doAnswer((Answer<Void>) invocationOnMock -> {
ChannelFuture f = http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, (short) 16, false, 0,
true, newPromise());
clientWriteAfterGoAwayFutureRef.set(f);
f.addListener((ChannelFutureListener) future -> clientWriteAfterGoAwayLatch.countDown());
http2Client.flush(ctx());
return null;
}).when(clientListener).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
});
assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
@ -996,12 +849,9 @@ public class Http2ConnectionRoundtripTest {
// Server has received the headers, so the stream is open
assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
runInChannel(serverChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise());
http2Server.flush(serverCtx());
}
runInChannel(serverChannel, () -> {
http2Server.encoder().writeGoAway(serverCtx(), 3, NO_ERROR.code(), EMPTY_BUFFER, serverNewPromise());
http2Server.flush(serverCtx());
});
// Wait for the client's write operation to complete.
@ -1033,16 +883,13 @@ public class Http2ConnectionRoundtripTest {
// Create a buffer filled with random bytes.
final ByteBuf data = randomBytes(length);
final ByteArrayOutputStream out = new ByteArrayOutputStream(length);
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock in) throws Throwable {
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
doAnswer((Answer<Integer>) in -> {
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
buf.readBytes(out, buf.readableBytes());
return processedBytes;
}
buf.readBytes(out, buf.readableBytes());
return processedBytes;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3),
any(ByteBuf.class), eq(0), anyBoolean());
try {
@ -1050,18 +897,15 @@ public class Http2ConnectionRoundtripTest {
bootstrapEnv(length, 1, 2, 1);
// Create the stream and send all of the data at once.
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
false, newPromise());
http2Client.encoder().writeData(ctx(), 3, data.retainedDuplicate(), 0, false, newPromise());
runInChannel(clientChannel, () -> {
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
false, newPromise());
http2Client.encoder().writeData(ctx(), 3, data.retainedDuplicate(), 0, false, newPromise());
// Write trailers.
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
}
// Write trailers.
http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0,
true, newPromise());
http2Client.flush(ctx());
});
// Wait for the trailers to be received.
@ -1110,44 +954,38 @@ public class Http2ConnectionRoundtripTest {
// Collect all the data buffers as we receive them at the server.
final StringBuilder[] receivedData = new StringBuilder[numStreams];
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock in) throws Throwable {
int streamId = (Integer) in.getArguments()[1];
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
doAnswer((Answer<Integer>) in -> {
int streamId = (Integer) in.getArguments()[1];
ByteBuf buf = (ByteBuf) in.getArguments()[2];
int padding = (Integer) in.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
int streamIndex = (streamId - 3) / 2;
StringBuilder builder = receivedData[streamIndex];
if (builder == null) {
builder = new StringBuilder(dataAsHex.length());
receivedData[streamIndex] = builder;
}
builder.append(ByteBufUtil.hexDump(buf));
return processedBytes;
int streamIndex = (streamId - 3) / 2;
StringBuilder builder = receivedData[streamIndex];
if (builder == null) {
builder = new StringBuilder(dataAsHex.length());
receivedData[streamIndex] = builder;
}
builder.append(ByteBufUtil.hexDump(buf));
return processedBytes;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), anyInt(),
any(ByteBuf.class), anyInt(), anyBoolean());
try {
bootstrapEnv(numStreams * length, 1, numStreams * 4, numStreams);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
int upperLimit = 3 + 2 * numStreams;
for (int streamId = 3; streamId < upperLimit; streamId += 2) {
// Send a bunch of data on each stream.
http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16,
false, 0, false, newPromise());
http2Client.encoder().writePing(ctx(), false, pingData,
newPromise());
http2Client.encoder().writeData(ctx(), streamId, data.retainedSlice(), 0,
false, newPromise());
// Write trailers.
http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16,
false, 0, true, newPromise());
http2Client.flush(ctx());
}
runInChannel(clientChannel, () -> {
int upperLimit = 3 + 2 * numStreams;
for (int streamId = 3; streamId < upperLimit; streamId += 2) {
// Send a bunch of data on each stream.
http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16,
false, 0, false, newPromise());
http2Client.encoder().writePing(ctx(), false, pingData,
newPromise());
http2Client.encoder().writeData(ctx(), streamId, data.retainedSlice(), 0,
false, newPromise());
// Write trailers.
http2Client.encoder().writeHeaders(ctx(), streamId, headers, 0, (short) 16,
false, 0, true, newPromise());
http2Client.flush(ctx());
}
});
// Wait for all frames to be received.
@ -1270,15 +1108,11 @@ public class Http2ConnectionRoundtripTest {
}
private static void mockFlowControl(Http2FrameListener listener) throws Http2Exception {
doAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
ByteBuf buf = (ByteBuf) invocation.getArguments()[2];
int padding = (Integer) invocation.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
return processedBytes;
}
doAnswer((Answer<Integer>) invocation -> {
ByteBuf buf = (ByteBuf) invocation.getArguments()[2];
int padding = (Integer) invocation.getArguments()[3];
int processedBytes = buf.readableBytes() + padding;
return processedBytes;
}).when(listener).onDataRead(any(ChannelHandlerContext.class), anyInt(),
any(ByteBuf.class), anyInt(), anyBoolean());
}
@ -1294,12 +1128,9 @@ public class Http2ConnectionRoundtripTest {
private static void setGracefulShutdownTime(Channel channel, final Http2ConnectionHandler handler,
final long millis) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
runInChannel(channel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
handler.gracefulShutdownTimeoutMillis(millis);
latch.countDown();
}
runInChannel(channel, () -> {
handler.gracefulShutdownTimeoutMillis(millis);
latch.countDown();
});
assertTrue(latch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));

View File

@ -573,15 +573,12 @@ public class Http2FrameCodecTest {
final Promise<Void> listenerExecuted = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false).stream(stream))
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
assertTrue(isStreamIdValid(stream.id()));
listenerExecuted.setSuccess(null);
}
}
);
.addListener((ChannelFutureListener) future -> {
assertTrue(future.isSuccess());
assertTrue(isStreamIdValid(stream.id()));
listenerExecuted.setSuccess(null);
}
);
ByteBuf data = Unpooled.buffer().writeZero(100);
ChannelFuture f = channel.writeAndFlush(new DefaultHttp2DataFrame(data).stream(stream));
assertTrue(f.isSuccess());
@ -735,12 +732,9 @@ public class Http2FrameCodecTest {
Http2FrameStream idleStream = frameCodec.newStream();
final Set<Http2FrameStream> activeStreams = new HashSet<>();
frameCodec.forEachActiveStream(new Http2FrameStreamVisitor() {
@Override
public boolean visit(Http2FrameStream stream) {
activeStreams.add(stream);
return true;
}
frameCodec.forEachActiveStream(stream -> {
activeStreams.add(stream);
return true;
});
assertEquals(2, activeStreams.size());
@ -758,13 +752,10 @@ public class Http2FrameCodecTest {
final AtomicBoolean listenerExecuted = new AtomicBoolean();
channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()).stream(stream2))
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
assertEquals(State.OPEN, stream2.state());
listenerExecuted.set(true);
}
.addListener((ChannelFutureListener) future -> {
assertTrue(future.isSuccess());
assertEquals(State.OPEN, stream2.state());
listenerExecuted.set(true);
});
assertTrue(listenerExecuted.get());
@ -795,15 +786,12 @@ public class Http2FrameCodecTest {
// Simulate consuming the frame and update the flow-controller.
Http2DataFrame data = (Http2DataFrame) msg;
ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(data.initialFlowControlledBytes())
.stream(data.stream())).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if (cause != null) {
ctx.fireExceptionCaught(cause);
}
}
});
.stream(data.stream())).addListener((ChannelFutureListener) future -> {
Throwable cause = future.cause();
if (cause != null) {
ctx.fireExceptionCaught(cause);
}
});
}
ReferenceCountUtil.release(msg);
}

View File

@ -97,24 +97,10 @@ public class Http2FrameRoundtripTest {
when(ctx.alloc()).thenReturn(alloc);
when(ctx.executor()).thenReturn(executor);
when(ctx.channel()).thenReturn(channel);
doAnswer(new Answer<ByteBuf>() {
@Override
public ByteBuf answer(InvocationOnMock in) throws Throwable {
return Unpooled.buffer();
}
}).when(alloc).buffer();
doAnswer(new Answer<ByteBuf>() {
@Override
public ByteBuf answer(InvocationOnMock in) throws Throwable {
return Unpooled.buffer((Integer) in.getArguments()[0]);
}
}).when(alloc).buffer(anyInt());
doAnswer(new Answer<ChannelPromise>() {
@Override
public ChannelPromise answer(InvocationOnMock invocation) throws Throwable {
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE);
}
}).when(ctx).newPromise();
doAnswer((Answer<ByteBuf>) in -> Unpooled.buffer()).when(alloc).buffer();
doAnswer((Answer<ByteBuf>) in -> Unpooled.buffer((Integer) in.getArguments()[0])).when(alloc).buffer(anyInt());
doAnswer((Answer<ChannelPromise>) invocation ->
new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE)).when(ctx).newPromise();
writer = new DefaultHttp2FrameWriter(new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE, newTestEncoder()));
reader = new DefaultHttp2FrameReader(new DefaultHttp2HeadersDecoder(false, newTestDecoder()));

View File

@ -245,12 +245,7 @@ public class Http2MultiplexCodecTest {
frameInboundWriter.writeInboundData(channel.stream().id(), tenBytes, 0, true);
// Verify we marked the bytes as consumed
verify(flowController).consumeBytes(argThat(new ArgumentMatcher<Http2Stream>() {
@Override
public boolean matches(Http2Stream http2Stream) {
return http2Stream.id() == channel.stream().id();
}
}), eq(10));
verify(flowController).consumeBytes(argThat(http2Stream -> http2Stream.id() == channel.stream().id()), eq(10));
// headers and data frame
verifyFramesMultiplexedToCorrectChannel(channel, handler, 2);
@ -459,13 +454,9 @@ public class Http2MultiplexCodecTest {
Http2Headers headers = new DefaultHttp2Headers();
when(frameWriter.writeHeaders(eqMultiplexCodecCtx(), anyInt(),
eq(headers), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(8)).setFailure(
new StreamException(childChannel.stream().id(), Http2Error.STREAM_CLOSED, "Stream Closed"));
}
});
any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(8)).setFailure(
new StreamException(childChannel.stream().id(), Http2Error.STREAM_CLOSED, "Stream Closed")));
ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
parentChannel.flush();
@ -521,13 +512,9 @@ public class Http2MultiplexCodecTest {
Http2Headers headers = new DefaultHttp2Headers();
when(frameWriter.writeHeaders(eqMultiplexCodecCtx(), anyInt(),
eq(headers), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(8)).setFailure(
new Http2NoMoreStreamIdsException());
}
});
any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(8)).setFailure(
new Http2NoMoreStreamIdsException()));
ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));
parentChannel.flush();
@ -554,12 +541,9 @@ public class Http2MultiplexCodecTest {
// Create a promise before actually doing the close, because otherwise we would be adding a listener to a future
// that is already completed because we are using EmbeddedChannel which executes code in the JUnit thread.
ChannelPromise p = childChannel.newPromise();
p.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
channelOpen.set(future.channel().isOpen());
channelActive.set(future.channel().isActive());
}
p.addListener((ChannelFutureListener) future -> {
channelOpen.set(future.channel().isOpen());
channelActive.set(future.channel().isActive());
});
childChannel.close(p).syncUninterruptibly();
@ -579,12 +563,9 @@ public class Http2MultiplexCodecTest {
final AtomicBoolean channelOpen = new AtomicBoolean(true);
final AtomicBoolean channelActive = new AtomicBoolean(true);
childChannel.closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
channelOpen.set(future.channel().isOpen());
channelActive.set(future.channel().isActive());
}
childChannel.closeFuture().addListener((ChannelFutureListener) future -> {
channelOpen.set(future.channel().isOpen());
channelActive.set(future.channel().isActive());
});
childChannel.close().syncUninterruptibly();
@ -609,23 +590,17 @@ public class Http2MultiplexCodecTest {
Http2Headers headers = new DefaultHttp2Headers();
when(frameWriter.writeHeaders(eqMultiplexCodecCtx(), anyInt(),
eq(headers), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
ChannelPromise promise = invocationOnMock.getArgument(8);
writePromises.offer(promise);
return promise;
}
});
any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock -> {
ChannelPromise promise = invocationOnMock.getArgument(8);
writePromises.offer(promise);
return promise;
});
ChannelFuture f = childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers));
assertFalse(f.isDone());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
channelOpen.set(future.channel().isOpen());
channelActive.set(future.channel().isActive());
}
f.addListener((ChannelFutureListener) future -> {
channelOpen.set(future.channel().isOpen());
channelActive.set(future.channel().isActive());
});
ChannelPromise first = writePromises.poll();
@ -794,12 +769,9 @@ public class Http2MultiplexCodecTest {
public void endOfStreamDoesNotDiscardData() {
AtomicInteger numReads = new AtomicInteger(1);
final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();
Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {
@Override
public void accept(ChannelHandlerContext obj) {
if (shouldDisableAutoRead.get()) {
obj.channel().config().setAutoRead(false);
}
Consumer<ChannelHandlerContext> ctxConsumer = obj -> {
if (shouldDisableAutoRead.get()) {
obj.channel().config().setAutoRead(false);
}
};
LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);
@ -859,13 +831,10 @@ public class Http2MultiplexCodecTest {
AtomicInteger numReads = new AtomicInteger(1);
final AtomicInteger channelReadCompleteCount = new AtomicInteger(0);
final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();
Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {
@Override
public void accept(ChannelHandlerContext obj) {
channelReadCompleteCount.incrementAndGet();
if (shouldDisableAutoRead.get()) {
obj.channel().config().setAutoRead(false);
}
Consumer<ChannelHandlerContext> ctxConsumer = obj -> {
channelReadCompleteCount.incrementAndGet();
if (shouldDisableAutoRead.get()) {
obj.channel().config().setAutoRead(false);
}
};
LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);
@ -922,13 +891,10 @@ public class Http2MultiplexCodecTest {
final AtomicInteger numReads = new AtomicInteger(1);
final AtomicInteger channelReadCompleteCount = new AtomicInteger(0);
final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();
Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {
@Override
public void accept(ChannelHandlerContext obj) {
channelReadCompleteCount.incrementAndGet();
if (shouldDisableAutoRead.get()) {
obj.channel().config().setAutoRead(false);
}
Consumer<ChannelHandlerContext> ctxConsumer = obj -> {
channelReadCompleteCount.incrementAndGet();
if (shouldDisableAutoRead.get()) {
obj.channel().config().setAutoRead(false);
}
};
final LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);

View File

@ -70,14 +70,11 @@ public final class Http2TestUtil {
* Runs the given operation within the event loop thread of the given {@link Channel}.
*/
static void runInChannel(Channel channel, final Http2Runnable runnable) {
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
runnable.run();
} catch (Http2Exception e) {
throw new RuntimeException(e);
}
channel.eventLoop().execute(() -> {
try {
runnable.run();
} catch (Http2Exception e) {
throw new RuntimeException(e);
}
});
}
@ -477,12 +474,9 @@ public final class Http2TestUtil {
public ChannelPromise unvoid() {
ChannelPromise promise =
new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
channel().pipeline().fireExceptionCaught(future.cause());
}
promise.addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
channel().pipeline().fireExceptionCaught(future.cause());
}
});
return promise;
@ -575,103 +569,63 @@ public final class Http2TestUtil {
final ConcurrentLinkedQueue<ByteBuf> buffers = new ConcurrentLinkedQueue<>();
Http2FrameWriter frameWriter = Mockito.mock(Http2FrameWriter.class);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) {
for (;;) {
ByteBuf buf = buffers.poll();
if (buf == null) {
break;
}
buf.release();
doAnswer(invocationOnMock -> {
for (;;) {
ByteBuf buf = buffers.poll();
if (buf == null) {
break;
}
return null;
buf.release();
}
return null;
}).when(frameWriter).close();
when(frameWriter.configuration()).thenReturn(configuration);
when(frameWriter.writeSettings(any(ChannelHandlerContext.class), any(Http2Settings.class),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(2)).setSuccess();
}
});
any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(2)).setSuccess());
when(frameWriter.writeSettingsAck(any(ChannelHandlerContext.class), any(ChannelPromise.class)))
.thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(1)).setSuccess();
}
});
.thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(1)).setSuccess());
when(frameWriter.writeGoAway(any(ChannelHandlerContext.class), anyInt(),
anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
buffers.offer((ByteBuf) invocationOnMock.getArgument(3));
return ((ChannelPromise) invocationOnMock.getArgument(4)).setSuccess();
}
});
anyLong(), any(ByteBuf.class), any(ChannelPromise.class))).thenAnswer(invocationOnMock -> {
buffers.offer((ByteBuf) invocationOnMock.getArgument(3));
return ((ChannelPromise) invocationOnMock.getArgument(4)).setSuccess();
});
when(frameWriter.writeHeaders(any(ChannelHandlerContext.class), anyInt(), any(Http2Headers.class), anyInt(),
anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
anyBoolean(), any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess());
when(frameWriter.writeHeaders(any(ChannelHandlerContext.class), anyInt(),
any(Http2Headers.class), anyInt(), anyShort(), anyBoolean(), anyInt(), anyBoolean(),
any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(8)).setSuccess();
}
});
any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(8)).setSuccess());
when(frameWriter.writeData(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(),
anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
buffers.offer((ByteBuf) invocationOnMock.getArgument(2));
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
anyBoolean(), any(ChannelPromise.class))).thenAnswer(invocationOnMock -> {
buffers.offer((ByteBuf) invocationOnMock.getArgument(2));
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
});
when(frameWriter.writeRstStream(any(ChannelHandlerContext.class), anyInt(),
anyLong(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess();
}
});
anyLong(), any(ChannelPromise.class))).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess());
when(frameWriter.writeWindowUpdate(any(ChannelHandlerContext.class), anyInt(), anyInt(),
any(ChannelPromise.class))).then(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess();
}
});
any(ChannelPromise.class))).then((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(3)).setSuccess());
when(frameWriter.writePushPromise(any(ChannelHandlerContext.class), anyInt(), anyInt(), any(Http2Headers.class),
anyInt(), anyChannelPromise())).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
anyInt(), anyChannelPromise())).thenAnswer((Answer<ChannelFuture>) invocationOnMock ->
((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess());
when(frameWriter.writeFrame(any(ChannelHandlerContext.class), anyByte(), anyInt(), any(Http2Flags.class),
any(ByteBuf.class), anyChannelPromise())).thenAnswer(new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocationOnMock) {
buffers.offer((ByteBuf) invocationOnMock.getArgument(4));
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
}
});
any(ByteBuf.class), anyChannelPromise())).thenAnswer(invocationOnMock -> {
buffers.offer((ByteBuf) invocationOnMock.getArgument(4));
return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
});
return frameWriter;
}

View File

@ -337,12 +337,9 @@ public class HttpToHttp2ConnectionHandlerTest {
public void testRequestWithBody() throws Exception {
final String text = "foooooogoooo";
final List<String> receivedBuffers = Collections.synchronizedList(new ArrayList<>());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
return null;
}
doAnswer((Answer<Void>) in -> {
receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
return null;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3),
any(ByteBuf.class), eq(0), eq(true));
bootstrapEnv(3, 1, 0);
@ -380,12 +377,9 @@ public class HttpToHttp2ConnectionHandlerTest {
public void testRequestWithBodyAndTrailingHeaders() throws Exception {
final String text = "foooooogoooo";
final List<String> receivedBuffers = Collections.synchronizedList(new ArrayList<>());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
return null;
}
doAnswer((Answer<Void>) in -> {
receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
return null;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3),
any(ByteBuf.class), eq(0), eq(false));
bootstrapEnv(4, 1, 1);
@ -432,12 +426,9 @@ public class HttpToHttp2ConnectionHandlerTest {
final String text = "foooooo";
final String text2 = "goooo";
final List<String> receivedBuffers = Collections.synchronizedList(new ArrayList<>());
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
return null;
}
doAnswer((Answer<Void>) in -> {
receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
return null;
}).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3),
any(ByteBuf.class), eq(0), eq(false));
bootstrapEnv(4, 1, 1);

View File

@ -148,12 +148,9 @@ public class InboundHttp2ToHttpAdapterTest {
final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).
scheme(new AsciiString("https")).authority(new AsciiString("example.org"))
.path(new AsciiString("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -184,12 +181,9 @@ public class InboundHttp2ToHttpAdapterTest {
.add(HttpHeaderNames.COOKIE, "a=b")
.add(HttpHeaderNames.COOKIE, "c=d")
.add(HttpHeaderNames.COOKIE, "e=f");
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -219,12 +213,9 @@ public class InboundHttp2ToHttpAdapterTest {
.path(new AsciiString("/some/path/resource2"))
.add(HttpHeaderNames.COOKIE, "a=b; c=d")
.add(HttpHeaderNames.COOKIE, "e=f");
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -246,12 +237,9 @@ public class InboundHttp2ToHttpAdapterTest {
.path(new AsciiString("/some/path/resource2"))
.add(new AsciiString("çã".getBytes(CharsetUtil.UTF_8)),
new AsciiString("Ãã".getBytes(CharsetUtil.UTF_8)));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, true, newPromiseClient());
clientChannel.flush();
});
awaitResponses();
assertTrue(isStreamError(clientException));
@ -271,14 +259,11 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
new AsciiString("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true,
newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true,
newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -305,17 +290,14 @@ public class InboundHttp2ToHttpAdapterTest {
final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
new AsciiString("/some/path/resource2"));
final int midPoint = text.length() / 2;
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(
ctxClient(), 3, content.retainedSlice(0, midPoint), 0, false, newPromiseClient());
clientHandler.encoder().writeData(
ctxClient(), 3, content.retainedSlice(midPoint, text.length() - midPoint),
0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(
ctxClient(), 3, content.retainedSlice(0, midPoint), 0, false, newPromiseClient());
clientHandler.encoder().writeData(
ctxClient(), 3, content.retainedSlice(midPoint, text.length() - midPoint),
0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -341,15 +323,12 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(
new AsciiString("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -383,15 +362,12 @@ public class InboundHttp2ToHttpAdapterTest {
.set(new AsciiString("foo"), new AsciiString("goo"))
.set(new AsciiString("foo2"), new AsciiString("goo2"))
.add(new AsciiString("foo2"), new AsciiString("goo3"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, false,
newPromiseClient());
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers2, 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, false,
newPromiseClient());
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers2, 0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -428,19 +404,16 @@ public class InboundHttp2ToHttpAdapterTest {
new AsciiString("/some/path/resource"));
final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(new AsciiString("PUT")).path(
new AsciiString("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeHeaders(ctxClient(), 5, http2Headers2, 3, (short) 123, true, 0,
false, newPromiseClient());
clientChannel.flush(); // Headers are queued in the flow controller and so flush them.
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true,
newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 5, content2.retainedDuplicate(), 0, true,
newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientHandler.encoder().writeHeaders(ctxClient(), 5, http2Headers2, 3, (short) 123, true, 0,
false, newPromiseClient());
clientChannel.flush(); // Headers are queued in the flow controller and so flush them.
clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true,
newPromiseClient());
clientHandler.encoder().writeData(ctxClient(), 5, content2.retainedDuplicate(), 0, true,
newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> httpObjectCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -485,12 +458,9 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
final Http2Headers http2Headers3 = new DefaultHttp2Headers().method(new AsciiString("GET"))
.path(new AsciiString("/push/test"));
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers3, 0, true, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers3, 0, true, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -507,17 +477,14 @@ public class InboundHttp2ToHttpAdapterTest {
final Http2Headers http2Headers2 = new DefaultHttp2Headers()
.scheme(new AsciiString("https"))
.authority(new AsciiString("example.org"));
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
serverHandler.encoder().writeHeaders(ctxServer(), 3, http2Headers, 0, false, newPromiseServer());
serverHandler.encoder().writePushPromise(ctxServer(), 3, 2, http2Headers2, 0, newPromiseServer());
serverHandler.encoder().writeData(ctxServer(), 3, content.retainedDuplicate(), 0, true,
newPromiseServer());
serverHandler.encoder().writeData(ctxServer(), 5, content2.retainedDuplicate(), 0, true,
newPromiseServer());
serverConnectedChannel.flush();
}
runInChannel(serverConnectedChannel, () -> {
serverHandler.encoder().writeHeaders(ctxServer(), 3, http2Headers, 0, false, newPromiseServer());
serverHandler.encoder().writePushPromise(ctxServer(), 3, 2, http2Headers2, 0, newPromiseServer());
serverHandler.encoder().writeData(ctxServer(), 3, content.retainedDuplicate(), 0, true,
newPromiseServer());
serverHandler.encoder().writeData(ctxServer(), 5, content2.retainedDuplicate(), 0, true,
newPromiseServer());
serverConnectedChannel.flush();
});
awaitResponses();
ArgumentCaptor<FullHttpMessage> responseCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
@ -553,12 +520,9 @@ public class InboundHttp2ToHttpAdapterTest {
final FullHttpMessage response2 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
try {
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
clientChannel.flush();
});
awaitRequests();
@ -566,26 +530,20 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
final Http2Headers http2HeadersResponse = new DefaultHttp2Headers().status(new AsciiString("100"));
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse, 0, false,
newPromiseServer());
serverConnectedChannel.flush();
}
runInChannel(serverConnectedChannel, () -> {
serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse, 0, false,
newPromiseServer());
serverConnectedChannel.flush();
});
awaitResponses();
httpHeaders = request2.headers();
httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
httpHeaders.remove(HttpHeaderNames.EXPECT);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() {
clientHandler.encoder().writeData(ctxClient(), 3, payload.retainedDuplicate(), 0, true,
newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeData(ctxClient(), 3, payload.retainedDuplicate(), 0, true,
newPromiseClient());
clientChannel.flush();
});
awaitRequests2();
@ -595,13 +553,10 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
final Http2Headers http2HeadersResponse2 = new DefaultHttp2Headers().status(new AsciiString("200"));
runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override
public void run() throws Http2Exception {
serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse2, 0, true,
newPromiseServer());
serverConnectedChannel.flush();
}
runInChannel(serverConnectedChannel, () -> {
serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse2, 0, true,
newPromiseServer());
serverConnectedChannel.flush();
});
awaitResponses2();
@ -633,12 +588,9 @@ public class InboundHttp2ToHttpAdapterTest {
public void propagateSettings() throws Exception {
boostrapEnv(1, 1, 2);
final Http2Settings settings = new Http2Settings().pushEnabled(true);
runInChannel(clientChannel, new Http2Runnable() {
@Override
public void run() {
clientHandler.encoder().writeSettings(ctxClient(), settings, newPromiseClient());
clientChannel.flush();
}
runInChannel(clientChannel, () -> {
clientHandler.encoder().writeSettings(ctxClient(), settings, newPromiseClient());
clientChannel.flush();
});
assertTrue(settingsLatch.await(5, SECONDS));
ArgumentCaptor<Http2Settings> settingsCaptor = ArgumentCaptor.forClass(Http2Settings.class);

View File

@ -46,10 +46,7 @@ public class LastInboundHandler extends ChannelDuplexHandler {
void accept(T obj);
}
private static final Consumer<Object> NOOP_CONSUMER = new Consumer<Object>() {
@Override
public void accept(Object obj) {
}
private static final Consumer<Object> NOOP_CONSUMER = obj -> {
};
@SuppressWarnings("unchecked")

View File

@ -130,12 +130,7 @@ public class StreamBufferingEncoderTest {
when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(executor.inEventLoop()).thenReturn(true);
doAnswer(new Answer<ChannelPromise>() {
@Override
public ChannelPromise answer(InvocationOnMock invocation) throws Throwable {
return newPromise();
}
}).when(ctx).newPromise();
doAnswer((Answer<ChannelPromise>) invocation -> newPromise()).when(ctx).newPromise();
when(ctx.executor()).thenReturn(executor);
when(channel.isActive()).thenReturn(false);
when(channel.config()).thenReturn(config);
@ -519,17 +514,14 @@ public class StreamBufferingEncoderTest {
}
private Answer<ChannelFuture> successAnswer() {
return new Answer<ChannelFuture>() {
@Override
public ChannelFuture answer(InvocationOnMock invocation) throws Throwable {
for (Object a : invocation.getArguments()) {
ReferenceCountUtil.safeRelease(a);
}
ChannelPromise future = newPromise();
future.setSuccess();
return future;
return invocation -> {
for (Object a : invocation.getArguments()) {
ReferenceCountUtil.safeRelease(a);
}
ChannelPromise future = newPromise();
future.setSuccess();
return future;
};
}

View File

@ -83,17 +83,14 @@ public class UniformStreamByteDistributorTest {
}
private Answer<Void> writeAnswer() {
return new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
Http2Stream stream = in.getArgument(0);
int numBytes = in.getArgument(1);
TestStreamByteDistributorStreamState state = stateMap.get(stream.id());
state.pendingBytes -= numBytes;
state.hasFrame = state.pendingBytes > 0;
distributor.updateStreamableBytes(state);
return null;
}
return in -> {
Http2Stream stream = in.getArgument(0);
int numBytes = in.getArgument(1);
TestStreamByteDistributorStreamState state = stateMap.get(stream.id());
state.pendingBytes -= numBytes;
state.hasFrame = state.pendingBytes > 0;
distributor.updateStreamableBytes(state);
return null;
};
}

View File

@ -79,13 +79,10 @@ public class WeightedFairQueueByteDistributorDependencyTreeTest extends
final Http2Stream streamB = connection.local().createStream(5, false);
final Http2Stream streamC = connection.local().createStream(7, false);
setPriority(streamB.id(), streamA.id(), DEFAULT_PRIORITY_WEIGHT, false);
connection.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
streamA.close();
setPriority(streamB.id(), streamC.id(), DEFAULT_PRIORITY_WEIGHT, false);
return true;
}
connection.forEachActiveStream(stream -> {
streamA.close();
setPriority(streamB.id(), streamC.id(), DEFAULT_PRIORITY_WEIGHT, false);
return true;
});
}

View File

@ -29,33 +29,30 @@ import io.netty.util.NetUtil;
*/
public interface Socks5AddressEncoder {
Socks5AddressEncoder DEFAULT = new Socks5AddressEncoder() {
@Override
public void encodeAddress(Socks5AddressType addrType, String addrValue, ByteBuf out) throws Exception {
final byte typeVal = addrType.byteValue();
if (typeVal == Socks5AddressType.IPv4.byteValue()) {
if (addrValue != null) {
out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
} else {
out.writeInt(0);
}
} else if (typeVal == Socks5AddressType.DOMAIN.byteValue()) {
if (addrValue != null) {
out.writeByte(addrValue.length());
out.writeCharSequence(addrValue, CharsetUtil.US_ASCII);
} else {
out.writeByte(0);
}
} else if (typeVal == Socks5AddressType.IPv6.byteValue()) {
if (addrValue != null) {
out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
} else {
out.writeLong(0);
out.writeLong(0);
}
Socks5AddressEncoder DEFAULT = (addrType, addrValue, out) -> {
final byte typeVal = addrType.byteValue();
if (typeVal == Socks5AddressType.IPv4.byteValue()) {
if (addrValue != null) {
out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
} else {
throw new EncoderException("unsupported addrType: " + (addrType.byteValue() & 0xFF));
out.writeInt(0);
}
} else if (typeVal == Socks5AddressType.DOMAIN.byteValue()) {
if (addrValue != null) {
out.writeByte(addrValue.length());
out.writeCharSequence(addrValue, CharsetUtil.US_ASCII);
} else {
out.writeByte(0);
}
} else if (typeVal == Socks5AddressType.IPv6.byteValue()) {
if (addrValue != null) {
out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
} else {
out.writeLong(0);
out.writeLong(0);
}
} else {
throw new EncoderException("unsupported addrType: " + (addrType.byteValue() & 0xFF));
}
};

View File

@ -72,31 +72,28 @@ public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter
/**
* Cumulate {@link ByteBuf}s by merge them into one {@link ByteBuf}'s, using memory copies.
*/
public static final Cumulator MERGE_CUMULATOR = new Cumulator() {
@Override
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
try {
final ByteBuf buffer;
if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes()
|| cumulation.refCnt() > 1 || cumulation.isReadOnly()) {
// Expand cumulation (by replace it) when either there is not more room in the buffer
// or if the refCnt is greater then 1 which may happen when the user use slice().retain() or
// duplicate().retain() or if its read-only.
//
// See:
// - https://github.com/netty/netty/issues/2327
// - https://github.com/netty/netty/issues/1764
buffer = expandCumulation(alloc, cumulation, in.readableBytes());
} else {
buffer = cumulation;
}
buffer.writeBytes(in);
return buffer;
} finally {
// We must release in in all cases as otherwise it may produce a leak if writeBytes(...) throw
// for whatever release (for example because of OutOfMemoryError)
in.release();
public static final Cumulator MERGE_CUMULATOR = (alloc, cumulation, in) -> {
try {
final ByteBuf buffer;
if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes()
|| cumulation.refCnt() > 1 || cumulation.isReadOnly()) {
// Expand cumulation (by replace it) when either there is not more room in the buffer
// or if the refCnt is greater then 1 which may happen when the user use slice().retain() or
// duplicate().retain() or if its read-only.
//
// See:
// - https://github.com/netty/netty/issues/2327
// - https://github.com/netty/netty/issues/1764
buffer = expandCumulation(alloc, cumulation, in.readableBytes());
} else {
buffer = cumulation;
}
buffer.writeBytes(in);
return buffer;
} finally {
// We must release in in all cases as otherwise it may produce a leak if writeBytes(...) throw
// for whatever release (for example because of OutOfMemoryError)
in.release();
}
};
@ -105,39 +102,36 @@ public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter
* Be aware that {@link CompositeByteBuf} use a more complex indexing implementation so depending on your use-case
* and the decoder implementation this may be slower then just use the {@link #MERGE_CUMULATOR}.
*/
public static final Cumulator COMPOSITE_CUMULATOR = new Cumulator() {
@Override
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
ByteBuf buffer;
try {
if (cumulation.refCnt() > 1) {
// Expand cumulation (by replace it) when the refCnt is greater then 1 which may happen when the
// user use slice().retain() or duplicate().retain().
//
// See:
// - https://github.com/netty/netty/issues/2327
// - https://github.com/netty/netty/issues/1764
buffer = expandCumulation(alloc, cumulation, in.readableBytes());
buffer.writeBytes(in);
public static final Cumulator COMPOSITE_CUMULATOR = (alloc, cumulation, in) -> {
ByteBuf buffer;
try {
if (cumulation.refCnt() > 1) {
// Expand cumulation (by replace it) when the refCnt is greater then 1 which may happen when the
// user use slice().retain() or duplicate().retain().
//
// See:
// - https://github.com/netty/netty/issues/2327
// - https://github.com/netty/netty/issues/1764
buffer = expandCumulation(alloc, cumulation, in.readableBytes());
buffer.writeBytes(in);
} else {
CompositeByteBuf composite;
if (cumulation instanceof CompositeByteBuf) {
composite = (CompositeByteBuf) cumulation;
} else {
CompositeByteBuf composite;
if (cumulation instanceof CompositeByteBuf) {
composite = (CompositeByteBuf) cumulation;
} else {
composite = alloc.compositeBuffer(Integer.MAX_VALUE);
composite.addComponent(true, cumulation);
}
composite.addComponent(true, in);
in = null;
buffer = composite;
}
return buffer;
} finally {
if (in != null) {
// We must release if the ownership was not transferred as otherwise it may produce a leak if
// writeBytes(...) throw for whatever release (for example because of OutOfMemoryError).
in.release();
composite = alloc.compositeBuffer(Integer.MAX_VALUE);
composite.addComponent(true, cumulation);
}
composite.addComponent(true, in);
in = null;
buffer = composite;
}
return buffer;
} finally {
if (in != null) {
// We must release if the ownership was not transferred as otherwise it may produce a leak if
// writeBytes(...) throw for whatever release (for example because of OutOfMemoryError).
in.release();
}
}
};

View File

@ -28,11 +28,8 @@ import static io.netty.util.internal.ObjectUtil.checkNotNull;
*/
final class CodecOutputList extends AbstractList<Object> implements RandomAccess {
private static final CodecOutputListRecycler NOOP_RECYCLER = new CodecOutputListRecycler() {
@Override
public void recycle(CodecOutputList object) {
// drop on the floor and let the GC handle it.
}
private static final CodecOutputListRecycler NOOP_RECYCLER = object -> {
// drop on the floor and let the GC handle it.
};
private static final FastThreadLocal<CodecOutputLists> CODEC_OUTPUT_LISTS_POOL =

View File

@ -64,12 +64,7 @@ public class DefaultHeaders<K, V, T extends Headers<K, V, T>> implements Headers
void validateName(K name);
@SuppressWarnings("rawtypes")
NameValidator NOT_NULL = new NameValidator() {
@Override
public void validateName(Object name) {
checkNotNull(name, "name");
}
};
NameValidator NOT_NULL = name -> checkNotNull(name, "name");
}
@SuppressWarnings("unchecked")

View File

@ -210,12 +210,9 @@ public abstract class MessageAggregator<I, S, C extends ByteBufHolder, O extends
// Cache the write listener for reuse.
ChannelFutureListener listener = continueResponseWriteListener;
if (listener == null) {
continueResponseWriteListener = listener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
}
continueResponseWriteListener = listener = future -> {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
}
};
}

View File

@ -42,12 +42,9 @@ abstract class ByteBufChecksum implements Checksum {
CRC32_UPDATE_METHOD = updateByteBuffer(new CRC32());
}
private final ByteProcessor updateProcessor = new ByteProcessor() {
@Override
public boolean process(byte value) throws Exception {
update(value);
return true;
}
private final ByteProcessor updateProcessor = value -> {
update(value);
return true;
};
private static Method updateByteBuffer(Checksum checksum) {

View File

@ -33,12 +33,7 @@ import static io.netty.handler.codec.compression.Bzip2Constants.*;
* 7. Huffman encode and write data - {@link #close(ByteBuf)} (through {@link Bzip2HuffmanStageEncoder})
*/
final class Bzip2BlockCompressor {
private final ByteProcessor writeProcessor = new ByteProcessor() {
@Override
public boolean process(byte value) throws Exception {
return write(value);
}
};
private final ByteProcessor writeProcessor = this::write;
/**
* A writer that provides bit-level writes.

View File

@ -184,12 +184,9 @@ public class Bzip2Encoder extends MessageToByteEncoder<ByteBuf> {
if (executor.inEventLoop()) {
return finishEncode(ctx, promise);
} else {
executor.execute(new Runnable() {
@Override
public void run() {
ChannelFuture f = finishEncode(ctx(), promise);
f.addListener(new ChannelPromiseNotifier(promise));
}
executor.execute(() -> {
ChannelFuture f = finishEncode(ctx(), promise);
f.addListener(new ChannelPromiseNotifier(promise));
});
return promise;
}
@ -198,20 +195,12 @@ public class Bzip2Encoder extends MessageToByteEncoder<ByteBuf> {
@Override
public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
ctx.close(promise);
}
});
f.addListener((ChannelFutureListener) f1 -> ctx.close(promise));
if (!f.isDone()) {
// Ensure the channel is closed even if the write operation completes in time.
ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
ctx.executor().schedule(() -> {
ctx.close(promise);
}, 10, TimeUnit.SECONDS); // FIXME: Magic number
}
}

View File

@ -252,12 +252,9 @@ public class JZlibEncoder extends ZlibEncoder {
return finishEncode(ctx, promise);
} else {
final ChannelPromise p = ctx.newPromise();
executor.execute(new Runnable() {
@Override
public void run() {
ChannelFuture f = finishEncode(ctx(), p);
f.addListener(new ChannelPromiseNotifier(promise));
}
executor.execute(() -> {
ChannelFuture f = finishEncode(ctx(), p);
f.addListener(new ChannelPromiseNotifier(promise));
});
return p;
}
@ -342,20 +339,12 @@ public class JZlibEncoder extends ZlibEncoder {
final ChannelHandlerContext ctx,
final ChannelPromise promise) {
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
ctx.close(promise);
}
});
f.addListener((ChannelFutureListener) f1 -> ctx.close(promise));
if (!f.isDone()) {
// Ensure the channel is closed even if the write operation completes in time.
ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
ctx.executor().schedule(() -> {
ctx.close(promise);
}, 10, TimeUnit.SECONDS); // FIXME: Magic number
}
}

View File

@ -163,12 +163,9 @@ public class JdkZlibEncoder extends ZlibEncoder {
return finishEncode(ctx, promise);
} else {
final ChannelPromise p = ctx.newPromise();
executor.execute(new Runnable() {
@Override
public void run() {
ChannelFuture f = finishEncode(ctx(), p);
f.addListener(new ChannelPromiseNotifier(promise));
}
executor.execute(() -> {
ChannelFuture f = finishEncode(ctx(), p);
f.addListener(new ChannelPromiseNotifier(promise));
});
return p;
}
@ -262,20 +259,12 @@ public class JdkZlibEncoder extends ZlibEncoder {
@Override
public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
ctx.close(promise);
}
});
f.addListener((ChannelFutureListener) f1 -> ctx.close(promise));
if (!f.isDone()) {
// Ensure the channel is closed even if the write operation completes in time.
ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
ctx.executor().schedule(() -> {
ctx.close(promise);
}, 10, TimeUnit.SECONDS); // FIXME: Magic number
}
}

View File

@ -364,12 +364,9 @@ public class Lz4FrameEncoder extends MessageToByteEncoder<ByteBuf> {
if (executor.inEventLoop()) {
return finishEncode(ctx, promise);
} else {
executor.execute(new Runnable() {
@Override
public void run() {
ChannelFuture f = finishEncode(ctx(), promise);
f.addListener(new ChannelPromiseNotifier(promise));
}
executor.execute(() -> {
ChannelFuture f = finishEncode(ctx(), promise);
f.addListener(new ChannelPromiseNotifier(promise));
});
return promise;
}
@ -378,20 +375,12 @@ public class Lz4FrameEncoder extends MessageToByteEncoder<ByteBuf> {
@Override
public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
ctx.close(promise);
}
});
f.addListener((ChannelFutureListener) f1 -> ctx.close(promise));
if (!f.isDone()) {
// Ensure the channel is closed even if the write operation completes in time.
ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
ctx.executor().schedule(() -> {
ctx.close(promise);
}, 10, TimeUnit.SECONDS); // FIXME: Magic number
}
}

View File

@ -270,24 +270,18 @@ public class Lz4FrameEncoderTest extends AbstractEncoderTest {
clientChannel = bs.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
final Channel finalClientChannel = clientChannel;
clientChannel.eventLoop().execute(new Runnable() {
@Override
public void run() {
finalClientChannel.close();
final int size = 27;
ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(size, size);
finalClientChannel.writeAndFlush(buf.writerIndex(buf.writerIndex() + size))
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
clientChannel.eventLoop().execute(() -> {
finalClientChannel.close();
final int size = 27;
ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(size, size);
finalClientChannel.writeAndFlush(buf.writerIndex(buf.writerIndex() + size))
.addListener((ChannelFutureListener) future -> {
try {
writeFailCauseRef.set(future.cause());
} finally {
latch.countDown();
}
}
});
}
});
});
latch.await();
Throwable writeFailCause = writeFailCauseRef.get();

View File

@ -29,20 +29,10 @@ public interface BooleanSupplier {
/**
* A supplier which always returns {@code false} and never throws.
*/
BooleanSupplier FALSE_SUPPLIER = new BooleanSupplier() {
@Override
public boolean get() {
return false;
}
};
BooleanSupplier FALSE_SUPPLIER = () -> false;
/**
* A supplier which always returns {@code true} and never throws.
*/
BooleanSupplier TRUE_SUPPLIER = new BooleanSupplier() {
@Override
public boolean get() {
return true;
}
};
BooleanSupplier TRUE_SUPPLIER = () -> true;
}

View File

@ -103,42 +103,22 @@ public interface ByteProcessor {
/**
* Aborts on a {@code CR ('\r')} or a {@code LF ('\n')}.
*/
ByteProcessor FIND_CRLF = new ByteProcessor() {
@Override
public boolean process(byte value) {
return value != CARRIAGE_RETURN && value != LINE_FEED;
}
};
ByteProcessor FIND_CRLF = value -> value != CARRIAGE_RETURN && value != LINE_FEED;
/**
* Aborts on a byte which is neither a {@code CR ('\r')} nor a {@code LF ('\n')}.
*/
ByteProcessor FIND_NON_CRLF = new ByteProcessor() {
@Override
public boolean process(byte value) {
return value == CARRIAGE_RETURN || value == LINE_FEED;
}
};
ByteProcessor FIND_NON_CRLF = value -> value == CARRIAGE_RETURN || value == LINE_FEED;
/**
* Aborts on a linear whitespace (a ({@code ' '} or a {@code '\t'}).
*/
ByteProcessor FIND_LINEAR_WHITESPACE = new ByteProcessor() {
@Override
public boolean process(byte value) {
return value != SPACE && value != HTAB;
}
};
ByteProcessor FIND_LINEAR_WHITESPACE = value -> value != SPACE && value != HTAB;
/**
* Aborts on a byte which is not a linear whitespace (neither {@code ' '} nor {@code '\t'}).
*/
ByteProcessor FIND_NON_LINEAR_WHITESPACE = new ByteProcessor() {
@Override
public boolean process(byte value) {
return value == SPACE || value == HTAB;
}
};
ByteProcessor FIND_NON_LINEAR_WHITESPACE = value -> value == SPACE || value == HTAB;
/**
* @return {@code true} if the processor wants to continue the loop and handle the next byte in the buffer.

View File

@ -250,59 +250,56 @@ public final class NetUtil {
// As a SecurityManager may prevent reading the somaxconn file we wrap this in a privileged block.
//
// See https://github.com/netty/netty/issues/3680
SOMAXCONN = AccessController.doPrivileged(new PrivilegedAction<Integer>() {
@Override
public Integer run() {
// Determine the default somaxconn (server socket backlog) value of the platform.
// The known defaults:
// - Windows NT Server 4.0+: 200
// - Linux and Mac OS X: 128
int somaxconn = PlatformDependent.isWindows() ? 200 : 128;
File file = new File("/proc/sys/net/core/somaxconn");
BufferedReader in = null;
try {
// file.exists() may throw a SecurityException if a SecurityManager is used, so execute it in the
// try / catch block.
// See https://github.com/netty/netty/issues/4936
if (file.exists()) {
in = new BufferedReader(new FileReader(file));
somaxconn = Integer.parseInt(in.readLine());
if (logger.isDebugEnabled()) {
logger.debug("{}: {}", file, somaxconn);
}
} else {
// Try to get from sysctl
Integer tmp = null;
if (SystemPropertyUtil.getBoolean("io.netty.net.somaxconn.trySysctl", false)) {
tmp = sysctlGetInt("kern.ipc.somaxconn");
if (tmp == null) {
tmp = sysctlGetInt("kern.ipc.soacceptqueue");
if (tmp != null) {
somaxconn = tmp;
}
} else {
SOMAXCONN = AccessController.doPrivileged((PrivilegedAction<Integer>) () -> {
// Determine the default somaxconn (server socket backlog) value of the platform.
// The known defaults:
// - Windows NT Server 4.0+: 200
// - Linux and Mac OS X: 128
int somaxconn = PlatformDependent.isWindows() ? 200 : 128;
File file = new File("/proc/sys/net/core/somaxconn");
BufferedReader in = null;
try {
// file.exists() may throw a SecurityException if a SecurityManager is used, so execute it in the
// try / catch block.
// See https://github.com/netty/netty/issues/4936
if (file.exists()) {
in = new BufferedReader(new FileReader(file));
somaxconn = Integer.parseInt(in.readLine());
if (logger.isDebugEnabled()) {
logger.debug("{}: {}", file, somaxconn);
}
} else {
// Try to get from sysctl
Integer tmp = null;
if (SystemPropertyUtil.getBoolean("io.netty.net.somaxconn.trySysctl", false)) {
tmp = sysctlGetInt("kern.ipc.somaxconn");
if (tmp == null) {
tmp = sysctlGetInt("kern.ipc.soacceptqueue");
if (tmp != null) {
somaxconn = tmp;
}
}
if (tmp == null) {
logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file,
somaxconn);
} else {
somaxconn = tmp;
}
}
} catch (Exception e) {
logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, somaxconn, e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Ignored.
}
if (tmp == null) {
logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file,
somaxconn);
}
}
} catch (Exception e) {
logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file, somaxconn, e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Ignored.
}
}
return somaxconn;
}
return somaxconn;
});
}

View File

@ -41,11 +41,8 @@ public abstract class Recycler<T> {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class);
@SuppressWarnings("rawtypes")
private static final Handle NOOP_HANDLE = new Handle() {
@Override
public void recycle(Object object) {
// NOOP
}
private static final Handle NOOP_HANDLE = object -> {
// NOOP
};
private static final AtomicInteger ID_GENERATOR = new AtomicInteger(Integer.MIN_VALUE);
private static final int OWN_THREAD_ID = ID_GENERATOR.getAndIncrement();

View File

@ -103,12 +103,8 @@ public abstract class ResourceLeakDetectorFactory {
DefaultResourceLeakDetectorFactory() {
String customLeakDetector;
try {
customLeakDetector = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return SystemPropertyUtil.get("io.netty.customResourceLeakDetector");
}
});
customLeakDetector = AccessController.doPrivileged((PrivilegedAction<String>) () ->
SystemPropertyUtil.get("io.netty.customResourceLeakDetector"));
} catch (Throwable cause) {
logger.error("Could not access System property: io.netty.customResourceLeakDetector", cause);
customLeakDetector = null;

View File

@ -114,12 +114,9 @@ public final class ThreadDeathWatcher {
// See:
// - https://github.com/netty/netty/issues/7290
// - https://bugs.openjdk.java.net/browse/JDK-7008595
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
watcherThread.setContextClassLoader(null);
return null;
}
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
watcherThread.setContextClassLoader(null);
return null;
});
watcherThread.start();

View File

@ -29,20 +29,10 @@ public interface UncheckedBooleanSupplier extends BooleanSupplier {
/**
* A supplier which always returns {@code false} and never throws.
*/
UncheckedBooleanSupplier FALSE_SUPPLIER = new UncheckedBooleanSupplier() {
@Override
public boolean get() {
return false;
}
};
UncheckedBooleanSupplier FALSE_SUPPLIER = () -> false;
/**
* A supplier which always returns {@code true} and never throws.
*/
UncheckedBooleanSupplier TRUE_SUPPLIER = new UncheckedBooleanSupplier() {
@Override
public boolean get() {
return true;
}
};
UncheckedBooleanSupplier TRUE_SUPPLIER = () -> true;
}

View File

@ -36,12 +36,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut
static final long START_TIME = System.nanoTime();
private static final Comparator<RunnableScheduledFutureNode<?>> SCHEDULED_FUTURE_TASK_COMPARATOR =
new Comparator<RunnableScheduledFutureNode<?>>() {
@Override
public int compare(RunnableScheduledFutureNode<?> o1, RunnableScheduledFutureNode<?> o2) {
return o1.compareTo(o2);
}
};
Comparable::compareTo;
private PriorityQueue<RunnableScheduledFutureNode<?>> scheduledTaskQueue;
@ -234,12 +229,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut
if (inEventLoop()) {
add0(task);
} else {
execute(new Runnable() {
@Override
public void run() {
add0(task);
}
});
execute(() -> add0(task));
}
return task;
}
@ -258,12 +248,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut
if (inEventLoop()) {
scheduledTaskQueue().removeTyped(task);
} else {
execute(new Runnable() {
@Override
public void run() {
removeScheduled(task);
}
});
execute(() -> removeScheduled(task));
}
}

View File

@ -429,12 +429,7 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
}
}
safeExecute(executor, new Runnable() {
@Override
public void run() {
notifyListenersNow();
}
});
safeExecute(executor, this::notifyListenersNow);
}
/**
@ -459,12 +454,7 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
}
}
safeExecute(executor, new Runnable() {
@Override
public void run() {
notifyListener0(future, listener);
}
});
safeExecute(executor, () -> notifyListener0(future, listener));
}
private void notifyListenersNow() {
@ -662,21 +652,11 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
if (listeners instanceof GenericProgressiveFutureListener[]) {
final GenericProgressiveFutureListener<?>[] array =
(GenericProgressiveFutureListener<?>[]) listeners;
safeExecute(executor, new Runnable() {
@Override
public void run() {
notifyProgressiveListeners0(self, array, progress, total);
}
});
safeExecute(executor, () -> notifyProgressiveListeners0(self, array, progress, total));
} else {
final GenericProgressiveFutureListener<ProgressiveFuture<V>> l =
(GenericProgressiveFutureListener<ProgressiveFuture<V>>) listeners;
safeExecute(executor, new Runnable() {
@Override
public void run() {
notifyProgressiveListener0(self, l, progress, total);
}
});
safeExecute(executor, () -> notifyProgressiveListener0(self, l, progress, total));
}
}
}

View File

@ -46,12 +46,9 @@ public final class GlobalEventExecutor extends AbstractScheduledEventExecutor {
static {
INSTANCE = new GlobalEventExecutor();
QUIET_PERIOD_TASK = new RunnableScheduledFutureAdapter<>(
INSTANCE, INSTANCE.newPromise(), Executors.callable(new Runnable() {
@Override
public void run() {
// NOOP
}
}, null), deadlineNanos(SCHEDULE_QUIET_PERIOD_INTERVAL), -SCHEDULE_QUIET_PERIOD_INTERVAL);
INSTANCE, INSTANCE.newPromise(), Executors.callable(() -> {
// NOOP
}, null), deadlineNanos(SCHEDULE_QUIET_PERIOD_INTERVAL), -SCHEDULE_QUIET_PERIOD_INTERVAL);
INSTANCE.scheduledTaskQueue().add(QUIET_PERIOD_TASK);
}
@ -228,12 +225,9 @@ public final class GlobalEventExecutor extends AbstractScheduledEventExecutor {
// See:
// - https://github.com/netty/netty/issues/7290
// - https://bugs.openjdk.java.net/browse/JDK-7008595
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
t.setContextClassLoader(null);
return null;
}
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
t.setContextClassLoader(null);
return null;
});
// Set the thread before starting it as otherwise inEventLoop() may return false and so produce

View File

@ -154,12 +154,9 @@ public class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup {
}
}
final FutureListener<Object> terminationListener = new FutureListener<Object>() {
@Override
public void operationComplete(Future<Object> future) throws Exception {
if (terminatedChildren.incrementAndGet() == children.length) {
terminationFuture.setSuccess(null);
}
final FutureListener<Object> terminationListener = future -> {
if (terminatedChildren.incrementAndGet() == children.length) {
terminationFuture.setSuccess(null);
}
};

View File

@ -25,11 +25,8 @@ import java.util.concurrent.locks.LockSupport;
* Expose helper methods which create different {@link RejectedExecutionHandler}s.
*/
public final class RejectedExecutionHandlers {
private static final RejectedExecutionHandler REJECT = new RejectedExecutionHandler() {
@Override
public void rejected(Runnable task, SingleThreadEventExecutor executor) {
throw new RejectedExecutionException();
}
private static final RejectedExecutionHandler REJECT = (task, executor) -> {
throw new RejectedExecutionException();
};
private RejectedExecutionHandlers() { }
@ -49,24 +46,21 @@ public final class RejectedExecutionHandlers {
public static RejectedExecutionHandler backoff(final int retries, long backoffAmount, TimeUnit unit) {
ObjectUtil.checkPositive(retries, "retries");
final long backOffNanos = unit.toNanos(backoffAmount);
return new RejectedExecutionHandler() {
@Override
public void rejected(Runnable task, SingleThreadEventExecutor executor) {
if (!executor.inEventLoop()) {
for (int i = 0; i < retries; i++) {
// Try to wake up the executor so it will empty its task queue.
executor.wakeup(false);
return (task, executor) -> {
if (!executor.inEventLoop()) {
for (int i = 0; i < retries; i++) {
// Try to wake up the executor so it will empty its task queue.
executor.wakeup(false);
LockSupport.parkNanos(backOffNanos);
if (executor.offerTask(task)) {
return;
}
LockSupport.parkNanos(backOffNanos);
if (executor.offerTask(task)) {
return;
}
}
// Either we tried to add the task from within the EventLoop or we was not able to add it even with
// backoff.
throw new RejectedExecutionException();
}
// Either we tried to add the task from within the EventLoop or we was not able to add it even with
// backoff.
throw new RejectedExecutionException();
};
}
}

View File

@ -59,17 +59,11 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
private static final int ST_SHUTDOWN = 4;
private static final int ST_TERMINATED = 5;
private static final Runnable WAKEUP_TASK = new Runnable() {
@Override
public void run() {
// Do nothing.
}
private static final Runnable WAKEUP_TASK = () -> {
// Do nothing.
};
private static final Runnable NOOP_TASK = new Runnable() {
@Override
public void run() {
// Do nothing.
}
private static final Runnable NOOP_TASK = () -> {
// Do nothing.
};
private static final AtomicIntegerFieldUpdater<SingleThreadEventExecutor> STATE_UPDATER =
@ -467,12 +461,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
if (inEventLoop()) {
shutdownHooks.add(task);
} else {
execute(new Runnable() {
@Override
public void run() {
shutdownHooks.add(task);
}
});
execute(() -> shutdownHooks.add(task));
}
}
@ -483,12 +472,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
if (inEventLoop()) {
shutdownHooks.remove(task);
} else {
execute(new Runnable() {
@Override
public void run() {
shutdownHooks.remove(task);
}
});
execute(() -> shutdownHooks.remove(task));
}
}
@ -854,66 +838,63 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
private void doStartThread() {
assert thread == null;
executor.execute(new Runnable() {
@Override
public void run() {
thread = Thread.currentThread();
if (interrupted) {
thread.interrupt();
executor.execute(() -> {
thread = Thread.currentThread();
if (interrupted) {
thread.interrupt();
}
boolean success = false;
updateLastExecutionTime();
try {
SingleThreadEventExecutor.this.run();
success = true;
} catch (Throwable t) {
logger.warn("Unexpected exception from an event executor: ", t);
} finally {
for (;;) {
int oldState = state;
if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet(
SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) {
break;
}
}
// Check if confirmShutdown() was called at the end of the loop.
if (success && gracefulShutdownStartTime == 0) {
if (logger.isErrorEnabled()) {
logger.error("Buggy " + EventExecutor.class.getSimpleName() + " implementation; " +
SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must " +
"be called before run() implementation terminates.");
}
}
boolean success = false;
updateLastExecutionTime();
try {
SingleThreadEventExecutor.this.run();
success = true;
} catch (Throwable t) {
logger.warn("Unexpected exception from an event executor: ", t);
} finally {
// Run all remaining tasks and shutdown hooks.
for (;;) {
int oldState = state;
if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet(
SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) {
if (confirmShutdown()) {
break;
}
}
// Check if confirmShutdown() was called at the end of the loop.
if (success && gracefulShutdownStartTime == 0) {
if (logger.isErrorEnabled()) {
logger.error("Buggy " + EventExecutor.class.getSimpleName() + " implementation; " +
SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must " +
"be called before run() implementation terminates.");
}
}
} finally {
try {
// Run all remaining tasks and shutdown hooks.
for (;;) {
if (confirmShutdown()) {
break;
}
}
cleanup();
} finally {
try {
cleanup();
} finally {
// Lets remove all FastThreadLocals for the Thread as we are about to terminate and notify
// the future. The user may block on the future and once it unblocks the JVM may terminate
// and start unloading classes.
// See https://github.com/netty/netty/issues/6596.
FastThreadLocal.removeAll();
// Lets remove all FastThreadLocals for the Thread as we are about to terminate and notify
// the future. The user may block on the future and once it unblocks the JVM may terminate
// and start unloading classes.
// See https://github.com/netty/netty/issues/6596.
FastThreadLocal.removeAll();
STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED);
threadLock.release();
if (!taskQueue.isEmpty()) {
if (logger.isWarnEnabled()) {
logger.warn("An event executor terminated with " +
"non-empty task queue (" + taskQueue.size() + ')');
}
STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED);
threadLock.release();
if (!taskQueue.isEmpty()) {
if (logger.isWarnEnabled()) {
logger.warn("An event executor terminated with " +
"non-empty task queue (" + taskQueue.size() + ')');
}
terminationFuture.setSuccess(null);
}
terminationFuture.setSuccess(null);
}
}
}

View File

@ -45,20 +45,17 @@ final class CleanerJava6 implements Cleaner {
Throwable error = null;
final ByteBuffer direct = ByteBuffer.allocateDirect(1);
try {
Object mayBeCleanerField = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Field cleanerField = direct.getClass().getDeclaredField("cleaner");
if (!PlatformDependent.hasUnsafe()) {
// We need to make it accessible if we do not use Unsafe as we will access it via
// reflection.
cleanerField.setAccessible(true);
}
return cleanerField;
} catch (Throwable cause) {
return cause;
Object mayBeCleanerField = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
Field cleanerField1 = direct.getClass().getDeclaredField("cleaner");
if (!PlatformDependent.hasUnsafe()) {
// We need to make it accessible if we do not use Unsafe as we will access it via
// reflection.
cleanerField1.setAccessible(true);
}
return cleanerField1;
} catch (Throwable cause) {
return cause;
}
});
if (mayBeCleanerField instanceof Throwable) {
@ -119,15 +116,12 @@ final class CleanerJava6 implements Cleaner {
}
private static void freeDirectBufferPrivileged(final ByteBuffer buffer) {
Throwable cause = AccessController.doPrivileged(new PrivilegedAction<Throwable>() {
@Override
public Throwable run() {
try {
freeDirectBuffer0(buffer);
return null;
} catch (Throwable cause) {
return cause;
}
Throwable cause = AccessController.doPrivileged((PrivilegedAction<Throwable>) () -> {
try {
freeDirectBuffer0(buffer);
return null;
} catch (Throwable cause1) {
return cause1;
}
});
if (cause != null) {

View File

@ -37,18 +37,15 @@ final class CleanerJava9 implements Cleaner {
final Throwable error;
if (PlatformDependent0.hasUnsafe()) {
final ByteBuffer buffer = ByteBuffer.allocateDirect(1);
Object maybeInvokeMethod = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// See https://bugs.openjdk.java.net/browse/JDK-8171377
Method m = PlatformDependent0.UNSAFE.getClass().getDeclaredMethod(
"invokeCleaner", ByteBuffer.class);
m.invoke(PlatformDependent0.UNSAFE, buffer);
return m;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
return e;
}
Object maybeInvokeMethod = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
// See https://bugs.openjdk.java.net/browse/JDK-8171377
Method m = PlatformDependent0.UNSAFE.getClass().getDeclaredMethod(
"invokeCleaner", ByteBuffer.class);
m.invoke(PlatformDependent0.UNSAFE, buffer);
return m;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
return e;
}
});
@ -91,16 +88,13 @@ final class CleanerJava9 implements Cleaner {
}
private static void freeDirectBufferPrivileged(final ByteBuffer buffer) {
Exception error = AccessController.doPrivileged(new PrivilegedAction<Exception>() {
@Override
public Exception run() {
try {
INVOKE_CLEANER.invoke(PlatformDependent0.UNSAFE, buffer);
} catch (InvocationTargetException | IllegalAccessException e) {
return e;
}
return null;
Exception error = AccessController.doPrivileged((PrivilegedAction<Exception>) () -> {
try {
INVOKE_CLEANER.invoke(PlatformDependent0.UNSAFE, buffer);
} catch (InvocationTargetException | IllegalAccessException e) {
return e;
}
return null;
});
if (error != null) {
PlatformDependent0.throwException(error);

View File

@ -322,18 +322,15 @@ public final class NativeLibraryLoader {
private static void loadLibraryByHelper(final Class<?> helper, final String name, final boolean absolute)
throws UnsatisfiedLinkError {
Object ret = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// Invoke the helper to load the native library, if succeed, then the native
// library belong to the specified ClassLoader.
Method method = helper.getMethod("loadLibrary", String.class, boolean.class);
method.setAccessible(true);
return method.invoke(null, name, absolute);
} catch (Exception e) {
return e;
}
Object ret = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
// Invoke the helper to load the native library, if succeed, then the native
// library belong to the specified ClassLoader.
Method method = helper.getMethod("loadLibrary", String.class, boolean.class);
method.setAccessible(true);
return method.invoke(null, name, absolute);
} catch (Exception e) {
return e;
}
});
if (ret instanceof Throwable) {
@ -368,20 +365,17 @@ public final class NativeLibraryLoader {
try {
// The helper class is NOT found in target ClassLoader, we have to define the helper class.
final byte[] classBinary = classToByteArray(helper);
return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
// Define the helper class in the target ClassLoader,
// then we can call the helper to load the native library.
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class);
defineClass.setAccessible(true);
return (Class<?>) defineClass.invoke(loader, helper.getName(), classBinary, 0,
classBinary.length);
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
return AccessController.doPrivileged((PrivilegedAction<Class<?>>) () -> {
try {
// Define the helper class in the target ClassLoader,
// then we can call the helper to load the native library.
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class);
defineClass.setAccessible(true);
return (Class<?>) defineClass.invoke(loader, helper.getName(), classBinary, 0,
classBinary.length);
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
});
} catch (ClassNotFoundException | Error | RuntimeException e2) {

View File

@ -42,47 +42,44 @@ public final class ObjectCleaner {
private static final Set<AutomaticCleanerReference> LIVE_SET = ConcurrentHashMap.newKeySet();
private static final ReferenceQueue<Object> REFERENCE_QUEUE = new ReferenceQueue<>();
private static final AtomicBoolean CLEANER_RUNNING = new AtomicBoolean(false);
private static final Runnable CLEANER_TASK = new Runnable() {
@Override
public void run() {
boolean interrupted = false;
for (;;) {
// Keep on processing as long as the LIVE_SET is not empty and once it becomes empty
// See if we can let this thread complete.
while (!LIVE_SET.isEmpty()) {
final AutomaticCleanerReference reference;
private static final Runnable CLEANER_TASK = () -> {
boolean interrupted = false;
for (;;) {
// Keep on processing as long as the LIVE_SET is not empty and once it becomes empty
// See if we can let this thread complete.
while (!LIVE_SET.isEmpty()) {
final AutomaticCleanerReference reference;
try {
reference = (AutomaticCleanerReference) REFERENCE_QUEUE.remove(REFERENCE_QUEUE_POLL_TIMEOUT_MS);
} catch (InterruptedException ex) {
// Just consume and move on
interrupted = true;
continue;
}
if (reference != null) {
try {
reference = (AutomaticCleanerReference) REFERENCE_QUEUE.remove(REFERENCE_QUEUE_POLL_TIMEOUT_MS);
} catch (InterruptedException ex) {
// Just consume and move on
interrupted = true;
continue;
}
if (reference != null) {
try {
reference.cleanup();
} catch (Throwable ignored) {
// ignore exceptions, and don't log in case the logger throws an exception, blocks, or has
// other unexpected side effects.
}
LIVE_SET.remove(reference);
reference.cleanup();
} catch (Throwable ignored) {
// ignore exceptions, and don't log in case the logger throws an exception, blocks, or has
// other unexpected side effects.
}
LIVE_SET.remove(reference);
}
CLEANER_RUNNING.set(false);
}
CLEANER_RUNNING.set(false);
// Its important to first access the LIVE_SET and then CLEANER_RUNNING to ensure correct
// behavior in multi-threaded environments.
if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) {
// There was nothing added after we set STARTED to false or some other cleanup Thread
// was started already so its safe to let this Thread complete now.
break;
}
}
if (interrupted) {
// As we caught the InterruptedException above we should mark the Thread as interrupted.
Thread.currentThread().interrupt();
// Its important to first access the LIVE_SET and then CLEANER_RUNNING to ensure correct
// behavior in multi-threaded environments.
if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) {
// There was nothing added after we set STARTED to false or some other cleanup Thread
// was started already so its safe to let this Thread complete now.
break;
}
}
if (interrupted) {
// As we caught the InterruptedException above we should mark the Thread as interrupted.
Thread.currentThread().interrupt();
}
};
/**
@ -108,12 +105,9 @@ public final class ObjectCleaner {
// See:
// - https://github.com/netty/netty/issues/7290
// - https://bugs.openjdk.java.net/browse/JDK-7008595
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
cleanupThread.setContextClassLoader(null);
return null;
}
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
cleanupThread.setContextClassLoader(null);
return null;
});
cleanupThread.setName(CLEANER_THREAD_NAME);

View File

@ -99,11 +99,8 @@ public final class PlatformDependent {
public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
private static final Cleaner NOOP = new Cleaner() {
@Override
public void freeDirectBuffer(ByteBuffer buffer) {
// NOOP
}
private static final Cleaner NOOP = buffer -> {
// NOOP
};
static {
@ -775,12 +772,9 @@ public final class PlatformDependent {
// jctools goes through its own process of initializing unsafe; of
// course, this requires permissions which might not be granted to calling code, so we
// must mark this block as privileged too
unsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
// force JCTools to initialize unsafe
return UnsafeAccess.UNSAFE;
}
unsafe = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
// force JCTools to initialize unsafe
return UnsafeAccess.UNSAFE;
});
}

View File

@ -80,25 +80,22 @@ final class PlatformDependent0 {
direct = ByteBuffer.allocateDirect(1);
// attempt to access field Unsafe#theUnsafe
final Object maybeUnsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
// We always want to try using Unsafe as the access still works on java9 as well and
// we need it for out native-transports and many optimizations.
Throwable cause = ReflectionUtil.trySetAccessible(unsafeField, false);
if (cause != null) {
return cause;
}
// the unsafe instance
return unsafeField.get(null);
} catch (NoSuchFieldException | SecurityException
| IllegalAccessException | NoClassDefFoundError e) {
return e;
} // Also catch NoClassDefFoundError in case someone uses for example OSGI and it made
// Unsafe unloadable.
}
final Object maybeUnsafe = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
// We always want to try using Unsafe as the access still works on java9 as well and
// we need it for out native-transports and many optimizations.
Throwable cause = ReflectionUtil.trySetAccessible(unsafeField, false);
if (cause != null) {
return cause;
}
// the unsafe instance
return unsafeField.get(null);
} catch (NoSuchFieldException | SecurityException
| IllegalAccessException | NoClassDefFoundError e) {
return e;
} // Also catch NoClassDefFoundError in case someone uses for example OSGI and it made
// Unsafe unloadable.
});
// the conditional check here can not be replaced with checking that maybeUnsafe
@ -119,16 +116,13 @@ final class PlatformDependent0 {
// http://www.mail-archive.com/jdk6-dev@openjdk.java.net/msg00698.html
if (unsafe != null) {
final Unsafe finalUnsafe = unsafe;
final Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
finalUnsafe.getClass().getDeclaredMethod(
"copyMemory", Object.class, long.class, Object.class, long.class, long.class);
return null;
} catch (NoSuchMethodException | SecurityException e) {
return e;
}
final Object maybeException = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
finalUnsafe.getClass().getDeclaredMethod(
"copyMemory", Object.class, long.class, Object.class, long.class, long.class);
return null;
} catch (NoSuchMethodException | SecurityException e) {
return e;
}
});
@ -146,24 +140,21 @@ final class PlatformDependent0 {
final Unsafe finalUnsafe = unsafe;
// attempt to access field Buffer#address
final Object maybeAddressField = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
final Field field = Buffer.class.getDeclaredField("address");
// Use Unsafe to read value of the address field. This way it will not fail on JDK9+ which
// will forbid changing the access level via reflection.
final long offset = finalUnsafe.objectFieldOffset(field);
final long address = finalUnsafe.getLong(direct, offset);
final Object maybeAddressField = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
final Field field = Buffer.class.getDeclaredField("address");
// Use Unsafe to read value of the address field. This way it will not fail on JDK9+ which
// will forbid changing the access level via reflection.
final long offset = finalUnsafe.objectFieldOffset(field);
final long address = finalUnsafe.getLong(direct, offset);
// if direct really is a direct buffer, address will be non-zero
if (address == 0) {
return null;
}
return field;
} catch (NoSuchFieldException | SecurityException e) {
return e;
// if direct really is a direct buffer, address will be non-zero
if (address == 0) {
return null;
}
return field;
} catch (NoSuchFieldException | SecurityException e) {
return e;
}
});
@ -205,20 +196,17 @@ final class PlatformDependent0 {
long address = -1;
try {
final Object maybeDirectBufferConstructor =
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
final Constructor<?> constructor =
direct.getClass().getDeclaredConstructor(long.class, int.class);
Throwable cause = ReflectionUtil.trySetAccessible(constructor, true);
if (cause != null) {
return cause;
}
return constructor;
} catch (NoSuchMethodException | SecurityException e) {
return e;
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
final Constructor<?> constructor =
direct.getClass().getDeclaredConstructor(long.class, int.class);
Throwable cause = ReflectionUtil.trySetAccessible(constructor, true);
if (cause != null) {
return cause;
}
return constructor;
} catch (NoSuchMethodException | SecurityException e) {
return e;
}
});
@ -299,33 +287,27 @@ final class PlatformDependent0 {
UNALIGNED = unaligned;
if (javaVersion() >= 9) {
Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// Java9 has jdk.internal.misc.Unsafe and not all methods are propagated to
// sun.misc.Unsafe
Class<?> internalUnsafeClass = getClassLoader(PlatformDependent0.class)
.loadClass("jdk.internal.misc.Unsafe");
Method method = internalUnsafeClass.getDeclaredMethod("getUnsafe");
return method.invoke(null);
} catch (Throwable e) {
return e;
}
Object maybeException = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
// Java9 has jdk.internal.misc.Unsafe and not all methods are propagated to
// sun.misc.Unsafe
Class<?> internalUnsafeClass = getClassLoader(PlatformDependent0.class)
.loadClass("jdk.internal.misc.Unsafe");
Method method = internalUnsafeClass.getDeclaredMethod("getUnsafe");
return method.invoke(null);
} catch (Throwable e) {
return e;
}
});
if (!(maybeException instanceof Throwable)) {
internalUnsafe = maybeException;
final Object finalInternalUnsafe = internalUnsafe;
maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
return finalInternalUnsafe.getClass().getDeclaredMethod(
"allocateUninitializedArray", Class.class, int.class);
} catch (NoSuchMethodException | SecurityException e) {
return e;
}
maybeException = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
return finalInternalUnsafe.getClass().getDeclaredMethod(
"allocateUninitializedArray", Class.class, int.class);
} catch (NoSuchMethodException | SecurityException e) {
return e;
}
});
@ -746,12 +728,7 @@ final class PlatformDependent0 {
if (System.getSecurityManager() == null) {
return clazz.getClassLoader();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
});
return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) clazz::getClassLoader);
}
}
@ -759,12 +736,8 @@ final class PlatformDependent0 {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () ->
Thread.currentThread().getContextClassLoader());
}
}
@ -772,12 +745,7 @@ final class PlatformDependent0 {
if (System.getSecurityManager() == null) {
return ClassLoader.getSystemClassLoader();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return ClassLoader.getSystemClassLoader();
}
});
return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) ClassLoader::getSystemClassLoader);
}
}

View File

@ -48,12 +48,9 @@ public final class SocketUtils {
public static void connect(final Socket socket, final SocketAddress remoteAddress, final int timeout)
throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socket.connect(remoteAddress, timeout);
return null;
}
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
socket.connect(remoteAddress, timeout);
return null;
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
@ -62,12 +59,9 @@ public final class SocketUtils {
public static void bind(final Socket socket, final SocketAddress bindpoint) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socket.bind(bindpoint);
return null;
}
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
socket.bind(bindpoint);
return null;
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
@ -77,12 +71,8 @@ public final class SocketUtils {
public static boolean connect(final SocketChannel socketChannel, final SocketAddress remoteAddress)
throws IOException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
@Override
public Boolean run() throws IOException {
return socketChannel.connect(remoteAddress);
}
});
return AccessController.doPrivileged((PrivilegedExceptionAction<Boolean>) () ->
socketChannel.connect(remoteAddress));
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
@ -90,12 +80,9 @@ public final class SocketUtils {
public static void bind(final SocketChannel socketChannel, final SocketAddress address) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socketChannel.bind(address);
return null;
}
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
socketChannel.bind(address);
return null;
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
@ -104,12 +91,8 @@ public final class SocketUtils {
public static SocketChannel accept(final ServerSocketChannel serverSocketChannel) throws IOException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<SocketChannel>() {
@Override
public SocketChannel run() throws IOException {
return serverSocketChannel.accept();
}
});
return AccessController.doPrivileged(
(PrivilegedExceptionAction<SocketChannel>) serverSocketChannel::accept);
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
@ -117,12 +100,9 @@ public final class SocketUtils {
public static void bind(final DatagramChannel networkChannel, final SocketAddress address) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
networkChannel.bind(address);
return null;
}
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
networkChannel.bind(address);
return null;
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
@ -130,22 +110,13 @@ public final class SocketUtils {
}
public static SocketAddress localSocketAddress(final ServerSocket socket) {
return AccessController.doPrivileged(new PrivilegedAction<SocketAddress>() {
@Override
public SocketAddress run() {
return socket.getLocalSocketAddress();
}
});
return AccessController.doPrivileged((PrivilegedAction<SocketAddress>) socket::getLocalSocketAddress);
}
public static InetAddress addressByName(final String hostname) throws UnknownHostException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress>() {
@Override
public InetAddress run() throws UnknownHostException {
return InetAddress.getByName(hostname);
}
});
return AccessController.doPrivileged((PrivilegedExceptionAction<InetAddress>) () ->
InetAddress.getByName(hostname));
} catch (PrivilegedActionException e) {
throw (UnknownHostException) e.getCause();
}
@ -153,52 +124,29 @@ public final class SocketUtils {
public static InetAddress[] allAddressesByName(final String hostname) throws UnknownHostException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress[]>() {
@Override
public InetAddress[] run() throws UnknownHostException {
return InetAddress.getAllByName(hostname);
}
});
return AccessController.doPrivileged((PrivilegedExceptionAction<InetAddress[]>) () ->
InetAddress.getAllByName(hostname));
} catch (PrivilegedActionException e) {
throw (UnknownHostException) e.getCause();
}
}
public static InetSocketAddress socketAddress(final String hostname, final int port) {
return AccessController.doPrivileged(new PrivilegedAction<InetSocketAddress>() {
@Override
public InetSocketAddress run() {
return new InetSocketAddress(hostname, port);
}
});
return AccessController.doPrivileged((PrivilegedAction<InetSocketAddress>) () ->
new InetSocketAddress(hostname, port));
}
public static Enumeration<InetAddress> addressesFromNetworkInterface(final NetworkInterface intf) {
return AccessController.doPrivileged(new PrivilegedAction<Enumeration<InetAddress>>() {
@Override
public Enumeration<InetAddress> run() {
return intf.getInetAddresses();
}
});
return AccessController.doPrivileged((PrivilegedAction<Enumeration<InetAddress>>) intf::getInetAddresses);
}
public static InetAddress loopbackAddress() {
return AccessController.doPrivileged(new PrivilegedAction<InetAddress>() {
@Override
public InetAddress run() {
return InetAddress.getLoopbackAddress();
}
});
return AccessController.doPrivileged((PrivilegedAction<InetAddress>) InetAddress::getLoopbackAddress);
}
public static byte[] hardwareAddressFromNetworkInterface(final NetworkInterface intf) throws SocketException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() {
@Override
public byte[] run() throws SocketException {
return intf.getHardwareAddress();
}
});
return AccessController.doPrivileged((PrivilegedExceptionAction<byte[]>) intf::getHardwareAddress);
} catch (PrivilegedActionException e) {
throw (SocketException) e.getCause();
}

View File

@ -68,12 +68,7 @@ public final class SystemPropertyUtil {
if (System.getSecurityManager() == null) {
value = System.getProperty(key);
} else {
value = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(key);
}
});
value = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key));
}
} catch (SecurityException e) {
logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e);

View File

@ -35,19 +35,16 @@ class Log4J2Logger extends ExtendedLoggerWrapper implements InternalLogger {
// Older Log4J2 versions have only log methods that takes the format + varargs. So we should not use
// Log4J2 if the version is too old.
// See https://github.com/netty/netty/issues/8217
VARARGS_ONLY = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
try {
Logger.class.getMethod("debug", String.class, Object.class);
return false;
} catch (NoSuchMethodException ignore) {
// Log4J2 version too old.
return true;
} catch (SecurityException ignore) {
// We could not detect the version so we will use Log4J2 if its on the classpath.
return false;
}
VARARGS_ONLY = AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
try {
Logger.class.getMethod("debug", String.class, Object.class);
return false;
} catch (NoSuchMethodException ignore) {
// Log4J2 version too old.
return true;
} catch (SecurityException ignore) {
// We could not detect the version so we will use Log4J2 if its on the classpath.
return false;
}
});
}

View File

@ -98,19 +98,16 @@ public class AbstractReferenceCountedTest {
for (int a = 0; a < threads; a++) {
final int retainCnt = ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE);
futures.add(service.submit(new Runnable() {
@Override
public void run() {
futures.add(service.submit(() -> {
try {
retainLatch.await();
try {
retainLatch.await();
try {
referenceCounted.retain(retainCnt);
} catch (IllegalReferenceCountException e) {
refCountExceptions.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
referenceCounted.retain(retainCnt);
} catch (IllegalReferenceCountException e) {
refCountExceptions.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
@ -147,21 +144,18 @@ public class AbstractReferenceCountedTest {
for (int a = 0; a < threads; a++) {
final AtomicInteger releaseCnt = new AtomicInteger(0);
futures.add(service.submit(new Runnable() {
@Override
public void run() {
futures.add(service.submit(() -> {
try {
releaseLatch.await();
try {
releaseLatch.await();
try {
if (referenceCounted.release(releaseCnt.incrementAndGet())) {
releasedCount.incrementAndGet();
}
} catch (IllegalReferenceCountException e) {
refCountExceptions.incrementAndGet();
if (referenceCounted.release(releaseCnt.incrementAndGet())) {
releasedCount.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IllegalReferenceCountException e) {
refCountExceptions.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}

View File

@ -79,12 +79,7 @@ public class ConstantPoolTest {
assertThat(array.length, is(5));
// Sort by name
Arrays.sort(array, new Comparator<TestConstant>() {
@Override
public int compare(TestConstant o1, TestConstant o2) {
return o1.name().compareTo(o2.name());
}
});
Arrays.sort(array, (o1, o2) -> o1.name().compareTo(o2.name()));
assertThat(array[0], is(sameInstance(a)));
assertThat(array[1], is(sameInstance(b)));

View File

@ -35,12 +35,9 @@ public class HashedWheelTimerTest {
public void testScheduleTimeoutShouldNotRunBeforeDelay() throws InterruptedException {
final Timer timer = new HashedWheelTimer();
final CountDownLatch barrier = new CountDownLatch(1);
final Timeout timeout = timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
fail("This should not have run");
barrier.countDown();
}
final Timeout timeout = timer.newTimeout(timeout1 -> {
fail("This should not have run");
barrier.countDown();
}, 10, TimeUnit.SECONDS);
assertFalse(barrier.await(3, TimeUnit.SECONDS));
assertFalse("timer should not expire", timeout.isExpired());
@ -51,12 +48,7 @@ public class HashedWheelTimerTest {
public void testScheduleTimeoutShouldRunAfterDelay() throws InterruptedException {
final Timer timer = new HashedWheelTimer();
final CountDownLatch barrier = new CountDownLatch(1);
final Timeout timeout = timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
barrier.countDown();
}
}, 2, TimeUnit.SECONDS);
final Timeout timeout = timer.newTimeout(timeout1 -> barrier.countDown(), 2, TimeUnit.SECONDS);
assertTrue(barrier.await(3, TimeUnit.SECONDS));
assertTrue("timer should expire", timeout.isExpired());
timer.stop();
@ -67,12 +59,7 @@ public class HashedWheelTimerTest {
final CountDownLatch latch = new CountDownLatch(3);
final Timer timerProcessed = new HashedWheelTimer();
for (int i = 0; i < 3; i ++) {
timerProcessed.newTimeout(new TimerTask() {
@Override
public void run(final Timeout timeout) throws Exception {
latch.countDown();
}
}, 1, TimeUnit.MILLISECONDS);
timerProcessed.newTimeout(timeout -> latch.countDown(), 1, TimeUnit.MILLISECONDS);
}
latch.await();
@ -80,10 +67,7 @@ public class HashedWheelTimerTest {
final Timer timerUnprocessed = new HashedWheelTimer();
for (int i = 0; i < 5; i ++) {
timerUnprocessed.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
}
timerUnprocessed.newTimeout(timeout -> {
}, 5, TimeUnit.SECONDS);
}
Thread.sleep(1000L); // sleep for a second
@ -95,12 +79,7 @@ public class HashedWheelTimerTest {
final CountDownLatch latch = new CountDownLatch(3);
final Timer timer = new HashedWheelTimer();
for (int i = 0; i < 3; i ++) {
timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
latch.countDown();
}
}, 1, TimeUnit.MILLISECONDS);
timer.newTimeout(timeout -> latch.countDown(), 1, TimeUnit.MILLISECONDS);
}
latch.await();
@ -143,12 +122,8 @@ public class HashedWheelTimerTest {
int scheduledTasks = 100000;
for (int i = 0; i < scheduledTasks; i++) {
final long start = System.nanoTime();
timer.newTimeout(new TimerTask() {
@Override
public void run(final Timeout timeout) throws Exception {
queue.add(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
}
}, timeout, TimeUnit.MILLISECONDS);
timer.newTimeout(timeout1 -> queue.add(
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)), timeout, TimeUnit.MILLISECONDS);
}
for (int i = 0; i < scheduledTasks; i++) {
@ -234,31 +209,18 @@ public class HashedWheelTimerTest {
public void testOverflow() throws InterruptedException {
final HashedWheelTimer timer = new HashedWheelTimer();
final CountDownLatch latch = new CountDownLatch(1);
Timeout timeout = timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) {
latch.countDown();
}
}, Long.MAX_VALUE, TimeUnit.MILLISECONDS);
Timeout timeout = timer.newTimeout(timeout1 -> latch.countDown(), Long.MAX_VALUE, TimeUnit.MILLISECONDS);
assertFalse(latch.await(1, TimeUnit.SECONDS));
timeout.cancel();
timer.stop();
}
private static TimerTask createNoOpTimerTask() {
return new TimerTask() {
@Override
public void run(final Timeout timeout) throws Exception {
}
return timeout -> {
};
}
private static TimerTask createCountDownLatchTimerTask(final CountDownLatch latch) {
return new TimerTask() {
@Override
public void run(final Timeout timeout) throws Exception {
latch.countDown();
}
};
return timeout -> latch.countDown();
}
}

View File

@ -102,17 +102,14 @@ public class NettyRuntimeTests {
final NettyRuntime.AvailableProcessorsHolder holder,
final CyclicBarrier barrier,
final AtomicReference<IllegalStateException> reference) {
return new Runnable() {
@Override
public void run() {
await(barrier);
try {
holder.availableProcessors();
} catch (final IllegalStateException e) {
reference.set(e);
}
await(barrier);
return () -> {
await(barrier);
try {
holder.availableProcessors();
} catch (final IllegalStateException e) {
reference.set(e);
}
await(barrier);
};
}
@ -120,28 +117,22 @@ public class NettyRuntimeTests {
public void testRacingGetAndSet() throws InterruptedException {
final NettyRuntime.AvailableProcessorsHolder holder = new NettyRuntime.AvailableProcessorsHolder();
final CyclicBarrier barrier = new CyclicBarrier(3);
final Thread get = new Thread(new Runnable() {
@Override
public void run() {
await(barrier);
holder.availableProcessors();
await(barrier);
}
final Thread get = new Thread(() -> {
await(barrier);
holder.availableProcessors();
await(barrier);
});
get.start();
final AtomicReference<IllegalStateException> setException = new AtomicReference<>();
final Thread set = new Thread(new Runnable() {
@Override
public void run() {
await(barrier);
try {
holder.setAvailableProcessors(2048);
} catch (final IllegalStateException e) {
setException.set(e);
}
await(barrier);
final Thread set = new Thread(() -> {
await(barrier);
try {
holder.setAvailableProcessors(2048);
} catch (final IllegalStateException e) {
setException.set(e);
}
await(barrier);
});
set.start();

View File

@ -41,13 +41,10 @@ public class RecyclerTest {
final Recycler<HandledObject> recycler = newRecycler(1024);
final AtomicBoolean collected = new AtomicBoolean();
final AtomicReference<HandledObject> reference = new AtomicReference<>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HandledObject object = recycler.get();
// Store a reference to the HandledObject to ensure it is not collected when the run method finish.
reference.set(object);
}
Thread thread = new Thread(() -> {
HandledObject object = recycler.get();
// Store a reference to the HandledObject to ensure it is not collected when the run method finish.
reference.set(object);
}) {
@Override
protected void finalize() throws Throwable {
@ -86,23 +83,15 @@ public class RecyclerTest {
Recycler<HandledObject> recycler = newRecycler(1024);
final HandledObject object = recycler.get();
final AtomicReference<IllegalStateException> exceptionStore = new AtomicReference<>();
final Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
object.recycle();
}
});
final Thread thread1 = new Thread(object::recycle);
thread1.start();
thread1.join();
final Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
object.recycle();
} catch (IllegalStateException e) {
exceptionStore.set(e);
}
final Thread thread2 = new Thread(() -> {
try {
object.recycle();
} catch (IllegalStateException e) {
exceptionStore.set(e);
}
});
thread2.start();

View File

@ -46,12 +46,9 @@ public class ThreadDeathWatcherTest {
}
};
final Runnable task = new Runnable() {
@Override
public void run() {
if (!t.isAlive()) {
latch.countDown();
}
final Runnable task = () -> {
if (!t.isAlive()) {
latch.countDown();
}
};
@ -91,12 +88,7 @@ public class ThreadDeathWatcherTest {
}
};
final Runnable task = new Runnable() {
@Override
public void run() {
run.set(true);
}
};
final Runnable task = () -> run.set(true);
t.start();
@ -121,16 +113,10 @@ public class ThreadDeathWatcherTest {
public void testThreadGroup() throws InterruptedException {
final ThreadGroup group = new ThreadGroup("group");
final AtomicReference<ThreadGroup> capturedGroup = new AtomicReference<>();
final Thread thread = new Thread(group, new Runnable() {
@Override
public void run() {
final Thread t = ThreadDeathWatcher.threadFactory.newThread(new Runnable() {
@Override
public void run() {
}
});
capturedGroup.set(t.getThreadGroup());
}
final Thread thread = new Thread(group, () -> {
final Thread t = ThreadDeathWatcher.threadFactory.newThread(() -> {
});
capturedGroup.set(t.getThreadGroup());
});
thread.start();
thread.join();

View File

@ -27,11 +27,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class AbstractScheduledEventExecutorTest {
private static final Runnable TEST_RUNNABLE = new Runnable() {
@Override
public void run() {
}
private static final Runnable TEST_RUNNABLE = () -> {
};
private static final Callable<?> TEST_CALLABLE = Executors.callable(TEST_RUNNABLE);

View File

@ -157,12 +157,7 @@ public class DefaultPromiseTest {
}
};
GlobalEventExecutor.INSTANCE.execute(new Runnable() {
@Override
public void run() {
promise.setSuccess(null);
}
});
GlobalEventExecutor.INSTANCE.execute(() -> promise.setSuccess(null));
promise.addListener(listener1).addListener(listener2).addListener(listener3);
@ -217,12 +212,7 @@ public class DefaultPromiseTest {
final Map<Thread, DefaultPromise<Void>> promises = new HashMap<>();
for (int i = 0; i < numberOfAttempts; i++) {
final DefaultPromise<Void> promise = new DefaultPromise<>(executor);
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
promise.setSuccess(null);
}
});
final Thread thread = new Thread(() -> promise.setSuccess(null));
promises.put(thread, promise);
}
@ -278,12 +268,7 @@ public class DefaultPromiseTest {
final CountDownLatch latch = new CountDownLatch(promiseChainLength);
if (runTestInExecutorThread) {
executor.execute(new Runnable() {
@Override
public void run() {
testStackOverFlowChainedFuturesA(executor, p, latch);
}
});
executor.execute(() -> testStackOverFlowChainedFuturesA(executor, p, latch));
} else {
testStackOverFlowChainedFuturesA(executor, p, latch);
}
@ -299,14 +284,11 @@ public class DefaultPromiseTest {
for (int i = 0; i < p.length; i ++) {
final int finalI = i;
p[i] = new DefaultPromise<>(executor);
p[i].addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (finalI + 1 < p.length) {
p[finalI + 1].setSuccess(null);
}
latch.countDown();
p[i].addListener((FutureListener<Void>) future -> {
if (finalI + 1 < p.length) {
p[finalI + 1].setSuccess(null);
}
latch.countDown();
});
}
@ -320,12 +302,7 @@ public class DefaultPromiseTest {
final CountDownLatch latch = new CountDownLatch(promiseChainLength);
if (runTestInExecutorThread) {
executor.execute(new Runnable() {
@Override
public void run() {
testStackOverFlowChainedFuturesA(executor, p, latch);
}
});
executor.execute(() -> testStackOverFlowChainedFuturesA(executor, p, latch));
} else {
testStackOverFlowChainedFuturesA(executor, p, latch);
}
@ -341,20 +318,12 @@ public class DefaultPromiseTest {
for (int i = 0; i < p.length; i ++) {
final int finalI = i;
p[i] = new DefaultPromise<>(executor);
p[i].addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
future.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (finalI + 1 < p.length) {
p[finalI + 1].setSuccess(null);
}
latch.countDown();
}
});
p[i].addListener((FutureListener<Void>) future -> future.addListener((FutureListener<Void>) future1 -> {
if (finalI + 1 < p.length) {
p[finalI + 1].setSuccess(null);
}
});
latch.countDown();
}));
}
p[0].setSuccess(null);
@ -379,12 +348,7 @@ public class DefaultPromiseTest {
final Promise<Void> promise = new DefaultPromise<>(executor);
// Add a listener before completion so "lateListener" is used next time we add a listener.
promise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(state.compareAndSet(0, 1));
}
});
promise.addListener((FutureListener<Void>) future -> assertTrue(state.compareAndSet(0, 1)));
// Simulate write operation completing, which will execute listeners in another thread.
if (cause == null) {
@ -394,12 +358,9 @@ public class DefaultPromiseTest {
}
// Add a "late listener"
promise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(state.compareAndSet(1, 2));
latch1.countDown();
}
promise.addListener((FutureListener<Void>) future -> {
assertTrue(state.compareAndSet(1, 2));
latch1.countDown();
});
// Wait for the listeners and late listeners to be completed.
@ -408,27 +369,16 @@ public class DefaultPromiseTest {
// This is the important listener. A late listener that is added after all late listeners
// have completed, and needs to update state before a read operation (on the same executor).
executor.execute(new Runnable() {
@Override
public void run() {
promise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(state.compareAndSet(2, 3));
latch2.countDown();
}
});
}
});
executor.execute(() -> promise.addListener((FutureListener<Void>) future -> {
assertTrue(state.compareAndSet(2, 3));
latch2.countDown();
}));
// Simulate a read operation being queued up in the executor.
executor.execute(new Runnable() {
@Override
public void run() {
// This is the key, we depend upon the state being set in the next listener.
assertEquals(3, state.get());
latch2.countDown();
}
executor.execute(() -> {
// This is the key, we depend upon the state being set in the next listener.
assertEquals(3, state.get());
latch2.countDown();
});
latch2.await();
@ -440,17 +390,8 @@ public class DefaultPromiseTest {
private static void testPromiseListenerAddWhenComplete(Throwable cause) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Promise<Void> promise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE);
promise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
promise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
latch.countDown();
}
});
}
});
promise.addListener((FutureListener<Void>) future ->
promise.addListener((FutureListener<Void>) future1 -> latch.countDown()));
if (cause == null) {
promise.setSuccess(null);
} else {
@ -463,29 +404,16 @@ public class DefaultPromiseTest {
EventExecutor executor = new TestEventExecutor();
int expectedCount = numListenersBefore + 2;
final CountDownLatch latch = new CountDownLatch(expectedCount);
final FutureListener<Void> listener = new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
latch.countDown();
}
};
final FutureListener<Void> listener = future -> latch.countDown();
final Promise<Void> promise = new DefaultPromise<>(executor);
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < numListenersBefore; i++) {
promise.addListener(listener);
}
promise.setSuccess(null);
GlobalEventExecutor.INSTANCE.execute(new Runnable() {
@Override
public void run() {
promise.addListener(listener);
}
});
executor.execute(() -> {
for (int i = 0; i < numListenersBefore; i++) {
promise.addListener(listener);
}
promise.setSuccess(null);
GlobalEventExecutor.INSTANCE.execute(() -> promise.addListener(listener));
promise.addListener(listener);
});
assertTrue("Should have notified " + expectedCount + " listeners",

View File

@ -55,30 +55,22 @@ public class DefaultThreadFactoryTest {
// holder for the thread factory, plays the role of a global singleton
final AtomicReference<DefaultThreadFactory> factory = new AtomicReference<>();
final AtomicInteger counter = new AtomicInteger();
final Runnable task = new Runnable() {
@Override
public void run() {
counter.incrementAndGet();
}
};
final Runnable task = counter::incrementAndGet;
final AtomicReference<Throwable> interrupted = new AtomicReference<>();
// create the thread factory, since we are running the thread group brother, the thread
// factory will now forever be tied to that group
// we then create a thread from the factory to run a "task" for us
final Thread first = new Thread(new ThreadGroup("brother"), new Runnable() {
@Override
public void run() {
factory.set(new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, null));
final Thread t = factory.get().newThread(task);
t.start();
try {
t.join();
} catch (InterruptedException e) {
interrupted.set(e);
Thread.currentThread().interrupt();
}
final Thread first = new Thread(new ThreadGroup("brother"), () -> {
factory.set(new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, null));
final Thread t = factory.get().newThread(task);
t.start();
try {
t.join();
} catch (InterruptedException e) {
interrupted.set(e);
Thread.currentThread().interrupt();
}
});
first.start();
@ -89,17 +81,14 @@ public class DefaultThreadFactoryTest {
// now we will use factory again, this time from a sibling thread group sister
// if DefaultThreadFactory is "sticky" about thread groups, a security manager
// that forbids sibling thread groups from messing with each other will strike this down
final Thread second = new Thread(new ThreadGroup("sister"), new Runnable() {
@Override
public void run() {
final Thread t = factory.get().newThread(task);
t.start();
try {
t.join();
} catch (InterruptedException e) {
interrupted.set(e);
Thread.currentThread().interrupt();
}
final Thread second = new Thread(new ThreadGroup("sister"), () -> {
final Thread t = factory.get().newThread(task);
t.start();
try {
t.join();
} catch (InterruptedException e) {
interrupted.set(e);
Thread.currentThread().interrupt();
}
});
second.start();
@ -119,12 +108,7 @@ public class DefaultThreadFactoryTest {
public void testDefaultThreadFactoryStickyThreadGroupConstructor() throws InterruptedException {
final ThreadGroup sticky = new ThreadGroup("sticky");
runStickyThreadGroupTest(
new Callable<DefaultThreadFactory>() {
@Override
public DefaultThreadFactory call() throws Exception {
return new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, sticky);
}
},
() -> new DefaultThreadFactory("test", false, Thread.NORM_PRIORITY, sticky),
sticky);
}
@ -135,21 +119,13 @@ public class DefaultThreadFactoryTest {
final ThreadGroup sticky = new ThreadGroup("sticky");
runStickyThreadGroupTest(
new Callable<DefaultThreadFactory>() {
@Override
public DefaultThreadFactory call() throws Exception {
final AtomicReference<DefaultThreadFactory> factory =
new AtomicReference<>();
final Thread thread = new Thread(sticky, new Runnable() {
@Override
public void run() {
factory.set(new DefaultThreadFactory("test"));
}
});
thread.start();
thread.join();
return factory.get();
}
() -> {
final AtomicReference<DefaultThreadFactory> factory =
new AtomicReference<>();
final Thread thread = new Thread(sticky, () -> factory.set(new DefaultThreadFactory("test")));
thread.start();
thread.join();
return factory.get();
},
sticky);
}
@ -174,12 +150,7 @@ public class DefaultThreadFactoryTest {
}
});
runStickyThreadGroupTest(
new Callable<DefaultThreadFactory>() {
@Override
public DefaultThreadFactory call() throws Exception {
return new DefaultThreadFactory("test");
}
},
() -> new DefaultThreadFactory("test"),
sticky);
} finally {
System.setSecurityManager(current);
@ -192,23 +163,17 @@ public class DefaultThreadFactoryTest {
final AtomicReference<ThreadGroup> captured = new AtomicReference<>();
final AtomicReference<Throwable> exception = new AtomicReference<>();
final Thread first = new Thread(new ThreadGroup("wrong"), new Runnable() {
@Override
public void run() {
final DefaultThreadFactory factory;
try {
factory = callable.call();
} catch (Exception e) {
exception.set(e);
throw new RuntimeException(e);
}
final Thread t = factory.newThread(new Runnable() {
@Override
public void run() {
}
});
captured.set(t.getThreadGroup());
final Thread first = new Thread(new ThreadGroup("wrong"), () -> {
final DefaultThreadFactory factory;
try {
factory = callable.call();
} catch (Exception e) {
exception.set(e);
throw new RuntimeException(e);
}
final Thread t = factory.newThread(() -> {
});
captured.set(t.getThreadGroup());
});
first.start();
first.join();
@ -227,17 +192,11 @@ public class DefaultThreadFactoryTest {
final AtomicReference<ThreadGroup> firstCaptured = new AtomicReference<>();
final ThreadGroup firstGroup = new ThreadGroup("first");
final Thread first = new Thread(firstGroup, new Runnable() {
@Override
public void run() {
factory.set(new DefaultThreadFactory("sticky", false, Thread.NORM_PRIORITY, null));
final Thread t = factory.get().newThread(new Runnable() {
@Override
public void run() {
}
});
firstCaptured.set(t.getThreadGroup());
}
final Thread first = new Thread(firstGroup, () -> {
factory.set(new DefaultThreadFactory("sticky", false, Thread.NORM_PRIORITY, null));
final Thread t = factory.get().newThread(() -> {
});
firstCaptured.set(t.getThreadGroup());
});
first.start();
first.join();
@ -247,16 +206,10 @@ public class DefaultThreadFactoryTest {
final AtomicReference<ThreadGroup> secondCaptured = new AtomicReference<>();
final ThreadGroup secondGroup = new ThreadGroup("second");
final Thread second = new Thread(secondGroup, new Runnable() {
@Override
public void run() {
final Thread t = factory.get().newThread(new Runnable() {
@Override
public void run() {
}
});
secondCaptured.set(t.getThreadGroup());
}
final Thread second = new Thread(secondGroup, () -> {
final Thread t = factory.get().newThread(() -> {
});
secondCaptured.set(t.getThreadGroup());
});
second.start();
second.join();

View File

@ -82,14 +82,11 @@ public class FastThreadLocalTest {
@Test
public void testMultipleSetRemove() throws Exception {
final FastThreadLocal<String> threadLocal = new FastThreadLocal<>();
final Runnable runnable = new Runnable() {
@Override
public void run() {
threadLocal.set("1");
threadLocal.remove();
threadLocal.set("2");
threadLocal.remove();
}
final Runnable runnable = () -> {
threadLocal.set("1");
threadLocal.remove();
threadLocal.set("2");
threadLocal.remove();
};
final int sizeWhenStart = ObjectCleaner.getLiveSetCount();
@ -110,18 +107,15 @@ public class FastThreadLocalTest {
public void testMultipleSetRemove_multipleThreadLocal() throws Exception {
final FastThreadLocal<String> threadLocal = new FastThreadLocal<>();
final FastThreadLocal<String> threadLocal2 = new FastThreadLocal<>();
final Runnable runnable = new Runnable() {
@Override
public void run() {
threadLocal.set("1");
threadLocal.remove();
threadLocal.set("2");
threadLocal.remove();
threadLocal2.set("1");
threadLocal2.remove();
threadLocal2.set("2");
threadLocal2.remove();
}
final Runnable runnable = () -> {
threadLocal.set("1");
threadLocal.remove();
threadLocal.set("2");
threadLocal.remove();
threadLocal2.set("1");
threadLocal2.remove();
threadLocal2.set("2");
threadLocal2.remove();
};
final int sizeWhenStart = ObjectCleaner.getLiveSetCount();
@ -165,16 +159,13 @@ public class FastThreadLocalTest {
final TestFastThreadLocal threadLocal = new TestFastThreadLocal();
final TestFastThreadLocal threadLocal2 = new TestFastThreadLocal();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (callGet) {
assertEquals(Thread.currentThread().getName(), threadLocal.get());
assertEquals(Thread.currentThread().getName(), threadLocal2.get());
} else {
threadLocal.set(Thread.currentThread().getName());
threadLocal2.set(Thread.currentThread().getName());
}
Runnable runnable = () -> {
if (callGet) {
assertEquals(Thread.currentThread().getName(), threadLocal.get());
assertEquals(Thread.currentThread().getName(), threadLocal2.get());
} else {
threadLocal.set(Thread.currentThread().getName());
threadLocal2.set(Thread.currentThread().getName());
}
};
Thread thread = fastThreadLocal ? new FastThreadLocalThread(runnable) : new Thread(runnable);

View File

@ -99,16 +99,10 @@ public class GlobalEventExecutorTest {
public void testThreadGroup() throws InterruptedException {
final ThreadGroup group = new ThreadGroup("group");
final AtomicReference<ThreadGroup> capturedGroup = new AtomicReference<>();
final Thread thread = new Thread(group, new Runnable() {
@Override
public void run() {
final Thread t = e.threadFactory.newThread(new Runnable() {
@Override
public void run() {
}
});
capturedGroup.set(t.getThreadGroup());
}
final Thread thread = new Thread(group, () -> {
final Thread t = e.threadFactory.newThread(() -> {
});
capturedGroup.set(t.getThreadGroup());
});
thread.start();
thread.join();

View File

@ -68,14 +68,11 @@ public class NonStickyEventExecutorGroupTest {
final AtomicReference<Throwable> error = new AtomicReference<>();
List<Thread> threadList = new ArrayList<>(threads);
for (int i = 0 ; i < threads; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
execute(nonStickyGroup, startLatch);
} catch (Throwable cause) {
error.compareAndSet(null, cause);
}
Thread thread = new Thread(() -> {
try {
execute(nonStickyGroup, startLatch);
} catch (Throwable cause) {
error.compareAndSet(null, cause);
}
});
threadList.add(thread);
@ -106,12 +103,9 @@ public class NonStickyEventExecutorGroupTest {
final CountDownLatch firstCompleted = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
firstCompleted.countDown();
latch.countDown();
}
executor.execute(() -> {
firstCompleted.countDown();
latch.countDown();
});
Assert.assertTrue(firstCompleted.await(1, TimeUnit.SECONDS));
}
@ -135,23 +129,20 @@ public class NonStickyEventExecutorGroupTest {
for (int i = 1 ; i <= tasks; i++) {
final int id = i;
futures.add(executor.submit(new Runnable() {
@Override
public void run() {
try {
if (cause.get() == null) {
int lastId = last.get();
if (lastId >= id) {
cause.compareAndSet(null, new AssertionError(
"Out of order execution id(" + id + ") >= lastId(" + lastId + ')'));
}
if (!last.compareAndSet(lastId, id)) {
cause.compareAndSet(null, new AssertionError("Concurrent execution of tasks"));
}
futures.add(executor.submit(() -> {
try {
if (cause.get() == null) {
int lastId = last.get();
if (lastId >= id) {
cause.compareAndSet(null, new AssertionError(
"Out of order execution id(" + id + ") >= lastId(" + lastId + ')'));
}
if (!last.compareAndSet(lastId, id)) {
cause.compareAndSet(null, new AssertionError("Concurrent execution of tasks"));
}
} finally {
latch.countDown();
}
} finally {
latch.countDown();
}
}));
}

View File

@ -178,13 +178,9 @@ public class PromiseCombinerTest {
@SuppressWarnings("unchecked")
private static void mockListener(final Promise<Void> p, final GenericFutureListenerConsumer consumer) {
doAnswer(new Answer<Promise<Void>>() {
@SuppressWarnings({ "unchecked", "raw-types" })
@Override
public Promise<Void> answer(InvocationOnMock invocation) throws Throwable {
consumer.accept((GenericFutureListener) invocation.getArgument(0));
return p;
}
doAnswer(invocation -> {
consumer.accept((GenericFutureListener) invocation.getArgument(0));
return p;
}).when(p).addListener(any(GenericFutureListener.class));
}

View File

@ -60,11 +60,8 @@ public class SingleThreadEventExecutorTest {
private static void executeShouldFail(Executor executor) {
try {
executor.execute(new Runnable() {
@Override
public void run() {
// Noop.
}
executor.execute(() -> {
// Noop.
});
Assert.fail();
} catch (RejectedExecutionException expected) {
@ -133,34 +130,28 @@ public class SingleThreadEventExecutorTest {
};
try {
final Promise<Void> promise = executor.newPromise();
executor.execute(new Runnable() {
@Override
public void run() {
try {
Set<Callable<Boolean>> set = Collections.singleton(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
promise.setFailure(new AssertionError("Should never execute the Callable"));
return Boolean.TRUE;
}
});
if (any) {
if (timeout) {
executor.invokeAny(set, 10, TimeUnit.SECONDS);
} else {
executor.invokeAny(set);
}
executor.execute(() -> {
try {
Set<Callable<Boolean>> set = Collections.singleton(() -> {
promise.setFailure(new AssertionError("Should never execute the Callable"));
return Boolean.TRUE;
});
if (any) {
if (timeout) {
executor.invokeAny(set, 10, TimeUnit.SECONDS);
} else {
if (timeout) {
executor.invokeAll(set, 10, TimeUnit.SECONDS);
} else {
executor.invokeAll(set);
}
executor.invokeAny(set);
}
} else {
if (timeout) {
executor.invokeAll(set, 10, TimeUnit.SECONDS);
} else {
executor.invokeAll(set);
}
promise.setFailure(new AssertionError("Should never reach here"));
} catch (Throwable cause) {
promise.setFailure(cause);
}
promise.setFailure(new AssertionError("Should never reach here"));
} catch (Throwable cause) {
promise.setFailure(cause);
}
});
promise.syncUninterruptibly();

Some files were not shown because too many files have changed in this diff Show More