Fix most inspector warnings

Motivation:

It's good to minimize potentially broken windows.

Modifications:

Fix most inspector warnings from our profile

Result:

Cleaner code
This commit is contained in:
Trustin Lee 2014-07-02 19:04:11 +09:00
parent cea3b6b2ab
commit 330404da07
155 changed files with 439 additions and 618 deletions

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2012 The Netty Project
~
~ The Netty Project licenses this file to you under the Apache License,
~ version 2.0 (the "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at:
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
~ License for the specific language governing permissions and limitations
~ under the License.
-->
<FindBugsFilter>
<!-- Tests -->
<Match>
<Class name="~.*Test(\$[^\$]+)*"/>
</Match>
<!-- Generated code -->
<Match>
<Class name="~.*\.LocalTimeProtocol(\$[^\$]+)*"/>
</Match>
<!-- Noise -->
<Match>
<Bug code="Co,SF"
category="I18N"
pattern="REC_CATCH_EXCEPTION,UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR,DB_DUPLICATE_SWITCH_CLAUSES,VO_VOLATILE_REFERENCE_TO_ARRAY" />
</Match>
<!-- Known false positives -->
<Match>
<Class name="~.*Channel(Group)?Future"/>
<Method name="~await.*"/>
<Bug pattern="PS_PUBLIC_SEMAPHORES"/>
</Match>
<Match>
<Class name="~.*SelectorLoop"/>
<Method name="run"/>
<Bug code="ESync"/>
</Match>
<Match>
<Class name="~.*Channel"/>
<Or>
<Method name="setClosed"/>
<Method name="setInterestOpsNow"/>
</Or>
<Bug pattern="USM_USELESS_SUBCLASS_METHOD"/>
</Match>
<Match>
<Class name="~.*HttpTunnelingChannelHandler"/>
<Method name="~await.*"/>
<Bug pattern="RV_RETURN_VALUE_IGNORED_BAD_PRACTICE,RV_RETURN_VALUE_IGNORED2"/>
</Match>
<!-- Known issues that don't matter -->
<Match>
<Or>
<Class name="~.*\.util\.internal\.Concurrent[A-Za-z]*HashMap(\$[^\$]+)*"/>
<Class name="~.*\.util\.internal\..*TransferQueue(\$[^\$]+)*"/>
<Class name="~.*\.util\.internal\.MapBackedSet"/>
</Or>
<Bug pattern="SE_TRANSIENT_FIELD_NOT_RESTORED,SE_BAD_FIELD"/>
</Match>
</FindBugsFilter>

View File

@ -37,7 +37,6 @@ public abstract class AbstractReferenceCountedByteBuf extends AbstractByteBuf {
refCntUpdater = updater; refCntUpdater = updater;
} }
@SuppressWarnings("FieldMayBeFinal")
private volatile int refCnt = 1; private volatile int refCnt = 1;
protected AbstractReferenceCountedByteBuf(int maxCapacity) { protected AbstractReferenceCountedByteBuf(int maxCapacity) {

View File

@ -189,7 +189,7 @@ public class ByteBufInputStream extends InputStream implements DataInput {
loop: while (true) { loop: while (true) {
if (!buffer.isReadable()) { if (!buffer.isReadable()) {
return (lineBuf.length() > 0) ? lineBuf.toString() : null; return lineBuf.length() > 0 ? lineBuf.toString() : null;
} }
int c = buffer.readUnsignedByte(); int c = buffer.readUnsignedByte();
@ -198,7 +198,7 @@ public class ByteBufInputStream extends InputStream implements DataInput {
break loop; break loop;
case '\r': case '\r':
if (buffer.isReadable() && buffer.getUnsignedByte(buffer.readerIndex()) == '\n') { if (buffer.isReadable() && (char) buffer.getUnsignedByte(buffer.readerIndex()) == '\n') {
buffer.skipBytes(1); buffer.skipBytes(1);
} }
break loop; break loop;

View File

@ -289,7 +289,6 @@ public class CompositeByteBuf extends AbstractReferenceCountedByteBuf {
ByteBuf consolidated = allocBuffer(capacity); ByteBuf consolidated = allocBuffer(capacity);
// We're not using foreach to avoid creating an iterator. // We're not using foreach to avoid creating an iterator.
// noinspection ForLoopReplaceableByForEach
for (int i = 0; i < numComponents; i ++) { for (int i = 0; i < numComponents; i ++) {
Component c = components.get(i); Component c = components.get(i);
ByteBuf b = c.buf; ByteBuf b = c.buf;
@ -1098,7 +1097,6 @@ public class CompositeByteBuf extends AbstractReferenceCountedByteBuf {
} else { } else {
int count = 0; int count = 0;
int componentsCount = components.size(); int componentsCount = components.size();
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < componentsCount; i++) { for (int i = 0; i < componentsCount; i++) {
Component c = components.get(i); Component c = components.get(i);
count += c.buf.nioBufferCount(); count += c.buf.nioBufferCount();

View File

@ -41,7 +41,7 @@ final class FixedCompositeByteBuf extends AbstractReferenceCountedByteBuf {
private final Object[] buffers; private final Object[] buffers;
private final boolean direct; private final boolean direct;
public FixedCompositeByteBuf(ByteBufAllocator allocator, ByteBuf... buffers) { FixedCompositeByteBuf(ByteBufAllocator allocator, ByteBuf... buffers) {
super(Integer.MAX_VALUE); super(Integer.MAX_VALUE);
if (buffers.length == 0) { if (buffers.length == 0) {
this.buffers = EMPTY; this.buffers = EMPTY;
@ -204,7 +204,6 @@ final class FixedCompositeByteBuf extends AbstractReferenceCountedByteBuf {
private Component findComponent(int index) { private Component findComponent(int index) {
int readable = 0; int readable = 0;
//noinspection ForLoopReplaceableByForEach
for (int i = 0 ; i < buffers.length; i++) { for (int i = 0 ; i < buffers.length; i++) {
Component comp = null; Component comp = null;
ByteBuf b; ByteBuf b;
@ -545,7 +544,6 @@ final class FixedCompositeByteBuf extends AbstractReferenceCountedByteBuf {
@Override @Override
protected void deallocate() { protected void deallocate() {
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < buffers.length; i++) { for (int i = 0; i < buffers.length; i++) {
buffer(i).release(); buffer(i).release();
} }

View File

@ -147,7 +147,6 @@ abstract class PooledByteBuf<T> extends AbstractReferenceCountedByteBuf {
} }
} }
@SuppressWarnings("unchecked")
private void recycle() { private void recycle() {
recyclerHandle.recycle(this); recyclerHandle.recycle(this);
} }

View File

@ -308,7 +308,7 @@ final class PooledDirectByteBuf extends PooledByteBuf<ByteBuffer> {
tmpBuf.clear().position(index).limit(index + length); tmpBuf.clear().position(index).limit(index + length);
try { try {
return in.read(tmpBuf); return in.read(tmpBuf);
} catch (ClosedChannelException e) { } catch (ClosedChannelException ignored) {
return -1; return -1;
} }
} }

View File

@ -232,7 +232,7 @@ final class PooledHeapByteBuf extends PooledByteBuf<byte[]> {
index = idx(index); index = idx(index);
try { try {
return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)); return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length));
} catch (ClosedChannelException e) { } catch (ClosedChannelException ignored) {
return -1; return -1;
} }
} }

View File

@ -309,7 +309,7 @@ final class PooledUnsafeDirectByteBuf extends PooledByteBuf<ByteBuffer> {
tmpBuf.clear().position(index).limit(index + length); tmpBuf.clear().position(index).limit(index + length);
try { try {
return in.read(tmpBuf); return in.read(tmpBuf);
} catch (ClosedChannelException e) { } catch (ClosedChannelException ignored) {
return -1; return -1;
} }
} }

View File

@ -36,7 +36,7 @@ class ReadOnlyByteBufferBuf extends AbstractReferenceCountedByteBuf {
private final ByteBufAllocator allocator; private final ByteBufAllocator allocator;
private ByteBuffer tmpNioBuf; private ByteBuffer tmpNioBuf;
public ReadOnlyByteBufferBuf(ByteBufAllocator allocator, ByteBuffer buffer) { ReadOnlyByteBufferBuf(ByteBufAllocator allocator, ByteBuffer buffer) {
super(buffer.remaining()); super(buffer.remaining());
if (!buffer.isReadOnly()) { if (!buffer.isReadOnly()) {
throw new IllegalArgumentException("must be a readonly buffer: " + StringUtil.simpleClassName(buffer)); throw new IllegalArgumentException("must be a readonly buffer: " + StringUtil.simpleClassName(buffer));
@ -276,7 +276,7 @@ class ReadOnlyByteBufferBuf extends AbstractReferenceCountedByteBuf {
ByteBuffer src; ByteBuffer src;
try { try {
src = (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); src = (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException ignored) {
throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length));
} }

View File

@ -30,7 +30,7 @@ final class ReadOnlyUnsafeDirectByteBuf extends ReadOnlyByteBufferBuf {
private static final boolean NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; private static final boolean NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
private final long memoryAddress; private final long memoryAddress;
public ReadOnlyUnsafeDirectByteBuf(ByteBufAllocator allocator, ByteBuffer buffer) { ReadOnlyUnsafeDirectByteBuf(ByteBufAllocator allocator, ByteBuffer buffer) {
super(allocator, buffer); super(allocator, buffer);
memoryAddress = PlatformDependent.directBufferAddress(buffer); memoryAddress = PlatformDependent.directBufferAddress(buffer);
} }

View File

@ -39,7 +39,7 @@ public class SlicedByteBuf extends AbstractDerivedByteBuf {
public SlicedByteBuf(ByteBuf buffer, int index, int length) { public SlicedByteBuf(ByteBuf buffer, int index, int length) {
super(length); super(length);
if (index < 0 || index > buffer.capacity() - length) { if (index < 0 || index > buffer.capacity() - length) {
throw new IndexOutOfBoundsException(buffer.toString() + ".slice(" + index + ", " + length + ')'); throw new IndexOutOfBoundsException(buffer + ".slice(" + index + ", " + length + ')');
} }
if (buffer instanceof SlicedByteBuf) { if (buffer instanceof SlicedByteBuf) {

View File

@ -535,7 +535,7 @@ public class UnpooledDirectByteBuf extends AbstractReferenceCountedByteBuf {
tmpBuf.clear().position(index).limit(index + length); tmpBuf.clear().position(index).limit(index + length);
try { try {
return in.read(tmpNioBuf); return in.read(tmpNioBuf);
} catch (ClosedChannelException e) { } catch (ClosedChannelException ignored) {
return -1; return -1;
} }
} }
@ -556,7 +556,7 @@ public class UnpooledDirectByteBuf extends AbstractReferenceCountedByteBuf {
ByteBuffer src; ByteBuffer src;
try { try {
src = (ByteBuffer) buffer.duplicate().clear().position(index).limit(index + length); src = (ByteBuffer) buffer.duplicate().clear().position(index).limit(index + length);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException ignored) {
throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length));
} }

View File

@ -254,7 +254,7 @@ public class UnpooledHeapByteBuf extends AbstractReferenceCountedByteBuf {
ensureAccessible(); ensureAccessible();
try { try {
return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)); return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length));
} catch (ClosedChannelException e) { } catch (ClosedChannelException ignored) {
return -1; return -1;
} }
} }

View File

@ -444,7 +444,7 @@ public class UnpooledUnsafeDirectByteBuf extends AbstractReferenceCountedByteBuf
tmpBuf.clear().position(index).limit(index + length); tmpBuf.clear().position(index).limit(index + length);
try { try {
return in.read(tmpBuf); return in.read(tmpBuf);
} catch (ClosedChannelException e) { } catch (ClosedChannelException ignored) {
return -1; return -1;
} }
} }

View File

@ -773,6 +773,7 @@ public class WrappedByteBuf extends ByteBuf {
} }
@Override @Override
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
public boolean equals(Object obj) { public boolean equals(Object obj) {
return buf.equals(obj); return buf.equals(obj);
} }

View File

@ -18,10 +18,8 @@ package io.netty.buffer;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.IllegalReferenceCountException; import io.netty.util.IllegalReferenceCountException;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -1477,6 +1475,7 @@ public abstract class AbstractByteBufTest {
} }
@Test @Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() { public void testEquals() {
assertFalse(buffer.equals(null)); assertFalse(buffer.equals(null));
assertFalse(buffer.equals(new Object())); assertFalse(buffer.equals(new Object()));
@ -1728,7 +1727,6 @@ public abstract class AbstractByteBufTest {
assertThat(lastIndex.get(), is(CAPACITY / 4)); assertThat(lastIndex.get(), is(CAPACITY / 4));
} }
@Ignore
@Test @Test
public void testInternalNioBuffer() { public void testInternalNioBuffer() {
testInternalNioBuffer(128); testInternalNioBuffer(128);
@ -1796,7 +1794,7 @@ public abstract class AbstractByteBufTest {
return; return;
} }
} }
Assert.assertArrayEquals(bytes, channel.writtenBytes()); assertArrayEquals(bytes, channel.writtenBytes());
latch.countDown(); latch.countDown();
} }
try { try {
@ -1850,7 +1848,7 @@ public abstract class AbstractByteBufTest {
return; return;
} }
} }
Assert.assertArrayEquals(bytes, out.toByteArray()); assertArrayEquals(bytes, out.toByteArray());
latch.countDown(); latch.countDown();
} }
try { try {
@ -1899,11 +1897,11 @@ public abstract class AbstractByteBufTest {
byte[] array = new byte[8]; byte[] array = new byte[8];
buf.readBytes(array); buf.readBytes(array);
Assert.assertArrayEquals(bytes, array); assertArrayEquals(bytes, array);
Arrays.fill(array, (byte) 0); Arrays.fill(array, (byte) 0);
buf.getBytes(0, array); buf.getBytes(0, array);
Assert.assertArrayEquals(bytes, array); assertArrayEquals(bytes, array);
latch.countDown(); latch.countDown();
} }
@ -1929,6 +1927,7 @@ public abstract class AbstractByteBufTest {
} }
@Test @Test
@SuppressWarnings("ForLoopThatDoesntUseLoopVariable")
public void testNioBufferExposeOnlyRegion() { public void testNioBufferExposeOnlyRegion() {
final ByteBuf buffer = releaseLater(newBuffer(8)); final ByteBuf buffer = releaseLater(newBuffer(8));
byte[] data = new byte[8]; byte[] data = new byte[8];

View File

@ -71,8 +71,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
buffers.add(EMPTY_BUFFER); buffers.add(EMPTY_BUFFER);
} }
buffer = Unpooled.wrappedBuffer( buffer = wrappedBuffer(Integer.MAX_VALUE, buffers.toArray(new ByteBuf[buffers.size()])).order(order);
Integer.MAX_VALUE, buffers.toArray(new ByteBuf[buffers.size()])).order(order);
// Truncate to the requested capacity. // Truncate to the requested capacity.
buffer.capacity(length); buffer.capacity(length);
@ -802,7 +801,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
CompositeByteBuf cbuf = releaseLater(compositeBuffer()); CompositeByteBuf cbuf = releaseLater(compositeBuffer());
int len = 8 * 4; int len = 8 * 4;
for (int i = 0; i < len; i += 4) { for (int i = 0; i < len; i += 4) {
ByteBuf buf = Unpooled.buffer().writeInt(i); ByteBuf buf = buffer().writeInt(i);
cbuf.capacity(cbuf.writerIndex()).addComponent(buf).writerIndex(i + 4); cbuf.capacity(cbuf.writerIndex()).addComponent(buf).writerIndex(i + 4);
} }
cbuf.writeByte(1); cbuf.writeByte(1);

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -44,14 +43,6 @@ public class DuplicateByteBufTest extends AbstractByteBufTest {
new DuplicatedByteBuf(null); new DuplicatedByteBuf(null);
} }
@Ignore
@Test
// Test which shows bug
// https://github.com/netty/netty/issues/1802
public void testInternalNioBuffer() {
super.testInternalNioBuffer();
}
// See https://github.com/netty/netty/issues/1800 // See https://github.com/netty/netty/issues/1800
@Test @Test
public void testIncreaseCapacityWrapped() { public void testIncreaseCapacityWrapped() {

View File

@ -46,15 +46,15 @@ public class ReadOnlyByteBufTest {
@Test @Test
public void testUnwrap() { public void testUnwrap() {
ByteBuf buf = buffer(1); ByteBuf buf = buffer(1);
assertSame(buf, Unpooled.unmodifiableBuffer(buf).unwrap()); assertSame(buf, unmodifiableBuffer(buf).unwrap());
} }
@Test @Test
public void shouldHaveSameByteOrder() { public void shouldHaveSameByteOrder() {
ByteBuf buf = buffer(1); ByteBuf buf = buffer(1);
assertSame(BIG_ENDIAN, Unpooled.unmodifiableBuffer(buf).order()); assertSame(BIG_ENDIAN, unmodifiableBuffer(buf).order());
buf = buf.order(LITTLE_ENDIAN); buf = buf.order(LITTLE_ENDIAN);
assertSame(LITTLE_ENDIAN, Unpooled.unmodifiableBuffer(buf).order()); assertSame(LITTLE_ENDIAN, unmodifiableBuffer(buf).order());
} }
@Test @Test

View File

@ -445,8 +445,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readInt()); assertEquals(4, buffer.readInt());
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyInt(null).capacity()); assertEquals(0, copyInt(null).capacity());
assertEquals(0, Unpooled.copyInt(EMPTY_INTS).capacity()); assertEquals(0, copyInt(EMPTY_INTS).capacity());
} }
@Test @Test
@ -465,8 +465,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readShort()); assertEquals(4, buffer.readShort());
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyShort((short[]) null).capacity()); assertEquals(0, copyShort((short[]) null).capacity());
assertEquals(0, Unpooled.copyShort(EMPTY_SHORTS).capacity()); assertEquals(0, copyShort(EMPTY_SHORTS).capacity());
} }
@Test @Test
@ -477,8 +477,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readShort()); assertEquals(4, buffer.readShort());
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyShort((int[]) null).capacity()); assertEquals(0, copyShort((int[]) null).capacity());
assertEquals(0, Unpooled.copyShort(EMPTY_INTS).capacity()); assertEquals(0, copyShort(EMPTY_INTS).capacity());
} }
@Test @Test
@ -497,8 +497,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readMedium()); assertEquals(4, buffer.readMedium());
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyMedium(null).capacity()); assertEquals(0, copyMedium(null).capacity());
assertEquals(0, Unpooled.copyMedium(EMPTY_INTS).capacity()); assertEquals(0, copyMedium(EMPTY_INTS).capacity());
} }
@Test @Test
@ -517,8 +517,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readLong()); assertEquals(4, buffer.readLong());
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyLong(null).capacity()); assertEquals(0, copyLong(null).capacity());
assertEquals(0, Unpooled.copyLong(EMPTY_LONGS).capacity()); assertEquals(0, copyLong(EMPTY_LONGS).capacity());
} }
@Test @Test
@ -537,8 +537,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readFloat(), 0.01); assertEquals(4, buffer.readFloat(), 0.01);
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyFloat(null).capacity()); assertEquals(0, copyFloat(null).capacity());
assertEquals(0, Unpooled.copyFloat(EMPTY_FLOATS).capacity()); assertEquals(0, copyFloat(EMPTY_FLOATS).capacity());
} }
@Test @Test
@ -557,8 +557,8 @@ public class UnpooledTest {
assertEquals(4, buffer.readDouble(), 0.01); assertEquals(4, buffer.readDouble(), 0.01);
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyDouble(null).capacity()); assertEquals(0, copyDouble(null).capacity());
assertEquals(0, Unpooled.copyDouble(EMPTY_DOUBLES).capacity()); assertEquals(0, copyDouble(EMPTY_DOUBLES).capacity());
} }
@Test @Test
@ -569,8 +569,8 @@ public class UnpooledTest {
assertFalse(buffer.readBoolean()); assertFalse(buffer.readBoolean());
assertFalse(buffer.isReadable()); assertFalse(buffer.isReadable());
assertEquals(0, Unpooled.copyBoolean(null).capacity()); assertEquals(0, copyBoolean(null).capacity());
assertEquals(0, Unpooled.copyBoolean(EMPTY_BOOLEANS).capacity()); assertEquals(0, copyBoolean(EMPTY_BOOLEANS).capacity());
} }
@Test @Test

View File

@ -20,6 +20,8 @@ import io.netty.handler.codec.DecoderException;
public final class DnsResponseException extends DecoderException { public final class DnsResponseException extends DecoderException {
private static final long serialVersionUID = -8519053051363525286L;
private final DnsResponseCode code; private final DnsResponseCode code;
public DnsResponseException(DnsResponseCode code) { public DnsResponseException(DnsResponseCode code) {

View File

@ -14,10 +14,6 @@
*/ */
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.UPGRADE;
import static io.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
import static io.netty.util.ReferenceCountUtil.release;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
@ -26,6 +22,10 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.util.ReferenceCountUtil.*;
/** /**
* Client-side handler for handling an HTTP upgrade handshake to another protocol. When the first * Client-side handler for handling an HTTP upgrade handshake to another protocol. When the first
* HTTP request is sent, this handler will add all appropriate headers to perform an upgrade to the * HTTP request is sent, this handler will add all appropriate headers to perform an upgrade to the
@ -71,7 +71,7 @@ public class HttpClientUpgradeHandler extends HttpObjectAggregator {
*/ */
public interface UpgradeCodec { public interface UpgradeCodec {
/** /**
* Returns the name of the protocol supported by this codec, as indicated by the {@link UPGRADE} header. * Returns the name of the protocol supported by this codec, as indicated by the {@code 'UPGRADE'} header.
*/ */
String protocol(); String protocol();
@ -207,7 +207,7 @@ public class HttpClientUpgradeHandler extends HttpObjectAggregator {
} }
} }
private void removeThisHandler(ChannelHandlerContext ctx) { private static void removeThisHandler(ChannelHandlerContext ctx) {
ctx.pipeline().remove(ctx.name()); ctx.pipeline().remove(ctx.name());
} }
@ -226,7 +226,7 @@ public class HttpClientUpgradeHandler extends HttpObjectAggregator {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (String part : connectionParts) { for (String part : connectionParts) {
builder.append(part); builder.append(part);
builder.append(","); builder.append(',');
} }
builder.append(UPGRADE); builder.append(UPGRADE);
request.headers().set(CONNECTION, builder.toString()); request.headers().set(CONNECTION, builder.toString());

View File

@ -124,6 +124,7 @@ public class HttpContentCompressor extends HttpContentEncoder {
wrapper, compressionLevel, windowBits, memLevel))); wrapper, compressionLevel, windowBits, memLevel)));
} }
@SuppressWarnings("FloatingPointEquality")
protected ZlibWrapper determineWrapper(CharSequence acceptEncoding) { protected ZlibWrapper determineWrapper(CharSequence acceptEncoding) {
float starQ = -1.0f; float starQ = -1.0f;
float gzipQ = -1.0f; float gzipQ = -1.0f;

View File

@ -24,6 +24,7 @@ import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.HttpObjectDecoder.State;
import io.netty.util.internal.AppendableCharSequence; import io.netty.util.internal.AppendableCharSequence;
import java.util.List; import java.util.List;
@ -101,7 +102,7 @@ import static io.netty.buffer.ByteBufUtil.*;
* To implement the decoder of such a derived protocol, extend this class and * To implement the decoder of such a derived protocol, extend this class and
* implement all abstract methods properly. * implement all abstract methods properly.
*/ */
public abstract class HttpObjectDecoder extends ReplayingDecoder<HttpObjectDecoder.State> { public abstract class HttpObjectDecoder extends ReplayingDecoder<State> {
private final int maxInitialLineLength; private final int maxInitialLineLength;
private final int maxHeaderSize; private final int maxHeaderSize;

View File

@ -267,7 +267,7 @@ public final class CorsConfig {
* @return {@link Builder} to support method chaining. * @return {@link Builder} to support method chaining.
*/ */
public static Builder withOrigin(final String origin) { public static Builder withOrigin(final String origin) {
if (origin.equals("*")) { if ("*".equals(origin)) {
return new Builder(); return new Builder();
} }
return new Builder(origin); return new Builder(origin);

View File

@ -22,8 +22,10 @@ import io.netty.util.internal.PlatformDependent;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
/** /**
* Default factory giving Attribute and FileUpload according to constructor * Default factory giving Attribute and FileUpload according to constructor
@ -145,7 +147,7 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
private static void checkHttpDataSize(HttpData data) { private static void checkHttpDataSize(HttpData data) {
try { try {
data.checkSize(data.length()); data.checkSize(data.length());
} catch (IOException e) { } catch (IOException ignored) {
throw new IllegalArgumentException("Attribute bigger than maxSize allowed"); throw new IllegalArgumentException("Attribute bigger than maxSize allowed");
} }
} }
@ -235,15 +237,18 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
@Override @Override
public void cleanAllHttpData() { public void cleanAllHttpData() {
for (HttpRequest request : requestFileDeleteMap.keySet()) { Iterator<Entry<HttpRequest, List<HttpData>>> i = requestFileDeleteMap.entrySet().iterator();
List<HttpData> fileToDelete = requestFileDeleteMap.get(request); while (i.hasNext()) {
Entry<HttpRequest, List<HttpData>> e = i.next();
i.remove();
List<HttpData> fileToDelete = e.getValue();
if (fileToDelete != null) { if (fileToDelete != null) {
for (HttpData data: fileToDelete) { for (HttpData data : fileToDelete) {
data.delete(); data.delete();
} }
fileToDelete.clear(); fileToDelete.clear();
} }
requestFileDeleteMap.remove(request);
} }
} }
} }

View File

@ -106,7 +106,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
/** /**
* Used in Multipart * Used in Multipart
*/ */
private Map<String, Attribute> currentFieldAttributes; private Map<CharSequence, Attribute> currentFieldAttributes;
/** /**
* The current FileUpload that is currently in decode process * The current FileUpload that is currently in decode process
@ -516,7 +516,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
// load data // load data
try { try {
loadFieldMultipart(multipartDataBoundary); loadFieldMultipart(multipartDataBoundary);
} catch (NotEnoughDataDecoderException e) { } catch (NotEnoughDataDecoderException ignored) {
return null; return null;
} }
Attribute finalAttribute = currentAttribute; Attribute finalAttribute = currentAttribute;
@ -561,7 +561,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e) { } catch (SeekAheadNoBackArrayException ignored) {
try { try {
skipControlCharactersStandard(); skipControlCharactersStandard();
} catch (IndexOutOfBoundsException e1) { } catch (IndexOutOfBoundsException e1) {
@ -608,7 +608,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
int readerIndex = undecodedChunk.readerIndex(); int readerIndex = undecodedChunk.readerIndex();
try { try {
skipControlCharacters(); skipControlCharacters();
} catch (NotEnoughDataDecoderException e1) { } catch (NotEnoughDataDecoderException ignored) {
undecodedChunk.readerIndex(readerIndex); undecodedChunk.readerIndex(readerIndex);
return null; return null;
} }
@ -616,7 +616,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
String newline; String newline;
try { try {
newline = readDelimiter(delimiter); newline = readDelimiter(delimiter);
} catch (NotEnoughDataDecoderException e) { } catch (NotEnoughDataDecoderException ignored) {
undecodedChunk.readerIndex(readerIndex); undecodedChunk.readerIndex(readerIndex);
return null; return null;
} }
@ -648,7 +648,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
private InterfaceHttpData findMultipartDisposition() { private InterfaceHttpData findMultipartDisposition() {
int readerIndex = undecodedChunk.readerIndex(); int readerIndex = undecodedChunk.readerIndex();
if (currentStatus == MultiPartStatus.DISPOSITION) { if (currentStatus == MultiPartStatus.DISPOSITION) {
currentFieldAttributes = new TreeMap<String, Attribute>(CaseIgnoringComparator.INSTANCE); currentFieldAttributes = new TreeMap<CharSequence, Attribute>(CaseIgnoringComparator.INSTANCE);
} }
// read many lines until empty line with newline found! Store all data // read many lines until empty line with newline found! Store all data
while (!skipOneLine()) { while (!skipOneLine()) {
@ -656,7 +656,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
try { try {
skipControlCharacters(); skipControlCharacters();
newline = readLine(); newline = readLine();
} catch (NotEnoughDataDecoderException e) { } catch (NotEnoughDataDecoderException ignored) {
undecodedChunk.readerIndex(readerIndex); undecodedChunk.readerIndex(readerIndex);
return null; return null;
} }
@ -842,7 +842,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L; size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L;
} catch (IOException e) { } catch (IOException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} catch (NumberFormatException e) { } catch (NumberFormatException ignored) {
size = 0; size = 0;
} }
try { try {
@ -991,7 +991,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e1) { } catch (SeekAheadNoBackArrayException ignored) {
return readLineStandard(); return readLineStandard();
} }
int readerIndex = undecodedChunk.readerIndex(); int readerIndex = undecodedChunk.readerIndex();
@ -1142,7 +1142,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e1) { } catch (SeekAheadNoBackArrayException ignored) {
return readDelimiterStandard(delimiter); return readDelimiterStandard(delimiter);
} }
int readerIndex = undecodedChunk.readerIndex(); int readerIndex = undecodedChunk.readerIndex();
@ -1371,7 +1371,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e1) { } catch (SeekAheadNoBackArrayException ignored) {
readFileUploadByteMultipartStandard(delimiter); readFileUploadByteMultipartStandard(delimiter);
return; return;
} }
@ -1592,7 +1592,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e1) { } catch (SeekAheadNoBackArrayException ignored) {
loadFieldMultipartStandard(delimiter); loadFieldMultipartStandard(delimiter);
return; return;
} }
@ -1699,6 +1699,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
* *
* @return the cleaned String * @return the cleaned String
*/ */
@SuppressWarnings("IfStatementWithIdenticalBranches")
private static String cleanString(String field) { private static String cleanString(String field) {
StringBuilder sb = new StringBuilder(field.length()); StringBuilder sb = new StringBuilder(field.length());
for (int i = 0; i < field.length(); i++) { for (int i = 0; i < field.length(); i++) {

View File

@ -156,7 +156,8 @@ public class HttpPostRequestDecoder implements InterfaceHttpPostRequestDecoder {
String[] headerContentType = splitHeaderContentType(contentType); String[] headerContentType = splitHeaderContentType(contentType);
if (headerContentType[0].toLowerCase().startsWith( if (headerContentType[0].toLowerCase().startsWith(
HttpHeaders.Values.MULTIPART_FORM_DATA.toString())) { HttpHeaders.Values.MULTIPART_FORM_DATA.toString())) {
int mrank = 1, crank = 2; int mrank;
int crank;
if (headerContentType[1].toLowerCase().startsWith( if (headerContentType[1].toLowerCase().startsWith(
HttpHeaders.Values.BOUNDARY.toString())) { HttpHeaders.Values.BOUNDARY.toString())) {
mrank = 1; mrank = 1;

View File

@ -511,7 +511,7 @@ public class HttpPostStandardRequestDecoder implements InterfaceHttpPostRequestD
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e1) { } catch (SeekAheadNoBackArrayException ignored) {
parseBodyAttributesStandard(); parseBodyAttributesStandard();
return; return;
} }
@ -659,11 +659,11 @@ public class HttpPostStandardRequestDecoder implements InterfaceHttpPostRequestD
SeekAheadOptimize sao; SeekAheadOptimize sao;
try { try {
sao = new SeekAheadOptimize(undecodedChunk); sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArrayException e) { } catch (SeekAheadNoBackArrayException ignored) {
try { try {
skipControlCharactersStandard(); skipControlCharactersStandard();
} catch (IndexOutOfBoundsException e1) { } catch (IndexOutOfBoundsException e) {
throw new NotEnoughDataDecoderException(e1); throw new NotEnoughDataDecoderException(e);
} }
return; return;
} }

View File

@ -55,7 +55,7 @@ public interface InterfaceHttpPostRequestDecoder {
* @throws HttpPostRequestDecoder.NotEnoughDataDecoderException * @throws HttpPostRequestDecoder.NotEnoughDataDecoderException
* Need more chunks * Need more chunks
*/ */
List<InterfaceHttpData> getBodyHttpDatas() throws HttpPostRequestDecoder.NotEnoughDataDecoderException; List<InterfaceHttpData> getBodyHttpDatas();
/** /**
* This getMethod returns a List of all HttpDatas with the given name from * This getMethod returns a List of all HttpDatas with the given name from
@ -68,7 +68,7 @@ public interface InterfaceHttpPostRequestDecoder {
* @throws HttpPostRequestDecoder.NotEnoughDataDecoderException * @throws HttpPostRequestDecoder.NotEnoughDataDecoderException
* need more chunks * need more chunks
*/ */
List<InterfaceHttpData> getBodyHttpDatas(String name) throws HttpPostRequestDecoder.NotEnoughDataDecoderException; List<InterfaceHttpData> getBodyHttpDatas(String name);
/** /**
* This getMethod returns the first InterfaceHttpData with the given name from * This getMethod returns the first InterfaceHttpData with the given name from
@ -82,7 +82,7 @@ public interface InterfaceHttpPostRequestDecoder {
* @throws HttpPostRequestDecoder.NotEnoughDataDecoderException * @throws HttpPostRequestDecoder.NotEnoughDataDecoderException
* need more chunks * need more chunks
*/ */
InterfaceHttpData getBodyHttpData(String name) throws HttpPostRequestDecoder.NotEnoughDataDecoderException; InterfaceHttpData getBodyHttpData(String name);
/** /**
* Initialized the internals from a new chunk * Initialized the internals from a new chunk
@ -93,8 +93,7 @@ public interface InterfaceHttpPostRequestDecoder {
* if there is a problem with the charset decoding or other * if there is a problem with the charset decoding or other
* errors * errors
*/ */
InterfaceHttpPostRequestDecoder offer(HttpContent content) InterfaceHttpPostRequestDecoder offer(HttpContent content);
throws HttpPostRequestDecoder.ErrorDataDecoderException;
/** /**
* True if at current getStatus, there is an available decoded * True if at current getStatus, there is an available decoded
@ -106,7 +105,7 @@ public interface InterfaceHttpPostRequestDecoder {
* @throws HttpPostRequestDecoder.EndOfDataDecoderException * @throws HttpPostRequestDecoder.EndOfDataDecoderException
* No more data will be available * No more data will be available
*/ */
boolean hasNext() throws HttpPostRequestDecoder.EndOfDataDecoderException; boolean hasNext();
/** /**
* Returns the next available InterfaceHttpData or null if, at the time it * Returns the next available InterfaceHttpData or null if, at the time it
@ -120,7 +119,7 @@ public interface InterfaceHttpPostRequestDecoder {
* @throws HttpPostRequestDecoder.EndOfDataDecoderException * @throws HttpPostRequestDecoder.EndOfDataDecoderException
* No more data will be available * No more data will be available
*/ */
InterfaceHttpData next() throws HttpPostRequestDecoder.EndOfDataDecoderException; InterfaceHttpData next();
/** /**
* Destroy the {@link InterfaceHttpPostRequestDecoder} and release all it resources. After this method * Destroy the {@link InterfaceHttpPostRequestDecoder} and release all it resources. After this method

View File

@ -17,7 +17,6 @@ package io.netty.handler.codec.rtsp;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
@ -26,7 +25,6 @@ import static io.netty.handler.codec.http.HttpConstants.*;
/** /**
* Encodes an RTSP response represented in {@link FullHttpResponse} into * Encodes an RTSP response represented in {@link FullHttpResponse} into
* a {@link ByteBuf}. * a {@link ByteBuf}.
*/ */
public class RtspResponseEncoder extends RtspObjectEncoder<HttpResponse> { public class RtspResponseEncoder extends RtspObjectEncoder<HttpResponse> {
private static final byte[] CRLF = { CR, LF }; private static final byte[] CRLF = { CR, LF };

View File

@ -33,11 +33,11 @@ public class SpdyHeaderBlockRawEncoder extends SpdyHeaderBlockEncoder {
this.version = version.getVersion(); this.version = version.getVersion();
} }
private void setLengthField(ByteBuf buffer, int writerIndex, int length) { private static void setLengthField(ByteBuf buffer, int writerIndex, int length) {
buffer.setInt(writerIndex, length); buffer.setInt(writerIndex, length);
} }
private void writeLengthField(ByteBuf buffer, int length) { private static void writeLengthField(ByteBuf buffer, int length) {
buffer.writeInt(length); buffer.writeInt(length);
} }

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.spdy;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import java.io.Serializable;
import java.util.Comparator; import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.Queue; import java.util.Queue;
@ -320,7 +321,10 @@ final class SpdySession {
} }
} }
private final class PriorityComparator implements Comparator<Integer> { private final class PriorityComparator implements Comparator<Integer>, Serializable {
private static final long serialVersionUID = 1161471649740544848L;
@Override @Override
public int compare(Integer id1, Integer id2) { public int compare(Integer id1, Integer id2) {
StreamState state1 = activeStreams.get(id1); StreamState state1 = activeStreams.get(id1);

View File

@ -15,8 +15,6 @@
*/ */
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.stream.ChunkedFile; import io.netty.handler.stream.ChunkedFile;
@ -25,6 +23,7 @@ import io.netty.handler.stream.ChunkedNioFile;
import io.netty.handler.stream.ChunkedNioStream; import io.netty.handler.stream.ChunkedNioStream;
import io.netty.handler.stream.ChunkedStream; import io.netty.handler.stream.ChunkedStream;
import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.stream.ChunkedWriteHandler;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
@ -32,7 +31,7 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import org.junit.Test; import static org.junit.Assert.*;
public class HttpChunkedInputTest { public class HttpChunkedInputTest {
private static final byte[] BYTES = new byte[1024 * 64]; private static final byte[] BYTES = new byte[1024 * 64];
@ -119,6 +118,6 @@ public class HttpChunkedInputTest {
} }
assertEquals(BYTES.length * inputs.length, read); assertEquals(BYTES.length * inputs.length, read);
assertTrue("Last chunk must be DefaultLastHttpContent", lastHttpContent == LastHttpContent.EMPTY_LAST_CONTENT); assertSame("Last chunk must be DefaultLastHttpContent", LastHttpContent.EMPTY_LAST_CONTENT, lastHttpContent);
} }
} }

View File

@ -15,11 +15,12 @@
*/ */
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import org.junit.Test;
import java.text.ParseException; import java.text.ParseException;
import java.util.Date; import java.util.Date;
import org.junit.Assert; import static org.junit.Assert.*;
import org.junit.Test;
public class HttpHeaderDateFormatTest { public class HttpHeaderDateFormatTest {
/** /**
@ -35,28 +36,24 @@ public class HttpHeaderDateFormatTest {
HttpHeaderDateFormat format = HttpHeaderDateFormat.get(); HttpHeaderDateFormat format = HttpHeaderDateFormat.get();
final Date parsedDateWithSingleDigitDay = format.parse("Sun, 6 Nov 1994 08:49:37 GMT"); final Date parsedDateWithSingleDigitDay = format.parse("Sun, 6 Nov 1994 08:49:37 GMT");
Assert.assertNotNull(parsedDateWithSingleDigitDay); assertNotNull(parsedDateWithSingleDigitDay);
Assert.assertEquals(DATE, parsedDateWithSingleDigitDay); assertEquals(DATE, parsedDateWithSingleDigitDay);
final Date parsedDateWithDoubleDigitDay = format.parse("Sun, 06 Nov 1994 08:49:37 GMT"); final Date parsedDateWithDoubleDigitDay = format.parse("Sun, 06 Nov 1994 08:49:37 GMT");
Assert.assertNotNull(parsedDateWithDoubleDigitDay); assertNotNull(parsedDateWithDoubleDigitDay);
Assert.assertEquals(DATE, parsedDateWithDoubleDigitDay); assertEquals(DATE, parsedDateWithDoubleDigitDay);
final Date parsedDateWithDashSeparatorSingleDigitDay = format.parse("Sunday, 06-Nov-94 08:49:37 GMT"); final Date parsedDateWithDashSeparatorSingleDigitDay = format.parse("Sunday, 06-Nov-94 08:49:37 GMT");
Assert.assertNotNull(parsedDateWithDashSeparatorSingleDigitDay); assertNotNull(parsedDateWithDashSeparatorSingleDigitDay);
Assert.assertEquals(DATE, parsedDateWithDashSeparatorSingleDigitDay); assertEquals(DATE, parsedDateWithDashSeparatorSingleDigitDay);
final Date parsedDateWithSingleDoubleDigitDay = format.parse("Sunday, 6-Nov-94 08:49:37 GMT"); final Date parsedDateWithSingleDoubleDigitDay = format.parse("Sunday, 6-Nov-94 08:49:37 GMT");
Assert.assertNotNull(parsedDateWithSingleDoubleDigitDay); assertNotNull(parsedDateWithSingleDoubleDigitDay);
Assert.assertEquals(DATE, parsedDateWithSingleDoubleDigitDay); assertEquals(DATE, parsedDateWithSingleDoubleDigitDay);
final Date parsedDateWithoutGMT = format.parse("Sun Nov 6 08:49:37 1994"); final Date parsedDateWithoutGMT = format.parse("Sun Nov 6 08:49:37 1994");
Assert.assertNotNull(parsedDateWithoutGMT); assertNotNull(parsedDateWithoutGMT);
Assert.assertEquals(DATE, parsedDateWithoutGMT); assertEquals(DATE, parsedDateWithoutGMT);
}
private Date parseDate(HttpHeaderDateFormat dateFormat, String dateStr) throws ParseException {
return dateFormat.parse(dateStr);
} }
@Test @Test
@ -64,7 +61,7 @@ public class HttpHeaderDateFormatTest {
HttpHeaderDateFormat format = HttpHeaderDateFormat.get(); HttpHeaderDateFormat format = HttpHeaderDateFormat.get();
final String formatted = format.format(DATE); final String formatted = format.format(DATE);
Assert.assertNotNull(formatted); assertNotNull(formatted);
Assert.assertEquals("Sun, 06 Nov 1994 08:49:37 GMT", formatted); assertEquals("Sun, 06 Nov 1994 08:49:37 GMT", formatted);
} }
} }

View File

@ -20,6 +20,7 @@ import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.DecoderResultProvider;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
@ -308,7 +309,7 @@ public class HttpObjectAggregatorTest {
ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0 with extra\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0 with extra\r\n", CharsetUtil.UTF_8));
Object inbound = ch.readInbound(); Object inbound = ch.readInbound();
assertThat(inbound, is(instanceOf(FullHttpRequest.class))); assertThat(inbound, is(instanceOf(FullHttpRequest.class)));
assertTrue(((FullHttpRequest) inbound).decoderResult().isFailure()); assertTrue(((DecoderResultProvider) inbound).decoderResult().isFailure());
assertNull(ch.readInbound()); assertNull(ch.readInbound());
ch.finish(); ch.finish();
} }
@ -319,7 +320,7 @@ public class HttpObjectAggregatorTest {
ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.0 BAD_CODE Bad Server\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.0 BAD_CODE Bad Server\r\n", CharsetUtil.UTF_8));
Object inbound = ch.readInbound(); Object inbound = ch.readInbound();
assertThat(inbound, is(instanceOf(FullHttpResponse.class))); assertThat(inbound, is(instanceOf(FullHttpResponse.class)));
assertTrue(((FullHttpResponse) inbound).decoderResult().isFailure()); assertTrue(((DecoderResultProvider) inbound).decoderResult().isFailure());
assertNull(ch.readInbound()); assertNull(ch.readInbound());
ch.finish(); ch.finish();
} }

View File

@ -136,7 +136,6 @@ public class HttpRequestDecoderTest {
} }
// if header is done it should produce a HttpRequest // if header is done it should produce a HttpRequest
boolean headerDone = a + amount == headerLength;
channel.writeInbound(Unpooled.wrappedBuffer(content, a, amount)); channel.writeInbound(Unpooled.wrappedBuffer(content, a, amount));
a += amount; a += amount;
} }

View File

@ -47,7 +47,7 @@ public class HttpResponseEncoderTest {
buffer.release(); buffer.release();
FileRegion region = channel.readOutbound(); FileRegion region = channel.readOutbound();
assertSame(region, FILE_REGION); assertSame(FILE_REGION, region);
region.release(); region.release();
buffer = channel.readOutbound(); buffer = channel.readOutbound();
assertEquals("\r\n", buffer.toString(CharsetUtil.US_ASCII)); assertEquals("\r\n", buffer.toString(CharsetUtil.US_ASCII));

View File

@ -78,7 +78,7 @@ public class CorsHandlerTest {
@Test @Test
public void preflightDeleteRequestWithCustomHeaders() { public void preflightDeleteRequestWithCustomHeaders() {
final CorsConfig config = CorsConfig.withOrigin("http://localhost:8888") final CorsConfig config = CorsConfig.withOrigin("http://localhost:8888")
.allowedRequestMethods(HttpMethod.GET, HttpMethod.DELETE) .allowedRequestMethods(GET, DELETE)
.build(); .build();
final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1"); final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1");
assertThat(response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN), is("http://localhost:8888")); assertThat(response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN), is("http://localhost:8888"));
@ -89,7 +89,7 @@ public class CorsHandlerTest {
@Test @Test
public void preflightGetRequestWithCustomHeaders() { public void preflightGetRequestWithCustomHeaders() {
final CorsConfig config = CorsConfig.withOrigin("http://localhost:8888") final CorsConfig config = CorsConfig.withOrigin("http://localhost:8888")
.allowedRequestMethods(HttpMethod.OPTIONS, HttpMethod.GET, HttpMethod.DELETE) .allowedRequestMethods(OPTIONS, GET, DELETE)
.allowedRequestHeaders("content-type", "xheader1") .allowedRequestHeaders("content-type", "xheader1")
.build(); .build();
final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1"); final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1");

View File

@ -172,7 +172,7 @@ public class SpdySessionHandlerTest {
// a RST_STREAM frame for that Stream-ID // a RST_STREAM frame for that Stream-ID
sessionHandler.writeInbound(new DefaultSpdyRstStreamFrame(remoteStreamId, 3)); sessionHandler.writeInbound(new DefaultSpdyRstStreamFrame(remoteStreamId, 3));
assertNull(sessionHandler.readOutbound()); assertNull(sessionHandler.readOutbound());
remoteStreamId += 2; //remoteStreamId += 2;
// Check if session handler honors UNIDIRECTIONAL streams // Check if session handler honors UNIDIRECTIONAL streams
spdySynStreamFrame.setLast(false); spdySynStreamFrame.setLast(false);

View File

@ -116,8 +116,7 @@ public abstract class AbstractHttp2ConnectionHandler extends ByteToMessageDecode
} }
// Create a local stream used for the HTTP cleartext upgrade. // Create a local stream used for the HTTP cleartext upgrade.
createLocalStream(HTTP_UPGRADE_STREAM_ID, true createLocalStream(HTTP_UPGRADE_STREAM_ID, true);
);
} }
/** /**
@ -138,8 +137,7 @@ public abstract class AbstractHttp2ConnectionHandler extends ByteToMessageDecode
applyRemoteSettings(settings); applyRemoteSettings(settings);
// Create a stream in the half-closed state. // Create a stream in the half-closed state.
createRemoteStream(HTTP_UPGRADE_STREAM_ID, true createRemoteStream(HTTP_UPGRADE_STREAM_ID, true);
);
} }
@Override @Override

View File

@ -15,24 +15,14 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2CodecUtil.FRAME_HEADER_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.FRAME_LENGTH_MASK;
import static io.netty.handler.codec.http2.Http2CodecUtil.INT_FIELD_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_FRAME_PAYLOAD_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.PRIORITY_ENTRY_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.SETTINGS_COMPRESS_DATA;
import static io.netty.handler.codec.http2.Http2CodecUtil.SETTINGS_ENABLE_PUSH;
import static io.netty.handler.codec.http2.Http2CodecUtil.SETTINGS_HEADER_TABLE_SIZE;
import static io.netty.handler.codec.http2.Http2CodecUtil.SETTINGS_INITIAL_WINDOW_SIZE;
import static io.netty.handler.codec.http2.Http2CodecUtil.SETTINGS_MAX_CONCURRENT_STREAMS;
import static io.netty.handler.codec.http2.Http2CodecUtil.SETTING_ENTRY_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.readUnsignedInt;
import static io.netty.handler.codec.http2.Http2Exception.protocolError;
import static io.netty.util.CharsetUtil.UTF_8;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static io.netty.handler.codec.http2.Http2Exception.*;
import static io.netty.util.CharsetUtil.*;
/** /**
* A {@link Http2FrameReader} that supports all frame types defined by the HTTP/2 specification. * A {@link Http2FrameReader} that supports all frame types defined by the HTTP/2 specification.
*/ */

View File

@ -15,27 +15,15 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2CodecUtil.FRAME_HEADER_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.INT_FIELD_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_FRAME_PAYLOAD_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_UNSIGNED_BYTE;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_UNSIGNED_INT;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_UNSIGNED_SHORT;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_WEIGHT;
import static io.netty.handler.codec.http2.Http2CodecUtil.MIN_WEIGHT;
import static io.netty.handler.codec.http2.Http2CodecUtil.PRIORITY_ENTRY_LENGTH;
import static io.netty.handler.codec.http2.Http2CodecUtil.calcSettingsPayloadLength;
import static io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeader;
import static io.netty.handler.codec.http2.Http2CodecUtil.writeSettingsPayload;
import static io.netty.handler.codec.http2.Http2CodecUtil.writeUnsignedInt;
import static io.netty.handler.codec.http2.Http2CodecUtil.writeUnsignedShort;
import static io.netty.util.CharsetUtil.UTF_8;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.CompositeByteBuf;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static io.netty.util.CharsetUtil.*;
/** /**
* A {@link Http2FrameWriter} that supports all frame types defined by the HTTP/2 specification. * A {@link Http2FrameWriter} that supports all frame types defined by the HTTP/2 specification.
*/ */
@ -125,7 +113,7 @@ public class DefaultHttp2FrameWriter implements Http2FrameWriter {
ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + PRIORITY_ENTRY_LENGTH); ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + PRIORITY_ENTRY_LENGTH);
writeFrameHeader(frame, PRIORITY_ENTRY_LENGTH, Http2FrameType.PRIORITY, writeFrameHeader(frame, PRIORITY_ENTRY_LENGTH, Http2FrameType.PRIORITY,
Http2Flags.EMPTY, streamId); Http2Flags.EMPTY, streamId);
long word1 = exclusive ? (0x80000000L | streamDependency) : streamDependency; long word1 = exclusive ? 0x80000000L | streamDependency : streamDependency;
writeUnsignedInt(word1, frame); writeUnsignedInt(word1, frame);
// Adjust the weight so that it fits into a single byte on the wire. // Adjust the weight so that it fits into a single byte on the wire.
@ -381,7 +369,7 @@ public class DefaultHttp2FrameWriter implements Http2FrameWriter {
// Write the priority. // Write the priority.
if (hasPriority) { if (hasPriority) {
long word1 = exclusive ? (0x80000000L | streamDependency) : streamDependency; long word1 = exclusive ? 0x80000000L | streamDependency : streamDependency;
writeUnsignedInt(word1, firstFrame); writeUnsignedInt(word1, firstFrame);
// Adjust the weight so that it fits into a single byte on the wire. // Adjust the weight so that it fits into a single byte on the wire.

View File

@ -14,13 +14,6 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.base64.Base64Dialect.URL_SAFE;
import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME;
import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER;
import static io.netty.handler.codec.http2.Http2CodecUtil.calcSettingsPayloadLength;
import static io.netty.handler.codec.http2.Http2CodecUtil.writeSettingsPayload;
import static io.netty.util.CharsetUtil.UTF_8;
import static io.netty.util.ReferenceCountUtil.release;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.base64.Base64;
@ -28,18 +21,22 @@ import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientUpgradeHandler; import io.netty.handler.codec.http.HttpClientUpgradeHandler;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static io.netty.handler.codec.base64.Base64Dialect.*;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static io.netty.util.CharsetUtil.*;
import static io.netty.util.ReferenceCountUtil.*;
/** /**
* Client-side cleartext upgrade codec from HTTP to HTTP/2. * Client-side cleartext upgrade codec from HTTP to HTTP/2.
*/ */
public class Http2ClientUpgradeCodec implements HttpClientUpgradeHandler.UpgradeCodec { public class Http2ClientUpgradeCodec implements HttpClientUpgradeHandler.UpgradeCodec {
private static final List<String> UPGRADE_HEADERS = Collections.unmodifiableList(Arrays private static final List<String> UPGRADE_HEADERS = Collections.singletonList(HTTP_UPGRADE_SETTINGS_HEADER);
.asList(HTTP_UPGRADE_SETTINGS_HEADER));
private final String handlerName; private final String handlerName;
private final AbstractHttp2ConnectionHandler connectionHandler; private final AbstractHttp2ConnectionHandler connectionHandler;

View File

@ -15,19 +15,21 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;
import static io.netty.handler.codec.http2.Http2Exception.format;
import static io.netty.util.CharsetUtil.UTF_8;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.Http2StreamRemovalPolicy.Action; import io.netty.handler.codec.http2.Http2StreamRemovalPolicy.Action;
import static io.netty.handler.codec.http2.Http2Error.*;
import static io.netty.handler.codec.http2.Http2Exception.*;
import static io.netty.util.CharsetUtil.*;
/** /**
* Constants and utility method used for encoding/decoding HTTP2 frames. * Constants and utility method used for encoding/decoding HTTP2 frames.
*/ */
public final class Http2CodecUtil { public final class Http2CodecUtil {
private static final byte[] CONNECTION_PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(UTF_8); private static final byte[] CONNECTION_PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(UTF_8);
private static final byte[] EMPTY_PING = new byte[8]; private static final byte[] EMPTY_PING = new byte[8];
@ -46,8 +48,8 @@ public final class Http2CodecUtil {
public static final int SETTING_ENTRY_LENGTH = 5; public static final int SETTING_ENTRY_LENGTH = 5;
public static final int PRIORITY_ENTRY_LENGTH = 5; public static final int PRIORITY_ENTRY_LENGTH = 5;
public static final int INT_FIELD_LENGTH = 4; public static final int INT_FIELD_LENGTH = 4;
public static final short MAX_WEIGHT = (short) 256; public static final short MAX_WEIGHT = 256;
public static final short MIN_WEIGHT = (short) 1; public static final short MIN_WEIGHT = 1;
public static final short SETTINGS_HEADER_TABLE_SIZE = 1; public static final short SETTINGS_HEADER_TABLE_SIZE = 1;
public static final short SETTINGS_ENABLE_PUSH = 2; public static final short SETTINGS_ENABLE_PUSH = 2;
@ -144,18 +146,18 @@ public final class Http2CodecUtil {
* Writes a big-endian (32-bit) unsigned integer to the buffer. * Writes a big-endian (32-bit) unsigned integer to the buffer.
*/ */
public static void writeUnsignedInt(long value, ByteBuf out) { public static void writeUnsignedInt(long value, ByteBuf out) {
out.writeByte((int) ((value >> 24) & 0xFF)); out.writeByte((int) (value >> 24 & 0xFF));
out.writeByte((int) ((value >> 16) & 0xFF)); out.writeByte((int) (value >> 16 & 0xFF));
out.writeByte((int) ((value >> 8) & 0xFF)); out.writeByte((int) (value >> 8 & 0xFF));
out.writeByte((int) ((value & 0xFF))); out.writeByte((int) (value & 0xFF));
} }
/** /**
* Writes a big-endian (16-bit) unsigned integer to the buffer. * Writes a big-endian (16-bit) unsigned integer to the buffer.
*/ */
public static void writeUnsignedShort(int value, ByteBuf out) { public static void writeUnsignedShort(int value, ByteBuf out) {
out.writeByte((int) ((value >> 8) & 0xFF)); out.writeByte(value >> 8 & 0xFF);
out.writeByte((int) ((value & 0xFF))); out.writeByte(value & 0xFF);
} }
/** /**

View File

@ -163,11 +163,8 @@ public class Http2Flags {
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
Http2Flags other = (Http2Flags) obj;
if (value != other.value) { return value == ((Http2Flags) obj).value;
return false;
}
return true;
} }
@Override @Override
@ -195,7 +192,7 @@ public class Http2Flags {
if (padLowPresent()) { if (padLowPresent()) {
builder.append("PAD_LOW,"); builder.append("PAD_LOW,");
} }
builder.append(")"); builder.append(')');
return builder.toString(); return builder.toString();
} }

View File

@ -232,11 +232,11 @@ public abstract class Http2Headers implements Iterable<Entry<String, String>> {
StringBuilder builder = new StringBuilder("Http2Headers["); StringBuilder builder = new StringBuilder("Http2Headers[");
for (Map.Entry<String, String> header : this) { for (Map.Entry<String, String> header : this) {
builder.append(header.getKey()); builder.append(header.getKey());
builder.append(":"); builder.append(':');
builder.append(header.getValue()); builder.append(header.getValue());
builder.append(","); builder.append(',');
} }
builder.append("]"); builder.append(']');
return builder.toString(); return builder.toString();
} }
} }

View File

@ -14,13 +14,6 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.base64.Base64Dialect.URL_SAFE;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME;
import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER;
import static io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeader;
import static io.netty.handler.codec.http2.Http2Flags.EMPTY;
import static io.netty.handler.codec.http2.Http2FrameType.SETTINGS;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
@ -30,18 +23,24 @@ import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpServerUpgradeHandler; import io.netty.handler.codec.http.HttpServerUpgradeHandler;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static io.netty.handler.codec.base64.Base64Dialect.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static io.netty.handler.codec.http2.Http2Flags.*;
import static io.netty.handler.codec.http2.Http2FrameType.*;
/** /**
* Server-side codec for performing a cleartext upgrade from HTTP/1.x to HTTP/2. * Server-side codec for performing a cleartext upgrade from HTTP/1.x to HTTP/2.
*/ */
public class Http2ServerUpgradeCodec implements HttpServerUpgradeHandler.UpgradeCodec { public class Http2ServerUpgradeCodec implements HttpServerUpgradeHandler.UpgradeCodec {
private static final List<String> REQUIRED_UPGRADE_HEADERS = Collections private static final List<String> REQUIRED_UPGRADE_HEADERS =
.unmodifiableList(Arrays.asList(HTTP_UPGRADE_SETTINGS_HEADER)); Collections.singletonList(HTTP_UPGRADE_SETTINGS_HEADER);
private final String handlerName; private final String handlerName;
private final AbstractHttp2ConnectionHandler connectionHandler; private final AbstractHttp2ConnectionHandler connectionHandler;
private final Http2FrameReader frameReader; private final Http2FrameReader frameReader;
@ -73,7 +72,7 @@ public class Http2ServerUpgradeCodec implements HttpServerUpgradeHandler.Upgrade
} }
this.handlerName = handlerName; this.handlerName = handlerName;
this.connectionHandler = connectionHandler; this.connectionHandler = connectionHandler;
this.frameReader = new DefaultHttp2FrameReader(); frameReader = new DefaultHttp2FrameReader();
} }
@Override @Override
@ -139,8 +138,7 @@ public class Http2ServerUpgradeCodec implements HttpServerUpgradeHandler.Upgrade
final Http2Settings decodedSettings = new Http2Settings(); final Http2Settings decodedSettings = new Http2Settings();
frameReader.readFrame(ctx, frame, new Http2FrameAdapter() { frameReader.readFrame(ctx, frame, new Http2FrameAdapter() {
@Override @Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
throws Http2Exception {
decodedSettings.copy(settings); decodedSettings.copy(settings);
} }
}); });
@ -154,8 +152,7 @@ public class Http2ServerUpgradeCodec implements HttpServerUpgradeHandler.Upgrade
* Creates an HTTP2-Settings header with the given payload. The payload buffer is released. * Creates an HTTP2-Settings header with the given payload. The payload buffer is released.
*/ */
private static ByteBuf createSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload) { private static ByteBuf createSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload) {
ByteBuf frame = ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + payload.readableBytes());
ctx.alloc().buffer(Http2CodecUtil.FRAME_HEADER_LENGTH + payload.readableBytes());
writeFrameHeader(frame, payload.readableBytes(), SETTINGS, EMPTY, 0); writeFrameHeader(frame, payload.readableBytes(), SETTINGS, EMPTY, 0);
frame.writeBytes(payload); frame.writeBytes(payload);
payload.release(); payload.release();

View File

@ -187,12 +187,12 @@ public class Http2Settings {
* @return this object. * @return this object.
*/ */
public Http2Settings copy(Http2Settings source) { public Http2Settings copy(Http2Settings source) {
this.enabled = source.enabled; enabled = source.enabled;
this.allowCompressedData = source.allowCompressedData; allowCompressedData = source.allowCompressedData;
this.initialWindowSize = source.initialWindowSize; initialWindowSize = source.initialWindowSize;
this.maxConcurrentStreams = source.maxConcurrentStreams; maxConcurrentStreams = source.maxConcurrentStreams;
this.maxHeaderTableSize = source.maxHeaderTableSize; maxHeaderTableSize = source.maxHeaderTableSize;
this.pushEnabled = source.pushEnabled; pushEnabled = source.pushEnabled;
return this; return this;
} }
@ -236,31 +236,29 @@ public class Http2Settings {
if (maxConcurrentStreams != other.maxConcurrentStreams) { if (maxConcurrentStreams != other.maxConcurrentStreams) {
return false; return false;
} }
if (pushEnabled != other.pushEnabled) {
return false; return pushEnabled == other.pushEnabled;
}
return true;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder("Http2Settings ["); StringBuilder builder = new StringBuilder("Http2Settings [");
if (hasMaxHeaderTableSize()) { if (hasMaxHeaderTableSize()) {
builder.append("maxHeaderTableSize=").append(maxHeaderTableSize).append(","); builder.append("maxHeaderTableSize=").append(maxHeaderTableSize).append(',');
} }
if (hasPushEnabled()) { if (hasPushEnabled()) {
builder.append("pushEnabled=").append(pushEnabled).append(","); builder.append("pushEnabled=").append(pushEnabled).append(',');
} }
if (hasMaxConcurrentStreams()) { if (hasMaxConcurrentStreams()) {
builder.append("maxConcurrentStreams=").append(maxConcurrentStreams).append(","); builder.append("maxConcurrentStreams=").append(maxConcurrentStreams).append(',');
} }
if (hasInitialWindowSize()) { if (hasInitialWindowSize()) {
builder.append("initialWindowSize=").append(initialWindowSize).append(","); builder.append("initialWindowSize=").append(initialWindowSize).append(',');
} }
if (hasAllowCompressedData()) { if (hasAllowCompressedData()) {
builder.append("allowCompressedData=").append(allowCompressedData).append(","); builder.append("allowCompressedData=").append(allowCompressedData).append(',');
} }
builder.append("]"); builder.append(']');
return builder.toString(); return builder.toString();
} }

View File

@ -15,8 +15,7 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
/** /**
* A policy for determining when it is appropriate to remove streams from a * A policy for determining when it is appropriate to remove streams from an HTTP/2 stream registry.
* {@link Http2StreamRegistry}.
*/ */
public interface Http2StreamRemovalPolicy { public interface Http2StreamRemovalPolicy {

View File

@ -30,8 +30,6 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import static io.netty.handler.codec.http2.Http2CodecUtil.*; import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**

View File

@ -15,9 +15,7 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static org.junit.Assert.assertEquals; import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
@ -26,7 +24,7 @@ import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import org.junit.Test; import static org.junit.Assert.*;
/** /**
@ -73,7 +71,7 @@ public class DefaultHttp2HeadersTest {
// Now iterate through the headers, removing them from the original set. // Now iterate through the headers, removing them from the original set.
for (Map.Entry<String, String> entry : builder.build()) { for (Map.Entry<String, String> entry : builder.build()) {
assertTrue(headers.remove(entry.getKey() + ":" + entry.getValue())); assertTrue(headers.remove(entry.getKey() + ':' + entry.getValue()));
} }
// Make sure we removed them all. // Make sure we removed them all.

View File

@ -15,22 +15,17 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_FLOW_CONTROL_WINDOW_SIZE;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http2.Http2InboundFlowController.FrameWriter; import io.netty.handler.codec.http2.Http2InboundFlowController.FrameWriter;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static org.mockito.Mockito.*;
/** /**
* Tests for {@link DefaultHttp2InboundFlowController}. * Tests for {@link DefaultHttp2InboundFlowController}.
*/ */
@ -70,7 +65,7 @@ public class DefaultHttp2InboundFlowControllerTest {
@Test @Test
public void halfWindowRemainingShouldUpdateConnectionWindow() throws Http2Exception { public void halfWindowRemainingShouldUpdateConnectionWindow() throws Http2Exception {
int dataSize = (DEFAULT_FLOW_CONTROL_WINDOW_SIZE / 2) + 1; int dataSize = DEFAULT_FLOW_CONTROL_WINDOW_SIZE / 2 + 1;
int newWindow = DEFAULT_FLOW_CONTROL_WINDOW_SIZE - dataSize; int newWindow = DEFAULT_FLOW_CONTROL_WINDOW_SIZE - dataSize;
int windowDelta = DEFAULT_FLOW_CONTROL_WINDOW_SIZE - newWindow; int windowDelta = DEFAULT_FLOW_CONTROL_WINDOW_SIZE - newWindow;
@ -81,7 +76,7 @@ public class DefaultHttp2InboundFlowControllerTest {
@Test @Test
public void halfWindowRemainingShouldUpdateAllWindows() throws Http2Exception { public void halfWindowRemainingShouldUpdateAllWindows() throws Http2Exception {
int dataSize = (DEFAULT_FLOW_CONTROL_WINDOW_SIZE / 2) + 1; int dataSize = DEFAULT_FLOW_CONTROL_WINDOW_SIZE / 2 + 1;
int initialWindowSize = DEFAULT_FLOW_CONTROL_WINDOW_SIZE; int initialWindowSize = DEFAULT_FLOW_CONTROL_WINDOW_SIZE;
int windowDelta = getWindowDelta(initialWindowSize, initialWindowSize, dataSize); int windowDelta = getWindowDelta(initialWindowSize, initialWindowSize, dataSize);
@ -102,7 +97,7 @@ public class DefaultHttp2InboundFlowControllerTest {
controller.initialInboundWindowSize(newInitialWindowSize); controller.initialInboundWindowSize(newInitialWindowSize);
// Clear any previous calls to the writer. // Clear any previous calls to the writer.
Mockito.reset(frameWriter); reset(frameWriter);
// Send the next frame and verify that the expected window updates were sent. // Send the next frame and verify that the expected window updates were sent.
applyFlowControl(initialWindowSize, false); applyFlowControl(initialWindowSize, false);

View File

@ -15,27 +15,19 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_FLOW_CONTROL_WINDOW_SIZE;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http2.Http2OutboundFlowController.FrameWriter; import io.netty.handler.codec.http2.Http2OutboundFlowController.FrameWriter;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** /**
* Tests for {@link DefaultHttp2OutboundFlowController}. * Tests for {@link DefaultHttp2OutboundFlowController}.
*/ */
@ -536,18 +528,12 @@ public class DefaultHttp2OutboundFlowControllerTest {
captureWrite(STREAM_A, captor, false); captureWrite(STREAM_A, captor, false);
int aWritten = captor.getValue().readableBytes(); int aWritten = captor.getValue().readableBytes();
int min = aWritten;
int max = aWritten;
captureWrite(STREAM_B, captor, false); captureWrite(STREAM_B, captor, false);
int bWritten = captor.getValue().readableBytes(); int bWritten = captor.getValue().readableBytes();
min = Math.min(min, bWritten);
max = Math.max(max, bWritten);
captureWrite(STREAM_D, captor, false); captureWrite(STREAM_D, captor, false);
int dWritten = captor.getValue().readableBytes(); int dWritten = captor.getValue().readableBytes();
min = Math.min(min, dWritten);
max = Math.max(max, dWritten);
assertEquals(999, aWritten + bWritten + dWritten); assertEquals(999, aWritten + bWritten + dWritten);
assertEquals(333, aWritten); assertEquals(333, aWritten);
@ -579,7 +565,7 @@ public class DefaultHttp2OutboundFlowControllerTest {
connection.stream(stream).setPriority(parent, (short) weight, exclusive); connection.stream(stream).setPriority(parent, (short) weight, exclusive);
} }
private ByteBuf dummyData(int size) { private static ByteBuf dummyData(int size) {
ByteBuf buffer = Unpooled.buffer(size); ByteBuf buffer = Unpooled.buffer(size);
buffer.writerIndex(size); buffer.writerIndex(size);
return buffer; return buffer;

View File

@ -15,52 +15,32 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;
import static io.netty.handler.codec.http2.Http2CodecUtil.connectionPrefaceBuf;
import static io.netty.handler.codec.http2.Http2CodecUtil.emptyPingBuf;
import static io.netty.handler.codec.http2.Http2Error.NO_ERROR;
import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
import static io.netty.handler.codec.http2.Http2Exception.protocolError;
import static io.netty.handler.codec.http2.Http2Headers.EMPTY_HEADERS;
import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_LOCAL;
import static io.netty.handler.codec.http2.Http2Stream.State.OPEN;
import static io.netty.handler.codec.http2.Http2Stream.State.RESERVED_LOCAL;
import static io.netty.handler.codec.http2.Http2Stream.State.RESERVED_REMOTE;
import static io.netty.util.CharsetUtil.UTF_8;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import java.util.Arrays;
import java.util.Collections;
import io.netty.channel.DefaultChannelPromise; import io.netty.channel.DefaultChannelPromise;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import java.util.Collections;
import static io.netty.buffer.Unpooled.*;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static io.netty.handler.codec.http2.Http2Error.*;
import static io.netty.handler.codec.http2.Http2Exception.*;
import static io.netty.handler.codec.http2.Http2Headers.*;
import static io.netty.handler.codec.http2.Http2Stream.State.*;
import static io.netty.util.CharsetUtil.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** /**
* Tests for {@link DelegatingHttp2ConnectionHandlerTest} and its base class * Tests for {@link DelegatingHttp2ConnectionHandlerTest} and its base class
* {@link AbstractHttp2ConnectionHandler}. * {@link AbstractHttp2ConnectionHandler}.
@ -122,7 +102,7 @@ public class DelegatingHttp2ConnectionHandlerTest {
when(stream.id()).thenReturn(STREAM_ID); when(stream.id()).thenReturn(STREAM_ID);
when(stream.state()).thenReturn(OPEN); when(stream.state()).thenReturn(OPEN);
when(pushStream.id()).thenReturn(PUSH_STREAM_ID); when(pushStream.id()).thenReturn(PUSH_STREAM_ID);
when(connection.activeStreams()).thenReturn(Arrays.asList(stream)); when(connection.activeStreams()).thenReturn(Collections.singletonList(stream));
when(connection.stream(STREAM_ID)).thenReturn(stream); when(connection.stream(STREAM_ID)).thenReturn(stream);
when(connection.requireStream(STREAM_ID)).thenReturn(stream); when(connection.requireStream(STREAM_ID)).thenReturn(stream);
when(connection.local()).thenReturn(local); when(connection.local()).thenReturn(local);
@ -197,13 +177,13 @@ public class DelegatingHttp2ConnectionHandlerTest {
when(connection.isServer()).thenReturn(true); when(connection.isServer()).thenReturn(true);
handler = new DelegatingHttp2ConnectionHandler(connection, reader, writer, inboundFlow, handler = new DelegatingHttp2ConnectionHandler(connection, reader, writer, inboundFlow,
outboundFlow, observer); outboundFlow, observer);
handler.channelRead(ctx, Unpooled.copiedBuffer("BAD_PREFACE", UTF_8)); handler.channelRead(ctx, copiedBuffer("BAD_PREFACE", UTF_8));
verify(ctx).close(); verify(ctx).close();
} }
@Test @Test
public void serverReceivingValidClientPrefaceStringShouldContinueReadingFrames() throws Exception { public void serverReceivingValidClientPrefaceStringShouldContinueReadingFrames() throws Exception {
Mockito.reset(observer); reset(observer);
when(connection.isServer()).thenReturn(true); when(connection.isServer()).thenReturn(true);
handler = new DelegatingHttp2ConnectionHandler(connection, reader, writer, inboundFlow, handler = new DelegatingHttp2ConnectionHandler(connection, reader, writer, inboundFlow,
outboundFlow, observer); outboundFlow, observer);
@ -464,7 +444,7 @@ public class DelegatingHttp2ConnectionHandlerTest {
@Test(expected = Http2Exception.class) @Test(expected = Http2Exception.class)
public void serverAltSvcReadShouldThrow() throws Exception { public void serverAltSvcReadShouldThrow() throws Exception {
when(connection.isServer()).thenReturn(true); when(connection.isServer()).thenReturn(true);
decode().onAltSvcRead(ctx, STREAM_ID, 1, 2, Unpooled.EMPTY_BUFFER, "www.example.com", null); decode().onAltSvcRead(ctx, STREAM_ID, 1, 2, EMPTY_BUFFER, "www.example.com", null);
} }
@Test @Test
@ -645,7 +625,7 @@ public class DelegatingHttp2ConnectionHandlerTest {
@Test @Test
public void clientWriteAltSvcShouldThrow() throws Exception { public void clientWriteAltSvcShouldThrow() throws Exception {
when(connection.isServer()).thenReturn(false); when(connection.isServer()).thenReturn(false);
ChannelFuture future = handler.writeAltSvc(ctx, promise, STREAM_ID, 1, 2, Unpooled.EMPTY_BUFFER, ChannelFuture future = handler.writeAltSvc(ctx, promise, STREAM_ID, 1, 2, EMPTY_BUFFER,
"www.example.com", null); "www.example.com", null);
assertTrue(future.awaitUninterruptibly().cause() instanceof Http2Exception); assertTrue(future.awaitUninterruptibly().cause() instanceof Http2Exception);
} }
@ -662,11 +642,11 @@ public class DelegatingHttp2ConnectionHandlerTest {
private static ByteBuf dummyData() { private static ByteBuf dummyData() {
// The buffer is purposely 8 bytes so it will even work for a ping frame. // The buffer is purposely 8 bytes so it will even work for a ping frame.
return Unpooled.wrappedBuffer("abcdefgh".getBytes(UTF_8)); return wrappedBuffer("abcdefgh".getBytes(UTF_8));
} }
private void mockContext() { private void mockContext() {
Mockito.reset(ctx); reset(ctx);
when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
when(ctx.channel()).thenReturn(channel); when(ctx.channel()).thenReturn(channel);
when(ctx.newSucceededFuture()).thenReturn(future); when(ctx.newSucceededFuture()).thenReturn(future);

View File

@ -15,14 +15,6 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2TestUtil.runInChannel;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@ -37,16 +29,20 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.NetUtil; import io.netty.util.NetUtil;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import static io.netty.handler.codec.http2.Http2TestUtil.*;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** /**
* Tests the full HTTP/2 framing stack including the connection and preface handlers. * Tests the full HTTP/2 framing stack including the connection and preface handlers.
*/ */
@ -117,14 +113,14 @@ public class Http2ConnectionRoundtripTest {
new DefaultHttp2Headers.Builder().method("GET").scheme("https") new DefaultHttp2Headers.Builder().method("GET").scheme("https")
.authority("example.org").path("/some/path/resource2").build(); .authority("example.org").path("/some/path/resource2").build();
final String text = "hello world"; final String text = "hello world";
runInChannel(clientChannel, new Http2TestUtil.Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() throws Http2Exception { public void run() {
for (int i = 0, nextStream = 3; i < NUM_STREAMS; ++i, nextStream += 2) { for (int i = 0, nextStream = 3; i < NUM_STREAMS; ++i, nextStream += 2) {
final int streamId = nextStream; http2Client.writeHeaders(
http2Client.writeHeaders(ctx(), newPromise(), streamId, headers, 0, (short) 16, ctx(), newPromise(), nextStream, headers, 0, (short) 16, false, 0, false, false);
false, 0, false, false); http2Client.writeData(
http2Client.writeData(ctx(), newPromise(), streamId, ctx(), newPromise(), nextStream,
Unpooled.copiedBuffer(text.getBytes()), 0, true, true, false); Unpooled.copiedBuffer(text.getBytes()), 0, true, true, false);
} }
} }

View File

@ -16,8 +16,7 @@
package io.netty.handler.codec.memcache.binary; package io.netty.handler.codec.memcache.binary;
/** /**
* Contains all possible status values a * Contains all possible status values a {@link BinaryMemcacheResponse} can return.
* {@link BinaryMemcacheResponseHeader} can return.
*/ */
public final class BinaryMemcacheResponseStatus { public final class BinaryMemcacheResponseStatus {

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.socks.SocksAuthRequestDecoder.State;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import java.util.List; import java.util.List;
@ -26,7 +27,7 @@ import java.util.List;
* Decodes {@link ByteBuf}s into {@link SocksAuthRequest}. * Decodes {@link ByteBuf}s into {@link SocksAuthRequest}.
* Before returning SocksRequest decoder removes itself from pipeline. * Before returning SocksRequest decoder removes itself from pipeline.
*/ */
public class SocksAuthRequestDecoder extends ReplayingDecoder<SocksAuthRequestDecoder.State> { public class SocksAuthRequestDecoder extends ReplayingDecoder<State> {
private SocksSubnegotiationVersion version; private SocksSubnegotiationVersion version;
private int fieldLength; private int fieldLength;

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.socks.SocksAuthResponseDecoder.State;
import java.util.List; import java.util.List;
@ -25,7 +26,7 @@ import java.util.List;
* Decodes {@link ByteBuf}s into {@link SocksAuthResponse}. * Decodes {@link ByteBuf}s into {@link SocksAuthResponse}.
* Before returning SocksResponse decoder removes itself from pipeline. * Before returning SocksResponse decoder removes itself from pipeline.
*/ */
public class SocksAuthResponseDecoder extends ReplayingDecoder<SocksAuthResponseDecoder.State> { public class SocksAuthResponseDecoder extends ReplayingDecoder<State> {
private SocksSubnegotiationVersion version; private SocksSubnegotiationVersion version;
private SocksAuthStatus authStatus; private SocksAuthStatus authStatus;

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.socks.SocksCmdRequestDecoder.State;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import java.util.List; import java.util.List;
@ -26,12 +27,13 @@ import java.util.List;
* Decodes {@link ByteBuf}s into {@link SocksCmdRequest}. * Decodes {@link ByteBuf}s into {@link SocksCmdRequest}.
* Before returning SocksRequest decoder removes itself from pipeline. * Before returning SocksRequest decoder removes itself from pipeline.
*/ */
public class SocksCmdRequestDecoder extends ReplayingDecoder<SocksCmdRequestDecoder.State> { public class SocksCmdRequestDecoder extends ReplayingDecoder<State> {
private SocksProtocolVersion version; private SocksProtocolVersion version;
private int fieldLength; private int fieldLength;
private SocksCmdType cmdType; private SocksCmdType cmdType;
private SocksAddressType addressType; private SocksAddressType addressType;
@SuppressWarnings("UnusedDeclaration")
private byte reserved; private byte reserved;
private String host; private String host;
private int port; private int port;

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.socks.SocksCmdResponseDecoder.State;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import java.util.List; import java.util.List;
@ -26,7 +27,7 @@ import java.util.List;
* Decodes {@link ByteBuf}s into {@link SocksCmdResponse}. * Decodes {@link ByteBuf}s into {@link SocksCmdResponse}.
* Before returning SocksResponse decoder removes itself from pipeline. * Before returning SocksResponse decoder removes itself from pipeline.
*/ */
public class SocksCmdResponseDecoder extends ReplayingDecoder<SocksCmdResponseDecoder.State> { public class SocksCmdResponseDecoder extends ReplayingDecoder<State> {
private SocksProtocolVersion version; private SocksProtocolVersion version;
private int fieldLength; private int fieldLength;

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.socks.SocksInitRequestDecoder.State;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -26,7 +27,7 @@ import java.util.List;
* Decodes {@link ByteBuf}s into {@link SocksInitRequest}. * Decodes {@link ByteBuf}s into {@link SocksInitRequest}.
* Before returning SocksRequest decoder removes itself from pipeline. * Before returning SocksRequest decoder removes itself from pipeline.
*/ */
public class SocksInitRequestDecoder extends ReplayingDecoder<SocksInitRequestDecoder.State> { public class SocksInitRequestDecoder extends ReplayingDecoder<State> {
private final List<SocksAuthScheme> authSchemes = new ArrayList<SocksAuthScheme>(); private final List<SocksAuthScheme> authSchemes = new ArrayList<SocksAuthScheme>();
private SocksProtocolVersion version; private SocksProtocolVersion version;

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.socks.SocksInitResponseDecoder.State;
import java.util.List; import java.util.List;
@ -25,7 +26,7 @@ import java.util.List;
* Decodes {@link ByteBuf}s into {@link SocksInitResponse}. * Decodes {@link ByteBuf}s into {@link SocksInitResponse}.
* Before returning SocksResponse decoder removes itself from pipeline. * Before returning SocksResponse decoder removes itself from pipeline.
*/ */
public class SocksInitResponseDecoder extends ReplayingDecoder<SocksInitResponseDecoder.State> { public class SocksInitResponseDecoder extends ReplayingDecoder<State> {
private SocksProtocolVersion version; private SocksProtocolVersion version;
private SocksAuthScheme authScheme; private SocksAuthScheme authScheme;

View File

@ -48,7 +48,7 @@ public class StompSubframeDecoderTest {
assertNotNull(frame); assertNotNull(frame);
assertEquals(StompCommand.CONNECT, frame.command()); assertEquals(StompCommand.CONNECT, frame.command());
StompContentSubframe content = channel.readInbound(); StompContentSubframe content = channel.readInbound();
assertSame(content, LastStompContentSubframe.EMPTY_LAST_CONTENT); assertSame(LastStompContentSubframe.EMPTY_LAST_CONTENT, content);
Object o = channel.readInbound(); Object o = channel.readInbound();
assertNull(o); assertNull(o);
} }
@ -123,13 +123,13 @@ public class StompSubframeDecoderTest {
assertNotNull(frame); assertNotNull(frame);
assertEquals(StompCommand.CONNECT, frame.command()); assertEquals(StompCommand.CONNECT, frame.command());
StompContentSubframe content = channel.readInbound(); StompContentSubframe content = channel.readInbound();
assertSame(content, LastStompContentSubframe.EMPTY_LAST_CONTENT); assertSame(LastStompContentSubframe.EMPTY_LAST_CONTENT, content);
StompHeadersSubframe frame2 = channel.readInbound(); StompHeadersSubframe frame2 = channel.readInbound();
assertNotNull(frame2); assertNotNull(frame2);
assertEquals(StompCommand.CONNECTED, frame2.command()); assertEquals(StompCommand.CONNECTED, frame2.command());
StompContentSubframe content2 = channel.readInbound(); StompContentSubframe content2 = channel.readInbound();
assertSame(content2, LastStompContentSubframe.EMPTY_LAST_CONTENT); assertSame(LastStompContentSubframe.EMPTY_LAST_CONTENT, content2);
assertNull(channel.readInbound()); assertNull(channel.readInbound());
} }
} }

View File

@ -45,7 +45,6 @@ public class DefaultTextHeaders implements TextHeaders {
return Math.abs(hash % BUCKET_SIZE); return Math.abs(hash % BUCKET_SIZE);
} }
@SuppressWarnings("unchecked")
private final HeaderEntry[] entries = new HeaderEntry[BUCKET_SIZE]; private final HeaderEntry[] entries = new HeaderEntry[BUCKET_SIZE];
private final HeaderEntry head = new HeaderEntry(this); private final HeaderEntry head = new HeaderEntry(this);
private final boolean ignoreCase; private final boolean ignoreCase;
@ -71,7 +70,6 @@ public class DefaultTextHeaders implements TextHeaders {
return name; return name;
} }
@SuppressWarnings("unchecked")
protected CharSequence convertValue(Object value) { protected CharSequence convertValue(Object value) {
if (value == null) { if (value == null) {
throw new NullPointerException("value"); throw new NullPointerException("value");
@ -173,7 +171,6 @@ public class DefaultTextHeaders implements TextHeaders {
} }
if (headers instanceof DefaultTextHeaders) { if (headers instanceof DefaultTextHeaders) {
@SuppressWarnings("unchecked")
DefaultTextHeaders m = (DefaultTextHeaders) headers; DefaultTextHeaders m = (DefaultTextHeaders) headers;
HeaderEntry e = m.head.after; HeaderEntry e = m.head.after;
while (e != m.head) { while (e != m.head) {

View File

@ -286,7 +286,7 @@ public final class Base64 {
(DECODABET[src[srcOffset + 1]] & 0xFF) << 12 | (DECODABET[src[srcOffset + 1]] & 0xFF) << 12 |
(DECODABET[src[srcOffset + 2]] & 0xFF) << 6 | (DECODABET[src[srcOffset + 2]] & 0xFF) << 6 |
DECODABET[src[srcOffset + 3]] & 0xFF; DECODABET[src[srcOffset + 3]] & 0xFF;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException ignored) {
throw new IllegalArgumentException("not encoded in Base64"); throw new IllegalArgumentException("not encoded in Base64");
} }

View File

@ -157,7 +157,7 @@ public class Bzip2Decoder extends ByteToMessageDecoder {
int huffmanSymbolCount = 0; int huffmanSymbolCount = 0;
if (bitNumber > 0) { if (bitNumber > 0) {
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
if ((inUse16 & ((1 << 15) >>> i)) != 0) { if ((inUse16 & 1 << 15 >>> i) != 0) {
for (int j = 0, k = i << 4; j < 16; j++, k++) { for (int j = 0, k = i << 4; j < 16; j++, k++) {
if (readBoolean(in)) { if (readBoolean(in)) {
huffmanSymbolMap[huffmanSymbolCount++] = (byte) k; huffmanSymbolMap[huffmanSymbolCount++] = (byte) k;
@ -330,7 +330,7 @@ public class Bzip2Decoder extends ByteToMessageDecoder {
} }
this.bitCount = bitCount -= n; this.bitCount = bitCount -= n;
return (bitBuffer >>> bitCount) & ((1 << n) - 1); return bitBuffer >>> bitCount & (1 << n) - 1;
} }
private boolean readBoolean(ByteBuf in) { private boolean readBoolean(ByteBuf in) {

View File

@ -93,7 +93,7 @@ class Crc32c implements Checksum {
0xBE2DA0A5, 0x4C4623A6, 0x5F16D052, 0xAD7D5351, 0xBE2DA0A5, 0x4C4623A6, 0x5F16D052, 0xAD7D5351,
}; };
private static final int LONG_MASK = 0xFFFFFFFF; private static final long LONG_MASK = 0xFFFFFFFFL;
private static final int BYTE_MASK = 0xFF; private static final int BYTE_MASK = 0xFF;
private int crc = ~0; private int crc = ~0;
@ -121,6 +121,6 @@ class Crc32c implements Checksum {
} }
private static int crc32c(int crc, int b) { private static int crc32c(int crc, int b) {
return (crc >>> 8) ^ CRC_TABLE[(crc ^ (b & BYTE_MASK)) & BYTE_MASK]; return crc >>> 8 ^ CRC_TABLE[(crc ^ b & BYTE_MASK) & BYTE_MASK];
} }
} }

View File

@ -57,7 +57,7 @@ public class Snappy {
written = 0; written = 0;
} }
public void encode(ByteBuf in, ByteBuf out, int length) { public void encode(final ByteBuf in, final ByteBuf out, final int length) {
// Write the preamble length to the output buffer // Write the preamble length to the output buffer
for (int i = 0;; i ++) { for (int i = 0;; i ++) {
int b = length >>> i * 7; int b = length >>> i * 7;
@ -70,15 +70,14 @@ public class Snappy {
} }
int inIndex = in.readerIndex(); int inIndex = in.readerIndex();
final int baseIndex = in.readerIndex(); final int baseIndex = inIndex;
final int maxIndex = length;
final short[] table = getHashTable(maxIndex); final short[] table = getHashTable(length);
final int shift = 32 - (int) Math.floor(Math.log(table.length) / Math.log(2)); final int shift = 32 - (int) Math.floor(Math.log(table.length) / Math.log(2));
int nextEmit = inIndex; int nextEmit = inIndex;
if (maxIndex - inIndex >= MIN_COMPRESSIBLE_BYTES) { if (length - inIndex >= MIN_COMPRESSIBLE_BYTES) {
int nextHash = hash(in, ++inIndex, shift); int nextHash = hash(in, ++inIndex, shift);
outer: while (true) { outer: while (true) {
int skip = 32; int skip = 32;
@ -92,7 +91,7 @@ public class Snappy {
nextIndex = inIndex + bytesBetweenHashLookups; nextIndex = inIndex + bytesBetweenHashLookups;
// We need at least 4 remaining bytes to read the hash // We need at least 4 remaining bytes to read the hash
if (nextIndex > maxIndex - 4) { if (nextIndex > length - 4) {
break outer; break outer;
} }
@ -109,14 +108,14 @@ public class Snappy {
int insertTail; int insertTail;
do { do {
int base = inIndex; int base = inIndex;
int matched = 4 + findMatchingLength(in, candidate + 4, inIndex + 4, maxIndex); int matched = 4 + findMatchingLength(in, candidate + 4, inIndex + 4, length);
inIndex += matched; inIndex += matched;
int offset = base - candidate; int offset = base - candidate;
encodeCopy(out, offset, matched); encodeCopy(out, offset, matched);
in.readerIndex(in.readerIndex() + matched); in.readerIndex(in.readerIndex() + matched);
insertTail = inIndex - 1; insertTail = inIndex - 1;
nextEmit = inIndex; nextEmit = inIndex;
if (inIndex >= maxIndex - 4) { if (inIndex >= length - 4) {
break outer; break outer;
} }
@ -134,8 +133,8 @@ public class Snappy {
} }
// If there are any remaining characters, write them out as a literal // If there are any remaining characters, write them out as a literal
if (nextEmit < maxIndex) { if (nextEmit < length) {
encodeLiteral(in, out, maxIndex - nextEmit); encodeLiteral(in, out, length - nextEmit);
} }
} }

View File

@ -27,7 +27,7 @@ class ChannelBufferByteInput implements ByteInput {
private final ByteBuf buffer; private final ByteBuf buffer;
public ChannelBufferByteInput(ByteBuf buffer) { ChannelBufferByteInput(ByteBuf buffer) {
this.buffer = buffer; this.buffer = buffer;
} }

View File

@ -32,7 +32,7 @@ class ChannelBufferByteOutput implements ByteOutput {
/** /**
* Create a new instance which use the given {@link ByteBuf} * Create a new instance which use the given {@link ByteBuf}
*/ */
public ChannelBufferByteOutput(ByteBuf buffer) { ChannelBufferByteOutput(ByteBuf buffer) {
this.buffer = buffer; this.buffer = buffer;
} }

View File

@ -20,13 +20,12 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.Unmarshaller;
import java.io.ObjectStreamConstants; import java.io.ObjectStreamConstants;
import java.util.List; import java.util.List;
import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.Unmarshaller;
/** /**
* {@link ReplayingDecoder} which use an {@link Unmarshaller} to read the Object out of the {@link ByteBuf}. * {@link ReplayingDecoder} which use an {@link Unmarshaller} to read the Object out of the {@link ByteBuf}.
* *
@ -73,7 +72,7 @@ public class CompatibleMarshallingDecoder extends ReplayingDecoder<Void> {
Object obj = unmarshaller.readObject(); Object obj = unmarshaller.readObject();
unmarshaller.finish(); unmarshaller.finish();
out.add(obj); out.add(obj);
} catch (LimitingByteInput.TooBigObjectException e) { } catch (LimitingByteInput.TooBigObjectException ignored) {
discardingTooLongFrame = true; discardingTooLongFrame = true;
throw new TooLongFrameException(); throw new TooLongFrameException();
} finally { } finally {

View File

@ -32,7 +32,7 @@ class LimitingByteInput implements ByteInput {
private final long limit; private final long limit;
private long read; private long read;
public LimitingByteInput(ByteInput input, long limit) { LimitingByteInput(ByteInput input, long limit) {
if (limit <= 0) { if (limit <= 0) {
throw new IllegalArgumentException("The limit MUST be > 0"); throw new IllegalArgumentException("The limit MUST be > 0");
} }

View File

@ -27,7 +27,7 @@ class ClassLoaderClassResolver implements ClassResolver {
public Class<?> resolve(String className) throws ClassNotFoundException { public Class<?> resolve(String className) throws ClassNotFoundException {
try { try {
return classLoader.loadClass(className); return classLoader.loadClass(className);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException ignored) {
return Class.forName(className, false, classLoader); return Class.forName(className, false, classLoader);
} }
} }

View File

@ -65,7 +65,7 @@ class CompactObjectInputStream extends ObjectInputStream {
Class<?> clazz; Class<?> clazz;
try { try {
clazz = classResolver.resolve(desc.getName()); clazz = classResolver.resolve(desc.getName());
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ignored) {
clazz = super.resolveClass(desc); clazz = super.resolveClass(desc);
} }

View File

@ -21,7 +21,7 @@ import java.util.Map;
final class SoftReferenceMap<K, V> extends ReferenceMap<K, V> { final class SoftReferenceMap<K, V> extends ReferenceMap<K, V> {
public SoftReferenceMap(Map<K, Reference<V>> delegate) { SoftReferenceMap(Map<K, Reference<V>> delegate) {
super(delegate); super(delegate);
} }

View File

@ -21,7 +21,7 @@ import java.util.Map;
final class WeakReferenceMap<K, V> extends ReferenceMap<K, V> { final class WeakReferenceMap<K, V> extends ReferenceMap<K, V> {
public WeakReferenceMap(Map<K, Reference<V>> delegate) { WeakReferenceMap(Map<K, Reference<V>> delegate) {
super(delegate); super(delegate);
} }

View File

@ -26,9 +26,6 @@ import static io.netty.buffer.Unpooled.*;
import static org.hamcrest.core.Is.*; import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/**
*/
@SuppressWarnings("ZeroLengthArrayAllocation")
public class ByteArrayDecoderTest { public class ByteArrayDecoderTest {
private EmbeddedChannel ch; private EmbeddedChannel ch;

View File

@ -31,6 +31,7 @@ public class JdkZlibTest extends ZlibTest {
} }
@Test(expected = DecompressionException.class) @Test(expected = DecompressionException.class)
@Override
public void testZLIB_OR_NONE3() throws Exception { public void testZLIB_OR_NONE3() throws Exception {
super.testZLIB_OR_NONE3(); super.testZLIB_OR_NONE3();
} }

View File

@ -30,6 +30,7 @@ public class ZlibCrossTest2 extends ZlibTest {
} }
@Test(expected = DecompressionException.class) @Test(expected = DecompressionException.class)
@Override
public void testZLIB_OR_NONE3() throws Exception { public void testZLIB_OR_NONE3() throws Exception {
super.testZLIB_OR_NONE3(); super.testZLIB_OR_NONE3();
} }

View File

@ -35,7 +35,6 @@ public abstract class AbstractReferenceCounted implements ReferenceCounted {
refCntUpdater = updater; refCntUpdater = updater;
} }
@SuppressWarnings("FieldMayBeFinal")
private volatile int refCnt = 1; private volatile int refCnt = 1;
@Override @Override

View File

@ -48,7 +48,7 @@ public class DefaultAttributeMap implements AttributeMap {
@SuppressWarnings("UnusedDeclaration") @SuppressWarnings("UnusedDeclaration")
private volatile AtomicReferenceArray<DefaultAttribute<?>> attributes; private volatile AtomicReferenceArray<DefaultAttribute<?>> attributes;
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings("unchecked")
@Override @Override
public <T> Attribute<T> attr(AttributeKey<T> key) { public <T> Attribute<T> attr(AttributeKey<T> key) {
if (key == null) { if (key == null) {

View File

@ -222,7 +222,6 @@ public class HashedWheelTimer implements Timer {
leak = leakDetector.open(this); leak = leakDetector.open(this);
} }
@SuppressWarnings("unchecked")
private static HashedWheelBucket[] createWheel(int ticksPerWheel) { private static HashedWheelBucket[] createWheel(int ticksPerWheel) {
if (ticksPerWheel <= 0) { if (ticksPerWheel <= 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -306,7 +305,7 @@ public class HashedWheelTimer implements Timer {
workerThread.interrupt(); workerThread.interrupt();
try { try {
workerThread.join(100); workerThread.join(100);
} catch (InterruptedException e) { } catch (InterruptedException ignored) {
interrupted = true; interrupted = true;
} }
} }
@ -397,8 +396,7 @@ public class HashedWheelTimer implements Timer {
continue; continue;
} }
long calculated = timeout.deadline / tickDuration; long calculated = timeout.deadline / tickDuration;
long remainingRounds = (calculated - tick) / wheel.length; timeout.remainingRounds = (calculated - tick) / wheel.length;
timeout.remainingRounds = remainingRounds;
final long ticks = Math.max(calculated, tick); // Ensure we don't schedule for past. final long ticks = Math.max(calculated, tick); // Ensure we don't schedule for past.
int stopIndex = (int) (ticks & mask); int stopIndex = (int) (ticks & mask);
@ -439,7 +437,7 @@ public class HashedWheelTimer implements Timer {
try { try {
Thread.sleep(sleepTimeMs); Thread.sleep(sleepTimeMs);
} catch (InterruptedException e) { } catch (InterruptedException ignored) {
if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) { if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
return Long.MIN_VALUE; return Long.MIN_VALUE;
} }

View File

@ -164,7 +164,7 @@ public abstract class Recycler<T> {
private final WeakReference<Thread> owner; private final WeakReference<Thread> owner;
private final int id = ID_GENERATOR.getAndIncrement(); private final int id = ID_GENERATOR.getAndIncrement();
public WeakOrderQueue(Stack<?> stack, Thread thread) { WeakOrderQueue(Stack<?> stack, Thread thread) {
head = tail = new Link(); head = tail = new Link();
owner = new WeakReference<Thread>(thread); owner = new WeakReference<Thread>(thread);
synchronized (stack) { synchronized (stack) {
@ -194,7 +194,7 @@ public abstract class Recycler<T> {
} }
// transfer as many items as we can from this queue to the stack, returning true if any were transferred // transfer as many items as we can from this queue to the stack, returning true if any were transferred
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings("rawtypes")
boolean transfer(Stack<?> to) { boolean transfer(Stack<?> to) {
Link head = this.head; Link head = this.head;

View File

@ -132,7 +132,7 @@ public final class Version {
private static long parseIso8601(String value) { private static long parseIso8601(String value) {
try { try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(value).getTime(); return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(value).getTime();
} catch (ParseException e) { } catch (ParseException ignored) {
return 0; return 0;
} }
} }

View File

@ -47,7 +47,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
/** The maximum number of elements allowed without allocating more space. */ /** The maximum number of elements allowed without allocating more space. */
private int maxSize; private int maxSize;
/** The load factor for the map. Used to calculate {@link maxSize}. */ /** The load factor for the map. Used to calculate {@link #maxSize}. */
private final float loadFactor; private final float loadFactor;
private byte[] states; private byte[] states;
@ -80,7 +80,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
// Allocate the arrays. // Allocate the arrays.
states = new byte[initialCapacity]; states = new byte[initialCapacity];
keys = new int[initialCapacity]; keys = new int[initialCapacity];
@SuppressWarnings("unchecked") @SuppressWarnings({ "unchecked", "SuspiciousArrayCast" })
V[] temp = (V[]) new Object[initialCapacity]; V[] temp = (V[]) new Object[initialCapacity];
values = temp; values = temp;
@ -102,7 +102,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
int hash = hash(key); int hash = hash(key);
int capacity = capacity(); int capacity = capacity();
int index = hash % capacity; int index = hash % capacity;
int increment = 1 + (hash % (capacity - 2)); int increment = 1 + hash % (capacity - 2);
final int startIndex = index; final int startIndex = index;
int firstRemovedIndex = -1; int firstRemovedIndex = -1;
do { do {
@ -215,7 +215,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
int i = -1; int i = -1;
while ((i = nextEntryIndex(i + 1)) >= 0) { while ((i = nextEntryIndex(i + 1)) >= 0) {
V next = values[i]; V next = values[i];
if (value == next || (value != null && value.equals(next))) { if (value == next || value != null && value.equals(next)) {
return true; return true;
} }
} }
@ -268,7 +268,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
private int indexOf(int key) { private int indexOf(int key) {
int hash = hash(key); int hash = hash(key);
int capacity = capacity(); int capacity = capacity();
int increment = 1 + (hash % (capacity - 2)); int increment = 1 + hash % (capacity - 2);
int index = hash % capacity; int index = hash % capacity;
int startIndex = index; int startIndex = index;
do { do {
@ -308,7 +308,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
/** /**
* Creates a hash value for the given key. * Creates a hash value for the given key.
*/ */
private int hash(int key) { private static int hash(int key) {
// Just make sure the integer is positive. // Just make sure the integer is positive.
return key & Integer.MAX_VALUE; return key & Integer.MAX_VALUE;
} }
@ -351,12 +351,12 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
* Adjusts the given capacity value to ensure that it's odd. Even capacities can break probing. * Adjusts the given capacity value to ensure that it's odd. Even capacities can break probing.
* TODO: would be better to ensure it's prime as well. * TODO: would be better to ensure it's prime as well.
*/ */
private int adjustCapacity(int capacity) { private static int adjustCapacity(int capacity) {
return capacity |= 1; return capacity | 1;
} }
/** /**
* Marks the entry at the given index position as {@link REMOVED} and sets the value to * Marks the entry at the given index position as {@link #REMOVED} and sets the value to
* {@code null}. * {@code null}.
* <p> * <p>
* TODO: consider performing re-compaction. * TODO: consider performing re-compaction.
@ -395,7 +395,7 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
// New states array is automatically initialized to AVAILABLE (i.e. 0 == AVAILABLE). // New states array is automatically initialized to AVAILABLE (i.e. 0 == AVAILABLE).
states = new byte[newCapacity]; states = new byte[newCapacity];
keys = new int[newCapacity]; keys = new int[newCapacity];
@SuppressWarnings("unchecked") @SuppressWarnings({ "unchecked", "SuspiciousArrayCast" })
V[] temp = (V[]) new Object[newCapacity]; V[] temp = (V[]) new Object[newCapacity];
values = temp; values = temp;

View File

@ -24,7 +24,7 @@ final class DefaultFutureListeners {
private int progressiveSize; // the number of progressive listeners private int progressiveSize; // the number of progressive listeners
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public DefaultFutureListeners( DefaultFutureListeners(
GenericFutureListener<? extends Future<?>> first, GenericFutureListener<? extends Future<?>> second) { GenericFutureListener<? extends Future<?>> first, GenericFutureListener<? extends Future<?>> second) {
listeners = new GenericFutureListener[2]; listeners = new GenericFutureListener[2];
listeners[0] = first; listeners[0] = first;

View File

@ -147,7 +147,6 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
if (listeners instanceof DefaultFutureListeners) { if (listeners instanceof DefaultFutureListeners) {
((DefaultFutureListeners) listeners).add(listener); ((DefaultFutureListeners) listeners).add(listener);
} else { } else {
@SuppressWarnings("unchecked")
final GenericFutureListener<? extends Future<V>> firstListener = final GenericFutureListener<? extends Future<V>> firstListener =
(GenericFutureListener<? extends Future<V>>) listeners; (GenericFutureListener<? extends Future<V>>) listeners;
listeners = new DefaultFutureListeners(firstListener, listener); listeners = new DefaultFutureListeners(firstListener, listener);
@ -559,7 +558,6 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
if (listeners instanceof DefaultFutureListeners) { if (listeners instanceof DefaultFutureListeners) {
notifyListeners0(this, (DefaultFutureListeners) listeners); notifyListeners0(this, (DefaultFutureListeners) listeners);
} else { } else {
@SuppressWarnings("unchecked")
final GenericFutureListener<? extends Future<V>> l = final GenericFutureListener<? extends Future<V>> l =
(GenericFutureListener<? extends Future<V>>) listeners; (GenericFutureListener<? extends Future<V>>) listeners;
notifyListener0(this, l); notifyListener0(this, l);
@ -582,7 +580,6 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
} }
}); });
} else { } else {
@SuppressWarnings("unchecked")
final GenericFutureListener<? extends Future<V>> l = final GenericFutureListener<? extends Future<V>> l =
(GenericFutureListener<? extends Future<V>>) listeners; (GenericFutureListener<? extends Future<V>>) listeners;
execute(executor, new Runnable() { execute(executor, new Runnable() {
@ -729,7 +726,7 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
} }
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings("unchecked")
void notifyProgressiveListeners(final long progress, final long total) { void notifyProgressiveListeners(final long progress, final long total) {
final Object listeners = progressiveListeners(); final Object listeners = progressiveListeners();
if (listeners == null) { if (listeners == null) {
@ -794,7 +791,7 @@ public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
private static final class CauseHolder { private static final class CauseHolder {
final Throwable cause; final Throwable cause;
private CauseHolder(Throwable cause) { CauseHolder(Throwable cause) {
this.cause = cause; this.cause = cause;
} }
} }

View File

@ -18,5 +18,6 @@ package io.netty.util.concurrent;
/** /**
* The result of an scheduled asynchronous operation. * The result of an scheduled asynchronous operation.
*/ */
@SuppressWarnings("ClassNameSameAsAncestorName")
public interface ScheduledFuture<V> extends Future<V>, java.util.concurrent.ScheduledFuture<V> { public interface ScheduledFuture<V> extends Future<V>, java.util.concurrent.ScheduledFuture<V> {
} }

View File

@ -30,6 +30,7 @@ public final class EmptyArrays {
public static final short[] EMPTY_SHORTS = new short[0]; public static final short[] EMPTY_SHORTS = new short[0];
public static final long[] EMPTY_LONGS = new long[0]; public static final long[] EMPTY_LONGS = new long[0];
public static final Object[] EMPTY_OBJECTS = new Object[0]; public static final Object[] EMPTY_OBJECTS = new Object[0];
public static final Class<?>[] EMPTY_CLASSES = new Class[0];
public static final String[] EMPTY_STRINGS = new String[0]; public static final String[] EMPTY_STRINGS = new String[0];
public static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; public static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];
public static final ByteBuffer[] EMPTY_BYTE_BUFFERS = new ByteBuffer[0]; public static final ByteBuffer[] EMPTY_BYTE_BUFFERS = new ByteBuffer[0];

View File

@ -87,8 +87,7 @@ final class PlatformDependent0 {
// http://www.mail-archive.com/jdk6-dev@openjdk.java.net/msg00698.html // http://www.mail-archive.com/jdk6-dev@openjdk.java.net/msg00698.html
try { try {
unsafe.getClass().getDeclaredMethod( unsafe.getClass().getDeclaredMethod(
"copyMemory", "copyMemory", Object.class, long.class, Object.class, long.class, long.class);
new Class[] { Object.class, long.class, Object.class, long.class, long.class });
logger.debug("sun.misc.Unsafe.copyMemory: available"); logger.debug("sun.misc.Unsafe.copyMemory: available");
} catch (NoSuchMethodError t) { } catch (NoSuchMethodError t) {

View File

@ -29,12 +29,12 @@ import java.util.regex.Pattern;
*/ */
public final class SystemPropertyUtil { public final class SystemPropertyUtil {
@SuppressWarnings("all")
private static boolean initializedLogger; private static boolean initializedLogger;
private static final InternalLogger logger; private static final InternalLogger logger;
private static boolean loggedException; private static boolean loggedException;
static { static {
initializedLogger = false;
logger = InternalLoggerFactory.getInstance(SystemPropertyUtil.class); logger = InternalLoggerFactory.getInstance(SystemPropertyUtil.class);
initializedLogger = true; initializedLogger = true;
} }

View File

@ -35,6 +35,14 @@ public abstract class InternalLoggerFactory {
static { static {
final String name = InternalLoggerFactory.class.getName(); final String name = InternalLoggerFactory.class.getName();
InternalLoggerFactory f;
f = newDefaultFactory(name);
defaultFactory = f;
}
@SuppressWarnings("UnusedCatchParameter")
private static InternalLoggerFactory newDefaultFactory(String name) {
InternalLoggerFactory f; InternalLoggerFactory f;
try { try {
f = new Slf4JLoggerFactory(true); f = new Slf4JLoggerFactory(true);
@ -49,8 +57,7 @@ public abstract class InternalLoggerFactory {
f.newInstance(name).debug("Using java.util.logging as the default logging framework"); f.newInstance(name).debug("Using java.util.logging as the default logging framework");
} }
} }
return f;
defaultFactory = f;
} }
/** /**

View File

@ -72,7 +72,7 @@ class Log4JLogger extends AbstractInternalLogger {
try { try {
logger.isTraceEnabled(); logger.isTraceEnabled();
return true; return true;
} catch (NoSuchMethodError e) { } catch (NoSuchMethodError ignored) {
return false; return false;
} }
} }

View File

@ -52,7 +52,7 @@ class Slf4JLogger extends AbstractInternalLogger {
} }
@Override @Override
public void trace(String format, Object[] argArray) { public void trace(String format, Object... argArray) {
logger.trace(format, argArray); logger.trace(format, argArray);
} }
@ -82,7 +82,7 @@ class Slf4JLogger extends AbstractInternalLogger {
} }
@Override @Override
public void debug(String format, Object[] argArray) { public void debug(String format, Object... argArray) {
logger.debug(format, argArray); logger.debug(format, argArray);
} }
@ -112,7 +112,7 @@ class Slf4JLogger extends AbstractInternalLogger {
} }
@Override @Override
public void info(String format, Object[] argArray) { public void info(String format, Object... argArray) {
logger.info(format, argArray); logger.info(format, argArray);
} }
@ -137,7 +137,7 @@ class Slf4JLogger extends AbstractInternalLogger {
} }
@Override @Override
public void warn(String format, Object[] argArray) { public void warn(String format, Object... argArray) {
logger.warn(format, argArray); logger.warn(format, argArray);
} }
@ -172,7 +172,7 @@ class Slf4JLogger extends AbstractInternalLogger {
} }
@Override @Override
public void error(String format, Object[] argArray) { public void error(String format, Object... argArray) {
logger.error(format, argArray); logger.error(format, argArray);
} }

View File

@ -54,7 +54,7 @@ public class Slf4JLoggerFactory extends InternalLoggerFactory {
if (LoggerFactory.getILoggerFactory() instanceof NOPLoggerFactory) { if (LoggerFactory.getILoggerFactory() instanceof NOPLoggerFactory) {
throw new NoClassDefFoundError(buf.toString()); throw new NoClassDefFoundError(buf.toString());
} else { } else {
err.print(buf.toString()); err.print(buf);
err.flush(); err.flush();
} }
} finally { } finally {

View File

@ -42,10 +42,10 @@ public class DefaultAttributeMapTest {
assertSame(one, map.attr(key)); assertSame(one, map.attr(key));
one.setIfAbsent("Whoohoo"); one.setIfAbsent("Whoohoo");
assertSame(one.get(), "Whoohoo"); assertSame("Whoohoo", one.get());
one.setIfAbsent("What"); one.setIfAbsent("What");
assertNotSame(one.get(), "What"); assertNotSame("What", one.get());
one.remove(); one.remove();
assertNull(one.get()); assertNull(one.get());
@ -62,7 +62,7 @@ public class DefaultAttributeMapTest {
assertEquals(one.get(), Integer.valueOf(3653)); assertEquals(one.get(), Integer.valueOf(3653));
one.setIfAbsent(1); one.setIfAbsent(1);
assertNotSame(one.get(), 1); assertNotSame(1, one.get());
one.remove(); one.remove();
assertNull(one.get()); assertNull(one.get());

View File

@ -40,14 +40,14 @@ public class RecyclerTest {
private static final Recycler<RecyclableObject> RECYCLER = new Recycler<RecyclableObject>() { private static final Recycler<RecyclableObject> RECYCLER = new Recycler<RecyclableObject>() {
@Override @Override
protected RecyclableObject newObject(Handle handle) { protected RecyclableObject newObject(Handle<RecyclableObject> handle) {
return new RecyclableObject(handle); return new RecyclableObject(handle);
} }
}; };
private final Recycler.Handle handle; private final Recycler.Handle<RecyclableObject> handle;
private RecyclableObject(Recycler.Handle handle) { private RecyclableObject(Recycler.Handle<RecyclableObject> handle) {
this.handle = handle; this.handle = handle;
} }

View File

@ -14,17 +14,13 @@
*/ */
package io.netty.util.collection; package io.netty.util.collection;
import static org.junit.Assert.assertEquals; import org.junit.Before;
import static org.junit.Assert.assertFalse; import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.junit.Before; import static org.junit.Assert.*;
import org.junit.Test;
/** /**
* Tests for {@link IntObjectHashMap}. * Tests for {@link IntObjectHashMap}.
@ -34,7 +30,7 @@ public class IntObjectHashMapTest {
private static class Value { private static class Value {
private final String name; private final String name;
public Value(String name) { Value(String name) {
this.name = name; this.name = name;
} }
@ -42,7 +38,7 @@ public class IntObjectHashMapTest {
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode());
return result; return result;
} }

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