Code clean-up based on IntelliJ code analysis

This commit is contained in:
Trustin Lee 2012-06-11 22:54:28 +09:00
parent 8e55bfbc9c
commit 6211e53e86
74 changed files with 184 additions and 228 deletions

View File

@ -683,11 +683,11 @@ public class CompositeByteBuf extends AbstractByteBuf {
// New readerIndex and writerIndex will become 0 and // New readerIndex and writerIndex will become 0 and
// (previous writerIndex - previous readerIndex) respectively. // (previous writerIndex - previous readerIndex) respectively.
final int localReaderIndex = this.readerIndex(); final int localReaderIndex = readerIndex();
if (localReaderIndex == 0) { if (localReaderIndex == 0) {
return; return;
} }
int localWriterIndex = this.writerIndex(); int localWriterIndex = writerIndex();
final int bytesToMove = capacity() - localReaderIndex; final int bytesToMove = capacity() - localReaderIndex;
List<ByteBuf> list = decompose(localReaderIndex, bytesToMove); List<ByteBuf> list = decompose(localReaderIndex, bytesToMove);
@ -712,14 +712,14 @@ public class CompositeByteBuf extends AbstractByteBuf {
int localMarkedReaderIndex = localReaderIndex; int localMarkedReaderIndex = localReaderIndex;
try { try {
resetReaderIndex(); resetReaderIndex();
localMarkedReaderIndex = this.readerIndex(); localMarkedReaderIndex = readerIndex();
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// ignore // ignore
} }
int localMarkedWriterIndex = localWriterIndex; int localMarkedWriterIndex = localWriterIndex;
try { try {
resetWriterIndex(); resetWriterIndex();
localMarkedWriterIndex = this.writerIndex(); localMarkedWriterIndex = writerIndex();
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// ignore // ignore
} }

View File

@ -34,11 +34,6 @@
<artifactId>netty-codec</artifactId> <artifactId>netty-codec</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-handler</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -137,11 +137,11 @@ public class HttpContentCompressor extends HttpContentEncoder {
q = 0.0f; q = 0.0f;
} }
} }
if (encoding.indexOf("*") >= 0) { if (encoding.contains("*")) {
starQ = q; starQ = q;
} else if (encoding.indexOf("gzip") >= 0 && q > gzipQ) { } else if (encoding.contains("gzip") && q > gzipQ) {
gzipQ = q; gzipQ = q;
} else if (encoding.indexOf("deflate") >= 0 && q > deflateQ) { } else if (encoding.contains("deflate") && q > deflateQ) {
deflateQ = q; deflateQ = q;
} }
} }

View File

@ -269,7 +269,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
return readFixedLengthContent(buffer); return readFixedLengthContent(buffer);
} }
case READ_FIXED_LENGTH_CONTENT_AS_CHUNKS: { case READ_FIXED_LENGTH_CONTENT_AS_CHUNKS: {
assert this.chunkSize <= Integer.MAX_VALUE; assert chunkSize <= Integer.MAX_VALUE;
int chunkSize = (int) this.chunkSize; int chunkSize = (int) this.chunkSize;
int readLimit = actualReadableBytes(); int readLimit = actualReadableBytes();
int toRead = chunkSize; int toRead = chunkSize;
@ -322,7 +322,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
return chunk; return chunk;
} }
case READ_CHUNKED_CONTENT_AS_CHUNKS: { case READ_CHUNKED_CONTENT_AS_CHUNKS: {
assert this.chunkSize <= Integer.MAX_VALUE; assert chunkSize <= Integer.MAX_VALUE;
int chunkSize = (int) this.chunkSize; int chunkSize = (int) this.chunkSize;
int readLimit = actualReadableBytes(); int readLimit = actualReadableBytes();
int toRead = chunkSize; int toRead = chunkSize;
@ -395,7 +395,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
if (code == 101 && !res.containsHeader(HttpHeaders.Names.SEC_WEBSOCKET_ACCEPT)) { if (code == 101 && !res.containsHeader(HttpHeaders.Names.SEC_WEBSOCKET_ACCEPT)) {
// It's Hixie 76 websocket handshake response // It's Hixie 76 websocket handshake response
return false; return false;
} }
return true; return true;
} }
@ -440,7 +440,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
if (toRead > actualReadableBytes()) { if (toRead > actualReadableBytes()) {
toRead = actualReadableBytes(); toRead = actualReadableBytes();
} }
contentRead = contentRead + toRead; contentRead += toRead;
if (length < contentRead) { if (length < contentRead) {
if (!message.isChunked()) { if (!message.isChunked()) {
message.setChunked(true); message.setChunked(true);

View File

@ -218,7 +218,7 @@ public class QueryStringDecoder {
String name = null; String name = null;
int pos = 0; // Beginning of the unprocessed region int pos = 0; // Beginning of the unprocessed region
int i; // End of the unprocessed region int i; // End of the unprocessed region
char c = 0; // Current character char c; // Current character
for (i = 0; i < s.length(); i++) { for (i = 0; i < s.length(); i++) {
c = s.charAt(i); c = s.charAt(i);
if (c == '=' && name == null) { if (c == '=' && name == null) {
@ -246,18 +246,12 @@ public class QueryStringDecoder {
if (pos != i) { // Are there characters we haven't dealt with? if (pos != i) { // Are there characters we haven't dealt with?
if (name == null) { // Yes and we haven't seen any `='. if (name == null) { // Yes and we haven't seen any `='.
if (!addParam(params, decodeComponent(s.substring(pos, i), charset), "")) { addParam(params, decodeComponent(s.substring(pos, i), charset), "");
return;
}
} else { // Yes and this must be the last value. } else { // Yes and this must be the last value.
if (!addParam(params, name, decodeComponent(s.substring(pos, i), charset))) { addParam(params, name, decodeComponent(s.substring(pos, i), charset));
return;
}
} }
} else if (name != null) { // Have we seen a name without value? } else if (name != null) { // Have we seen a name without value?
if (!addParam(params, name, "")) { addParam(params, name, "");
return;
}
} }
} }

View File

@ -103,27 +103,26 @@ public class WebSocket08FrameEncoder extends MessageToByteEncoder<WebSocketFrame
WebSocketFrame msg, ByteBuf out) throws Exception { WebSocketFrame msg, ByteBuf out) throws Exception {
byte[] mask; byte[] mask;
WebSocketFrame frame = msg; ByteBuf data = msg.getBinaryData();
ByteBuf data = frame.getBinaryData();
if (data == null) { if (data == null) {
data = Unpooled.EMPTY_BUFFER; data = Unpooled.EMPTY_BUFFER;
} }
byte opcode; byte opcode;
if (frame instanceof TextWebSocketFrame) { if (msg instanceof TextWebSocketFrame) {
opcode = OPCODE_TEXT; opcode = OPCODE_TEXT;
} else if (frame instanceof PingWebSocketFrame) { } else if (msg instanceof PingWebSocketFrame) {
opcode = OPCODE_PING; opcode = OPCODE_PING;
} else if (frame instanceof PongWebSocketFrame) { } else if (msg instanceof PongWebSocketFrame) {
opcode = OPCODE_PONG; opcode = OPCODE_PONG;
} else if (frame instanceof CloseWebSocketFrame) { } else if (msg instanceof CloseWebSocketFrame) {
opcode = OPCODE_CLOSE; opcode = OPCODE_CLOSE;
} else if (frame instanceof BinaryWebSocketFrame) { } else if (msg instanceof BinaryWebSocketFrame) {
opcode = OPCODE_BINARY; opcode = OPCODE_BINARY;
} else if (frame instanceof ContinuationWebSocketFrame) { } else if (msg instanceof ContinuationWebSocketFrame) {
opcode = OPCODE_CONT; opcode = OPCODE_CONT;
} else { } else {
throw new UnsupportedOperationException("Cannot encode frame of type: " + frame.getClass().getName()); throw new UnsupportedOperationException("Cannot encode frame of type: " + msg.getClass().getName());
} }
int length = data.readableBytes(); int length = data.readableBytes();
@ -133,10 +132,10 @@ public class WebSocket08FrameEncoder extends MessageToByteEncoder<WebSocketFrame
} }
int b0 = 0; int b0 = 0;
if (frame.isFinalFragment()) { if (msg.isFinalFragment()) {
b0 |= 1 << 7; b0 |= 1 << 7;
} }
b0 |= frame.getRsv() % 8 << 4; b0 |= msg.getRsv() % 8 << 4;
b0 |= opcode % 128; b0 |= opcode % 128;
if (opcode == OPCODE_PING && length > 125) { if (opcode == OPCODE_PING && length > 125) {

View File

@ -19,6 +19,7 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
@ -79,9 +80,7 @@ public abstract class WebSocketServerHandshaker {
*/ */
public Set<String> getSubprotocols() { public Set<String> getSubprotocols() {
Set<String> ret = new LinkedHashSet<String>(); Set<String> ret = new LinkedHashSet<String>();
for (String p: subprotocols) { Collections.addAll(ret, subprotocols);
ret.add(p);
}
return ret; return ret;
} }

View File

@ -383,10 +383,8 @@ public final class RtspHeaders {
*/ */
public static final String URL = "url"; public static final String URL = "url";
protected Values() { private Values() { }
}
} }
private RtspHeaders() { private RtspHeaders() { }
}
} }

View File

@ -63,11 +63,13 @@ public class DefaultSpdyDataFrame implements SpdyDataFrame {
} }
@Override @Override
@Deprecated
public boolean isCompressed() { public boolean isCompressed() {
return compressed; return compressed;
} }
@Override @Override
@Deprecated
public void setCompressed(boolean compressed) { public void setCompressed(boolean compressed) {
this.compressed = compressed; this.compressed = compressed;
} }

View File

@ -33,7 +33,6 @@ public class DefaultSpdyHeadersFrame extends DefaultSpdyHeaderBlock
* @param streamID the Stream-ID of this frame * @param streamID the Stream-ID of this frame
*/ */
public DefaultSpdyHeadersFrame(int streamID) { public DefaultSpdyHeadersFrame(int streamID) {
super();
setStreamID(streamID); setStreamID(streamID);
} }

View File

@ -32,7 +32,6 @@ public class DefaultSpdySynReplyFrame extends DefaultSpdyHeaderBlock
* @param streamID the Stream-ID of this frame * @param streamID the Stream-ID of this frame
*/ */
public DefaultSpdySynReplyFrame(int streamID) { public DefaultSpdySynReplyFrame(int streamID) {
super();
setStreamID(streamID); setStreamID(streamID);
} }

View File

@ -38,7 +38,6 @@ public class DefaultSpdySynStreamFrame extends DefaultSpdyHeaderBlock
*/ */
public DefaultSpdySynStreamFrame( public DefaultSpdySynStreamFrame(
int streamID, int associatedToStreamID, byte priority) { int streamID, int associatedToStreamID, byte priority) {
super();
setStreamID(streamID); setStreamID(streamID);
setAssociatedToStreamID(associatedToStreamID); setAssociatedToStreamID(associatedToStreamID);
setPriority(priority); setPriority(priority);

View File

@ -248,7 +248,7 @@ final class SpdyCodecUtil {
".1statusversionurl "; ".1statusversionurl ";
static final byte[] SPDY2_DICT; static final byte[] SPDY2_DICT;
static { static {
byte[] SPDY2_DICT_ = null; byte[] SPDY2_DICT_;
try { try {
SPDY2_DICT_ = SPDY2_DICT_S.getBytes("US-ASCII"); SPDY2_DICT_ = SPDY2_DICT_S.getBytes("US-ASCII");

View File

@ -15,13 +15,14 @@
*/ */
package io.netty.handler.codec.spdy; package io.netty.handler.codec.spdy;
import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
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.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
/** /**
* Decodes {@link ByteBuf}s into SPDY Data and Control Frames. * Decodes {@link ByteBuf}s into SPDY Data and Control Frames.
*/ */
@ -49,7 +50,7 @@ public class SpdyFrameDecoder extends ByteToMessageDecoder<Object> {
private int numHeaders; private int numHeaders;
private ByteBuf decompressed; private ByteBuf decompressed;
private static enum State { private enum State {
READ_COMMON_HEADER, READ_COMMON_HEADER,
READ_CONTROL_FRAME, READ_CONTROL_FRAME,
READ_SETTINGS_FRAME, READ_SETTINGS_FRAME,

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.handler.codec.spdy; package io.netty.handler.codec.spdy;
import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
@ -26,6 +25,8 @@ import io.netty.handler.codec.UnsupportedMessageTypeException;
import java.util.Set; import java.util.Set;
import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
/** /**
* Encodes a SPDY Data or Control Frame into a {@link ByteBuf}. * Encodes a SPDY Data or Control Frame into a {@link ByteBuf}.
*/ */
@ -48,7 +49,6 @@ public class SpdyFrameEncoder extends MessageToByteEncoder<Object> {
* Creates a new instance with the specified parameters. * Creates a new instance with the specified parameters.
*/ */
public SpdyFrameEncoder(int version, int compressionLevel, int windowBits, int memLevel) { public SpdyFrameEncoder(int version, int compressionLevel, int windowBits, int memLevel) {
super();
if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) { if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"unknown version: " + version); "unknown version: " + version);

View File

@ -62,9 +62,7 @@ public class SpdyHeaders {
*/ */
public static final String VERSION = ":version"; public static final String VERSION = ":version";
private HttpNames() { private HttpNames() { }
super();
}
} }
/** /**
@ -93,9 +91,7 @@ public class SpdyHeaders {
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version";
private Spdy2HttpNames() { private Spdy2HttpNames() { }
super();
}
} }

View File

@ -52,7 +52,6 @@ public class SpdyHttpDecoder extends MessageToMessageDecoder<Object, HttpMessage
* a {@link TooLongFrameException} will be raised. * a {@link TooLongFrameException} will be raised.
*/ */
public SpdyHttpDecoder(int version, int maxContentLength) { public SpdyHttpDecoder(int version, int maxContentLength) {
super();
if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) { if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"unsupported version: " + version); "unsupported version: " + version);

View File

@ -51,9 +51,7 @@ public final class SpdyHttpHeaders {
*/ */
public static final String SCHEME = "X-SPDY-Scheme"; public static final String SCHEME = "X-SPDY-Scheme";
private Names() { private Names() { }
super();
}
} }
private SpdyHttpHeaders() { private SpdyHttpHeaders() {

View File

@ -27,9 +27,7 @@ public class SpdyProtocolException extends Exception {
/** /**
* Creates a new instance. * Creates a new instance.
*/ */
public SpdyProtocolException() { public SpdyProtocolException() { }
super();
}
/** /**
* Creates a new instance. * Creates a new instance.

View File

@ -259,11 +259,6 @@ final class SpdySession {
} }
private final class PriorityComparator implements Comparator<Integer> { private final class PriorityComparator implements Comparator<Integer> {
public PriorityComparator() {
super();
}
@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

@ -77,7 +77,6 @@ public class SpdySessionHandler
* handle the client endpoint of the connection. * handle the client endpoint of the connection.
*/ */
public SpdySessionHandler(int version, boolean server) { public SpdySessionHandler(int version, boolean server) {
super();
if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) { if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"unsupported version: " + version); "unsupported version: " + version);

View File

@ -15,7 +15,7 @@
*/ */
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import static org.junit.Assert.*; import org.junit.Test;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
@ -23,7 +23,7 @@ import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import org.junit.Test; import static org.junit.Assert.*;
public class CookieDecoderTest { public class CookieDecoderTest {
@Test @Test
@ -350,7 +350,7 @@ public class CookieDecoderTest {
@Test @Test
public void testDecodingLongDates() { public void testDecodingLongDates() {
Calendar cookieDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Calendar cookieDate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cookieDate.set(9999, 11, 31, 23, 59, 59); cookieDate.set(9999, Calendar.DECEMBER, 31, 23, 59, 59);
long expectedMaxAge = (cookieDate.getTimeInMillis() - System.currentTimeMillis()) / 1000; long expectedMaxAge = (cookieDate.getTimeInMillis() - System.currentTimeMillis()) / 1000;
String source = "Format=EU; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/"; String source = "Format=EU; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/";

View File

@ -20,13 +20,12 @@ import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.channel.embedded.EmbeddedMessageChannel; import io.netty.channel.embedded.EmbeddedMessageChannel;
import io.netty.logging.InternalLogger; import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory; import io.netty.logging.InternalLoggerFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class SpdySessionHandlerTest { public class SpdySessionHandlerTest {
private static final InternalLogger logger = private static final InternalLogger logger =
@ -278,7 +277,6 @@ public class SpdySessionHandlerTest {
private final boolean server; private final boolean server;
EchoHandler(int closeSignal, boolean server) { EchoHandler(int closeSignal, boolean server) {
super();
this.closeSignal = closeSignal; this.closeSignal = closeSignal;
this.server = server; this.server = server;
} }

View File

@ -29,9 +29,7 @@ public class PrematureChannelClosureException extends CodecException {
/** /**
* Creates a new instance. * Creates a new instance.
*/ */
public PrematureChannelClosureException() { public PrematureChannelClosureException() { }
super();
}
/** /**
* Creates a new instance. * Creates a new instance.

View File

@ -297,7 +297,7 @@ public abstract class ReplayingDecoder<O, S extends Enum<S>> extends ByteToMessa
* Creates a new instance with the specified initial state. * Creates a new instance with the specified initial state.
*/ */
protected ReplayingDecoder(S initialState) { protected ReplayingDecoder(S initialState) {
this.state = initialState; state = initialState;
} }
/** /**

View File

@ -39,7 +39,7 @@ class ReplayingDecoderBuffer implements ByteBuf {
private final SwappedByteBuf swapped; private final SwappedByteBuf swapped;
private boolean terminated; private boolean terminated;
public static ReplayingDecoderBuffer EMPTY_BUFFER = new ReplayingDecoderBuffer(Unpooled.EMPTY_BUFFER); static final ReplayingDecoderBuffer EMPTY_BUFFER = new ReplayingDecoderBuffer(Unpooled.EMPTY_BUFFER);
static { static {
EMPTY_BUFFER.terminate(); EMPTY_BUFFER.terminate();

View File

@ -25,9 +25,7 @@ public class UnsupportedMessageTypeException extends CodecException {
message == null? "null" : message.getClass().getName(), expectedTypes)); message == null? "null" : message.getClass().getName(), expectedTypes));
} }
public UnsupportedMessageTypeException() { public UnsupportedMessageTypeException() { }
super();
}
public UnsupportedMessageTypeException(String message, Throwable cause) { public UnsupportedMessageTypeException(String message, Throwable cause) {
super(message, cause); super(message, cause);

View File

@ -296,9 +296,9 @@ public final class Base64 {
byte[] b4 = new byte[4]; byte[] b4 = new byte[4];
int b4Posn = 0; int b4Posn = 0;
int i = 0; int i;
byte sbiCrop = 0; byte sbiCrop;
byte sbiDecode = 0; byte sbiDecode;
for (i = off; i < off + len; i ++) { for (i = off; i < off + len; i ++) {
sbiCrop = (byte) (src.getByte(i) & 0x7f); // Only the low seven bits sbiCrop = (byte) (src.getByte(i) & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[sbiCrop]; sbiDecode = DECODABET[sbiCrop];

View File

@ -294,8 +294,7 @@ public class ZlibEncoder extends ByteToByteEncoder {
z.next_out = out.array(); z.next_out = out.array();
z.next_out_index = out.arrayOffset() + out.writerIndex(); z.next_out_index = out.arrayOffset() + out.writerIndex();
} else { } else {
byte[] array = new byte[maxOutputLength]; z.next_out = new byte[maxOutputLength];
z.next_out = array;
z.next_out_index = 0; z.next_out_index = 0;
} }
int oldNextOutIndex = z.next_out_index; int oldNextOutIndex = z.next_out_index;

View File

@ -21,12 +21,11 @@ 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 io.netty.util.VoidEnum; import io.netty.util.VoidEnum;
import java.io.ObjectStreamConstants;
import org.jboss.marshalling.ByteInput; import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.Unmarshaller;
import java.io.ObjectStreamConstants;
/** /**
* {@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}.
* *
@ -88,8 +87,7 @@ public class CompatibleMarshallingDecoder extends ReplayingDecoder<Object, VoidE
} }
} }
Object decoded = decode(ctx, buffer); return decode(ctx, buffer);
return decoded;
} }
@Override @Override

View File

@ -15,10 +15,10 @@
*/ */
package io.netty.handler.codec.marshalling; package io.netty.handler.codec.marshalling;
import java.io.IOException;
import org.jboss.marshalling.ByteInput; import org.jboss.marshalling.ByteInput;
import java.io.IOException;
/** /**
* {@link ByteInput} implementation which wraps another {@link ByteInput} and throws a {@link TooBigObjectException} * {@link ByteInput} implementation which wraps another {@link ByteInput} and throws a {@link TooBigObjectException}
* if the read limit was reached. * if the read limit was reached.
@ -47,9 +47,7 @@ class LimitingByteInput implements ByteInput {
@Override @Override
public int available() throws IOException { public int available() throws IOException {
int available = input.available(); return readable(input.available());
int readable = readable(available);
return readable;
} }
@Override @Override

View File

@ -35,7 +35,7 @@ import com.google.protobuf.CodedInputStream;
* +--------+---------------+ +---------------+ * +--------+---------------+ +---------------+
* </pre> * </pre>
* *
* @see com.google.protobuf.CodedInputStream * @see CodedInputStream
*/ */
public class ProtobufVarint32FrameDecoder extends ByteToMessageDecoder<Object> { public class ProtobufVarint32FrameDecoder extends ByteToMessageDecoder<Object> {

View File

@ -35,7 +35,7 @@ import com.google.protobuf.CodedOutputStream;
* +---------------+ +--------+---------------+ * +---------------+ +--------+---------------+
* </pre> * * </pre> *
* *
* @see com.google.protobuf.CodedOutputStream * @see CodedOutputStream
*/ */
@Sharable @Sharable
public class ProtobufVarint32LengthFieldPrepender extends MessageToByteEncoder<ByteBuf> { public class ProtobufVarint32LengthFieldPrepender extends MessageToByteEncoder<ByteBuf> {
@ -54,8 +54,7 @@ public class ProtobufVarint32LengthFieldPrepender extends MessageToByteEncoder<B
@Override @Override
public void encode( public void encode(
ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
ByteBuf body = msg; int bodyLen = msg.readableBytes();
int bodyLen = body.readableBytes();
int headerLen = CodedOutputStream.computeRawVarint32Size(bodyLen); int headerLen = CodedOutputStream.computeRawVarint32Size(bodyLen);
out.ensureWritableBytes(headerLen + bodyLen); out.ensureWritableBytes(headerLen + bodyLen);
@ -64,6 +63,6 @@ public class ProtobufVarint32LengthFieldPrepender extends MessageToByteEncoder<B
headerOut.writeRawVarint32(bodyLen); headerOut.writeRawVarint32(bodyLen);
headerOut.flush(); headerOut.flush();
out.writeBytes(body); out.writeBytes(msg, msg.readerIndex(), bodyLen);
} }
} }

View File

@ -15,6 +15,7 @@
*/ */
package io.netty.handler.codec.serialization; package io.netty.handler.codec.serialization;
import java.io.BufferedReader;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -192,7 +193,7 @@ public class ObjectDecoderInputStream extends InputStream implements
} }
/** /**
* @deprecated Use {@link java.io.BufferedReader#readLine()} instead. * @deprecated Use {@link BufferedReader#readLine()} instead.
*/ */
@Override @Override
@Deprecated @Deprecated

View File

@ -16,6 +16,7 @@
package io.netty.logging; package io.netty.logging;
import org.apache.commons.logging.LogFactory;
/** /**
* Logger factory which creates an * Logger factory which creates an
@ -26,8 +27,6 @@ public class CommonsLoggerFactory extends InternalLoggerFactory {
@Override @Override
public InternalLogger newInstance(String name) { public InternalLogger newInstance(String name) {
final org.apache.commons.logging.Log logger = return new CommonsLogger(LogFactory.getLog(name), name);
org.apache.commons.logging.LogFactory.getLog(name);
return new CommonsLogger(logger, name);
} }
} }

View File

@ -39,7 +39,7 @@ public final class DetectionUtil {
static { static {
String os = System.getProperty("os.name").toLowerCase(); String os = System.getProperty("os.name").toLowerCase();
// windows // windows
IS_WINDOWS = os.indexOf("win") >= 0; IS_WINDOWS = os.contains("win");
} }
/** /**

View File

@ -29,7 +29,7 @@ public final class StringUtil {
public static final String NEWLINE; public static final String NEWLINE;
static { static {
String newLine = null; String newLine;
try { try {
newLine = new Formatter().format("%n").toString(); newLine = new Formatter().format("%n").toString();

View File

@ -18,13 +18,12 @@ package io.netty.example.http.websocketx.sslserver;
import io.netty.logging.InternalLogger; import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory; import io.netty.logging.InternalLoggerFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.Security; import java.security.Security;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
/** /**
* Creates a {@link SSLContext} for just server certificates. * Creates a {@link SSLContext} for just server certificates.
*/ */
@ -48,7 +47,6 @@ public final class WebSocketSslServerSslContext {
* See http://en.wikipedia.org/wiki/Singleton_pattern * See http://en.wikipedia.org/wiki/Singleton_pattern
*/ */
private static class SingletonHolder { private static class SingletonHolder {
public static final WebSocketSslServerSslContext INSTANCE = new WebSocketSslServerSslContext(); public static final WebSocketSslServerSslContext INSTANCE = new WebSocketSslServerSslContext();
} }
@ -63,7 +61,7 @@ public final class WebSocketSslServerSslContext {
algorithm = "SunX509"; algorithm = "SunX509";
} }
SSLContext serverContext = null; SSLContext serverContext;
try { try {
String keyStoreFilePath = System.getProperty("keystore.file.path"); String keyStoreFilePath = System.getProperty("keystore.file.path");
String keyStoreFilePassword = System.getProperty("keystore.file.password"); String keyStoreFilePassword = System.getProperty("keystore.file.password");

View File

@ -17,15 +17,14 @@ package io.netty.example.securechat;
import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandler;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;
import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;
/** /**
* Creates a bogus {@link SSLContext}. A client-side context created by this * Creates a bogus {@link SSLContext}. A client-side context created by this
@ -62,8 +61,8 @@ public final class SecureChatSslContextFactory {
algorithm = "SunX509"; algorithm = "SunX509";
} }
SSLContext serverContext = null; SSLContext serverContext;
SSLContext clientContext = null; SSLContext clientContext;
try { try {
KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
ks.load(SecureChatKeyStore.asInputStream(), ks.load(SecureChatKeyStore.asInputStream(),

View File

@ -85,9 +85,7 @@ public class ByteLoggingHandler
} }
} }
public ByteLoggingHandler() { public ByteLoggingHandler() { }
super();
}
public ByteLoggingHandler(Class<?> clazz, LogLevel level) { public ByteLoggingHandler(Class<?> clazz, LogLevel level) {
super(clazz, level); super(clazz, level);

View File

@ -28,9 +28,7 @@ public class MessageLoggingHandler
extends LoggingHandler extends LoggingHandler
implements ChannelInboundMessageHandler<Object>, ChannelOutboundMessageHandler<Object> { implements ChannelInboundMessageHandler<Object>, ChannelOutboundMessageHandler<Object> {
public MessageLoggingHandler() { public MessageLoggingHandler() { }
super();
}
public MessageLoggingHandler(Class<?> clazz, LogLevel level) { public MessageLoggingHandler(Class<?> clazz, LogLevel level) {
super(clazz, level); super(clazz, level);

View File

@ -344,7 +344,7 @@ public class SslHandler
boolean unwrapLater = false; boolean unwrapLater = false;
int bytesProduced = 0; int bytesProduced = 0;
try { try {
loop: for (;;) { for (;;) {
SSLEngineResult result = wrap(engine, in, out); SSLEngineResult result = wrap(engine, in, out);
bytesProduced += result.bytesProduced(); bytesProduced += result.bytesProduced();
if (result.getStatus() == Status.CLOSED) { if (result.getStatus() == Status.CLOSED) {
@ -380,7 +380,7 @@ public class SslHandler
} }
if (result.bytesConsumed() == 0 && result.bytesProduced() == 0) { if (result.bytesConsumed() == 0 && result.bytesProduced() == 0) {
break loop; break;
} }
} }
} }
@ -503,7 +503,7 @@ public class SslHandler
} }
if (result.bytesConsumed() == 0 && result.bytesProduced() == 0) { if (result.bytesConsumed() == 0 && result.bytesProduced() == 0) {
break loop; break;
} }
} }

View File

@ -33,7 +33,7 @@ import java.nio.channels.FileChannel;
public class ChunkedNioFile implements ChunkedByteInput { public class ChunkedNioFile implements ChunkedByteInput {
private final FileChannel in; private final FileChannel in;
private long startOffset; private final long startOffset;
private final long endOffset; private final long endOffset;
private final int chunkSize; private final int chunkSize;
private long offset; private long offset;

View File

@ -35,7 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* A {@link ChannelHandler} that adds support for writing a large data stream * A {@link ChannelHandler} that adds support for writing a large data stream
* asynchronously neither spending a lot of memory nor getting * asynchronously neither spending a lot of memory nor getting
* {@link java.lang.OutOfMemoryError}. Large data streaming such as file * {@link OutOfMemoryError}. Large data streaming such as file
* transfer requires complicated state management in a {@link ChannelHandler} * transfer requires complicated state management in a {@link ChannelHandler}
* implementation. {@link ChunkedWriteHandler} manages such complicated states * implementation. {@link ChunkedWriteHandler} manages such complicated states
* so that you can send a large data stream without difficulties. * so that you can send a large data stream without difficulties.
@ -71,7 +71,6 @@ public class ChunkedWriteHandler
private static final InternalLogger logger = private static final InternalLogger logger =
InternalLoggerFactory.getInstance(ChunkedWriteHandler.class); InternalLoggerFactory.getInstance(ChunkedWriteHandler.class);
private final MessageBuf<Object> queue = Unpooled.messageBuffer(); private final MessageBuf<Object> queue = Unpooled.messageBuffer();
private final int maxPendingWrites; private final int maxPendingWrites;
private volatile ChannelHandlerContext ctx; private volatile ChannelHandlerContext ctx;

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.testsuite.transport.socket; package io.netty.testsuite.transport.socket;
import static org.junit.Assert.*;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.Channel; import io.netty.channel.Channel;
@ -25,13 +24,14 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.DatagramPacket;
import io.netty.util.NetworkConstants; import io.netty.util.NetworkConstants;
import org.junit.Assert;
import org.junit.Test;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Assert; import static org.junit.Assert.*;
import org.junit.Test;
public class DatagramMulticastTest extends AbstractDatagramTest { public class DatagramMulticastTest extends AbstractDatagramTest {
@ -89,8 +89,8 @@ public class DatagramMulticastTest extends AbstractDatagramTest {
private final class MulticastTestHandler extends ChannelInboundMessageHandlerAdapter<DatagramPacket> { private final class MulticastTestHandler extends ChannelInboundMessageHandlerAdapter<DatagramPacket> {
private final CountDownLatch latch = new CountDownLatch(1); private final CountDownLatch latch = new CountDownLatch(1);
private boolean done = false; private boolean done;
private volatile boolean fail = false; private volatile boolean fail;
@Override @Override
public void messageReceived( public void messageReceived(

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.testsuite.transport.socket; package io.netty.testsuite.transport.socket;
import static org.junit.Assert.*;
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;
@ -27,7 +26,15 @@ import io.netty.channel.ChannelInboundByteHandlerAdapter;
import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandler;
import org.junit.Test;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactorySpi;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -40,15 +47,7 @@ import java.security.cert.X509Certificate;
import java.util.Random; import java.util.Random;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.KeyManagerFactory; import static org.junit.Assert.*;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactorySpi;
import javax.net.ssl.X509TrustManager;
import org.junit.Test;
public class SocketSslEchoTest extends AbstractSocketTest { public class SocketSslEchoTest extends AbstractSocketTest {
@ -209,8 +208,8 @@ public class SocketSslEchoTest extends AbstractSocketTest {
algorithm = "SunX509"; algorithm = "SunX509";
} }
SSLContext serverContext = null; SSLContext serverContext;
SSLContext clientContext = null; SSLContext clientContext;
try { try {
KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
ks.load(BogusKeyStore.asInputStream(), ks.load(BogusKeyStore.asInputStream(),
@ -250,7 +249,7 @@ public class SocketSslEchoTest extends AbstractSocketTest {
} }
/** /**
* Bogus {@link javax.net.ssl.TrustManagerFactorySpi} which accepts any certificate * Bogus {@link TrustManagerFactorySpi} which accepts any certificate
* even if it is invalid. * even if it is invalid.
*/ */
private static class BogusTrustManagerFactory extends TrustManagerFactorySpi { private static class BogusTrustManagerFactory extends TrustManagerFactorySpi {

View File

@ -152,7 +152,7 @@ final class SocketTestPermutation {
} }
private SocketTestPermutation() {} private SocketTestPermutation() {}
static interface Factory<T> { interface Factory<T> {
T newInstance(); T newInstance();
} }
} }

View File

@ -42,4 +42,6 @@ public class TestUtils {
} }
throw new RuntimeException("Unable to find a free port...."); throw new RuntimeException("Unable to find a free port....");
} }
private TestUtils() { }
} }

View File

@ -167,6 +167,13 @@ public class ServerBootstrap {
return future; return future;
} }
try {
channel.config().setOptions(parentOptions);
} catch (Exception e) {
future.setFailure(e);
return future;
}
ChannelPipeline p = channel.pipeline(); ChannelPipeline p = channel.pipeline();
if (handler != null) { if (handler != null) {
p.addLast(handler); p.addLast(handler);

View File

@ -728,18 +728,18 @@ public abstract class AbstractChannel extends DefaultAttributeMap implements Cha
return; return;
} }
final long writeCounter = AbstractChannel.this.writeCounter; final long writeCounter = this.writeCounter;
for (;;) { for (;;) {
FlushCheckpoint cp = flushCheckpoints.peek(); FlushCheckpoint cp = flushCheckpoints.peek();
if (cp == null) { if (cp == null) {
// Reset the counter if there's nothing in the notification list. // Reset the counter if there's nothing in the notification list.
AbstractChannel.this.writeCounter = 0; this.writeCounter = 0;
break; break;
} }
if (cp.flushCheckpoint() > writeCounter) { if (cp.flushCheckpoint() > writeCounter) {
if (writeCounter > 0 && flushCheckpoints.size() == 1) { if (writeCounter > 0 && flushCheckpoints.size() == 1) {
AbstractChannel.this.writeCounter = 0; this.writeCounter = 0;
cp.flushCheckpoint(cp.flushCheckpoint() - writeCounter); cp.flushCheckpoint(cp.flushCheckpoint() - writeCounter);
} }
break; break;
@ -750,11 +750,11 @@ public abstract class AbstractChannel extends DefaultAttributeMap implements Cha
} }
// Avoid overflow // Avoid overflow
final long newWriteCounter = AbstractChannel.this.writeCounter; final long newWriteCounter = this.writeCounter;
if (newWriteCounter >= 0x1000000000000000L) { if (newWriteCounter >= 0x1000000000000000L) {
// Reset the counter only when the counter grew pretty large // Reset the counter only when the counter grew pretty large
// so that we can reduce the cost of updating all entries in the notification list. // so that we can reduce the cost of updating all entries in the notification list.
AbstractChannel.this.writeCounter = 0; this.writeCounter = 0;
for (FlushCheckpoint cp: flushCheckpoints) { for (FlushCheckpoint cp: flushCheckpoints) {
cp.flushCheckpoint(cp.flushCheckpoint() - newWriteCounter); cp.flushCheckpoint(cp.flushCheckpoint() - newWriteCounter);
} }

View File

@ -178,7 +178,7 @@ public interface Channel extends AttributeMap, ChannelOutboundInvoker, ChannelFu
Unsafe unsafe(); Unsafe unsafe();
public interface Unsafe { interface Unsafe {
ChannelHandlerContext directOutboundContext(); ChannelHandlerContext directOutboundContext();
ChannelFuture voidFuture(); ChannelFuture voidFuture();

View File

@ -17,5 +17,5 @@ package io.netty.channel;
public enum ChannelBufferType { public enum ChannelBufferType {
BYTE, BYTE,
MESSAGE; MESSAGE
} }

View File

@ -23,7 +23,7 @@ public enum ChannelHandlerType {
final int direction; // 0 - up (inbound), 1 - down (outbound) final int direction; // 0 - up (inbound), 1 - down (outbound)
private ChannelHandlerType(int direction) { ChannelHandlerType(int direction) {
this.direction = direction; this.direction = direction;
} }
} }

View File

@ -209,7 +209,7 @@ public class DefaultChannelFuture extends FlushCheckpoint implements ChannelFutu
checkDeadLock(); checkDeadLock();
waiters++; waiters++;
try { try {
this.wait(); wait();
} finally { } finally {
waiters--; waiters--;
} }
@ -237,7 +237,7 @@ public class DefaultChannelFuture extends FlushCheckpoint implements ChannelFutu
checkDeadLock(); checkDeadLock();
waiters++; waiters++;
try { try {
this.wait(); wait();
} catch (InterruptedException e) { } catch (InterruptedException e) {
interrupted = true; interrupted = true;
} finally { } finally {
@ -293,7 +293,7 @@ public class DefaultChannelFuture extends FlushCheckpoint implements ChannelFutu
try { try {
for (;;) { for (;;) {
try { try {
this.wait(waitTime / 1000000, (int) (waitTime % 1000000)); wait(waitTime / 1000000, (int) (waitTime % 1000000));
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (interruptable) { if (interruptable) {
throw e; throw e;

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.channel; package io.netty.channel;
import static io.netty.channel.DefaultChannelPipeline.*;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.ChannelBuf; import io.netty.buffer.ChannelBuf;
import io.netty.buffer.MessageBuf; import io.netty.buffer.MessageBuf;
@ -30,6 +29,8 @@ import java.util.Set;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static io.netty.channel.DefaultChannelPipeline.*;
final class DefaultChannelHandlerContext extends DefaultAttributeMap implements ChannelHandlerContext { final class DefaultChannelHandlerContext extends DefaultAttributeMap implements ChannelHandlerContext {
private static final EnumSet<ChannelHandlerType> EMPTY_TYPE = EnumSet.noneOf(ChannelHandlerType.class); private static final EnumSet<ChannelHandlerType> EMPTY_TYPE = EnumSet.noneOf(ChannelHandlerType.class);
@ -757,9 +758,7 @@ final class DefaultChannelHandlerContext extends DefaultAttributeMap implements
break; break;
} }
for (Object d: data) { Collections.addAll(out, data);
out.add(d);
}
} }
} }
} }

View File

@ -22,7 +22,7 @@ public interface EventExecutor extends ScheduledExecutorService {
boolean inEventLoop(Thread thread); boolean inEventLoop(Thread thread);
Unsafe unsafe(); Unsafe unsafe();
public interface Unsafe { interface Unsafe {
EventExecutor nextChild(); EventExecutor nextChild();
} }
} }

View File

@ -514,8 +514,8 @@ public abstract class SingleThreadEventExecutor extends AbstractExecutorService
ScheduledFutureTask(Runnable runnable, V result, long nanoTime) { ScheduledFutureTask(Runnable runnable, V result, long nanoTime) {
super(runnable, result); super(runnable, result);
this.deadlineNanos = nanoTime; deadlineNanos = nanoTime;
this.periodNanos = 0; periodNanos = 0;
} }
ScheduledFutureTask(Runnable runnable, V result, long nanoTime, long period) { ScheduledFutureTask(Runnable runnable, V result, long nanoTime, long period) {
@ -524,14 +524,14 @@ public abstract class SingleThreadEventExecutor extends AbstractExecutorService
throw new IllegalArgumentException( throw new IllegalArgumentException(
String.format("period: %d (expected: != 0)", period)); String.format("period: %d (expected: != 0)", period));
} }
this.deadlineNanos = nanoTime; deadlineNanos = nanoTime;
this.periodNanos = period; periodNanos = period;
} }
ScheduledFutureTask(Callable<V> callable, long nanoTime) { ScheduledFutureTask(Callable<V> callable, long nanoTime) {
super(callable); super(callable);
this.deadlineNanos = nanoTime; deadlineNanos = nanoTime;
this.periodNanos = 0; periodNanos = 0;
} }
public long deadlineNanos() { public long deadlineNanos() {

View File

@ -41,7 +41,6 @@ public abstract class AbstractEmbeddedChannel extends AbstractChannel {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractEmbeddedChannel.class); private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractEmbeddedChannel.class);
private final EmbeddedEventLoop loop = new EmbeddedEventLoop();
private final ChannelConfig config = new DefaultChannelConfig(); private final ChannelConfig config = new DefaultChannelConfig();
private final SocketAddress localAddress = new EmbeddedSocketAddress(); private final SocketAddress localAddress = new EmbeddedSocketAddress();
private final SocketAddress remoteAddress = new EmbeddedSocketAddress(); private final SocketAddress remoteAddress = new EmbeddedSocketAddress();
@ -83,7 +82,7 @@ public abstract class AbstractEmbeddedChannel extends AbstractChannel {
} }
p.addLast(new LastInboundMessageHandler(), new LastInboundByteHandler()); p.addLast(new LastInboundMessageHandler(), new LastInboundByteHandler());
loop.register(this); new EmbeddedEventLoop().register(this);
} }
@Override @Override

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.channel.group; package io.netty.channel.group;
import static java.util.concurrent.TimeUnit.*;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelFutureListener;
@ -32,6 +31,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.*;
/** /**
* The default {@link ChannelGroupFuture} implementation. * The default {@link ChannelGroupFuture} implementation.
*/ */
@ -53,7 +54,7 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
@Override @Override
public void operationComplete(ChannelFuture future) throws Exception { public void operationComplete(ChannelFuture future) throws Exception {
boolean success = future.isSuccess(); boolean success = future.isSuccess();
boolean callSetDone = false; boolean callSetDone;
synchronized (DefaultChannelGroupFuture.this) { synchronized (DefaultChannelGroupFuture.this) {
if (success) { if (success) {
successCount ++; successCount ++;
@ -219,7 +220,7 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
checkDeadLock(); checkDeadLock();
waiters++; waiters++;
try { try {
this.wait(); wait();
} finally { } finally {
waiters--; waiters--;
} }
@ -247,7 +248,7 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
checkDeadLock(); checkDeadLock();
waiters++; waiters++;
try { try {
this.wait(); wait();
} catch (InterruptedException e) { } catch (InterruptedException e) {
interrupted = true; interrupted = true;
} finally { } finally {
@ -303,7 +304,7 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
try { try {
for (;;) { for (;;) {
try { try {
this.wait(waitTime / 1000000, (int) (waitTime % 1000000)); wait(waitTime / 1000000, (int) (waitTime % 1000000));
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (interruptable) { if (interruptable) {
throw e; throw e;
@ -341,11 +342,11 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
} }
} }
boolean setDone() { void setDone() {
synchronized (this) { synchronized (this) {
// Allow only once. // Allow only once.
if (done) { if (done) {
return false; return;
} }
done = true; done = true;
@ -355,7 +356,6 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
} }
notifyListeners(); notifyListeners();
return true;
} }
private void notifyListeners() { private void notifyListeners() {

View File

@ -23,6 +23,7 @@ import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.DefaultChannelConfig; import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.EventLoop; import io.netty.channel.EventLoop;
import io.netty.channel.SingleThreadEventExecutor;
import io.netty.channel.SingleThreadEventLoop; import io.netty.channel.SingleThreadEventLoop;
import java.net.SocketAddress; import java.net.SocketAddress;
@ -152,7 +153,7 @@ public class LocalChannel extends AbstractChannel {
postRegisterTask = null; postRegisterTask = null;
} }
((SingleThreadEventLoop) eventLoop()).addShutdownHook(shutdownHook); ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook);
return postRegisterTask; return postRegisterTask;
} }
@ -198,7 +199,7 @@ public class LocalChannel extends AbstractChannel {
if (isOpen()) { if (isOpen()) {
unsafe().close(unsafe().voidFuture()); unsafe().close(unsafe().voidFuture());
} }
((SingleThreadEventLoop) eventLoop()).removeShutdownHook(shutdownHook); ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook);
} }
@Override @Override

View File

@ -20,6 +20,7 @@ import io.netty.channel.ChannelConfig;
import io.netty.channel.DefaultChannelConfig; import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.EventLoop; import io.netty.channel.EventLoop;
import io.netty.channel.ServerChannel; import io.netty.channel.ServerChannel;
import io.netty.channel.SingleThreadEventExecutor;
import io.netty.channel.SingleThreadEventLoop; import io.netty.channel.SingleThreadEventLoop;
import java.net.SocketAddress; import java.net.SocketAddress;
@ -85,7 +86,7 @@ public class LocalServerChannel extends AbstractServerChannel {
@Override @Override
protected Runnable doRegister() throws Exception { protected Runnable doRegister() throws Exception {
((SingleThreadEventLoop) eventLoop()).addShutdownHook(shutdownHook); ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook);
return null; return null;
} }
@ -115,7 +116,7 @@ public class LocalServerChannel extends AbstractServerChannel {
@Override @Override
protected void doDeregister() throws Exception { protected void doDeregister() throws Exception {
((SingleThreadEventLoop) eventLoop()).removeShutdownHook(shutdownHook); ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook);
} }
LocalChannel serve(final LocalChannel peer) { LocalChannel serve(final LocalChannel peer) {

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.channel.socket; package io.netty.channel.socket;
import static io.netty.channel.ChannelOption.*;
import io.netty.channel.ChannelException; import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultChannelConfig; import io.netty.channel.DefaultChannelConfig;
@ -28,12 +27,14 @@ import java.net.NetworkInterface;
import java.net.SocketException; import java.net.SocketException;
import java.util.Map; import java.util.Map;
import static io.netty.channel.ChannelOption.*;
/** /**
* The default {@link DatagramChannelConfig} implementation. * The default {@link DatagramChannelConfig} implementation.
*/ */
public class DefaultDatagramChannelConfig extends DefaultChannelConfig implements DatagramChannelConfig { public class DefaultDatagramChannelConfig extends DefaultChannelConfig implements DatagramChannelConfig {
private static int DEFAULT_RECEIVE_PACKET_SIZE = 2048; private static final int DEFAULT_RECEIVE_PACKET_SIZE = 2048;
private final DatagramSocket socket; private final DatagramSocket socket;
private volatile int receivePacketSize = DEFAULT_RECEIVE_PACKET_SIZE; private volatile int receivePacketSize = DEFAULT_RECEIVE_PACKET_SIZE;

View File

@ -20,5 +20,5 @@ package io.netty.channel.socket;
*/ */
public enum InternetProtocolFamily { public enum InternetProtocolFamily {
IPv4, IPv4,
IPv6; IPv6
} }

View File

@ -144,13 +144,9 @@ public abstract class AbstractNioChannel extends AbstractChannel {
connectTimeoutException = new ConnectException("connection timed out"); connectTimeoutException = new ConnectException("connection timed out");
} }
ChannelFuture connectFuture = AbstractNioChannel.this.connectFuture; ChannelFuture connectFuture = AbstractNioChannel.this.connectFuture;
if (connectFuture == null) { if (connectFuture != null && connectFuture.setFailure(connectTimeoutException)) {
return; pipeline().fireExceptionCaught(connectTimeoutException);
} else { close(voidFuture());
if (connectFuture.setFailure(connectTimeoutException)) {
pipeline().fireExceptionCaught(connectTimeoutException);
close(voidFuture());
}
} }
} }
}, connectTimeoutMillis, TimeUnit.MILLISECONDS); }, connectTimeoutMillis, TimeUnit.MILLISECONDS);

View File

@ -24,6 +24,7 @@ import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.nio.channels.SelectionKey; import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel; import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Queue; import java.util.Queue;
public class NioServerSocketChannel extends AbstractNioMessageChannel public class NioServerSocketChannel extends AbstractNioMessageChannel
@ -61,7 +62,7 @@ public class NioServerSocketChannel extends AbstractNioMessageChannel
} }
@Override @Override
protected java.nio.channels.ServerSocketChannel javaChannel() { protected ServerSocketChannel javaChannel() {
return (ServerSocketChannel) super.javaChannel(); return (ServerSocketChannel) super.javaChannel();
} }
@ -84,7 +85,7 @@ public class NioServerSocketChannel extends AbstractNioMessageChannel
@Override @Override
protected int doReadMessages(Queue<Object> buf) throws Exception { protected int doReadMessages(Queue<Object> buf) throws Exception {
java.nio.channels.SocketChannel ch = javaChannel().accept(); SocketChannel ch = javaChannel().accept();
if (ch == null) { if (ch == null) {
return 0; return 0;
} }

View File

@ -17,6 +17,9 @@ package io.netty.channel.socket.nio;
import io.netty.channel.socket.InternetProtocolFamily; import io.netty.channel.socket.InternetProtocolFamily;
import java.net.ProtocolFamily;
import java.net.StandardProtocolFamily;
/** /**
* Helper class which convert the {@link InternetProtocolFamily}. * Helper class which convert the {@link InternetProtocolFamily}.
* *
@ -31,13 +34,13 @@ final class ProtocolFamilyConverter {
/** /**
* Convert the {@link InternetProtocolFamily}. This MUST only be called on jdk version >= 7. * Convert the {@link InternetProtocolFamily}. This MUST only be called on jdk version >= 7.
*/ */
public static java.net.ProtocolFamily convert(InternetProtocolFamily family) { public static ProtocolFamily convert(InternetProtocolFamily family) {
switch (family) { switch (family) {
case IPv4: case IPv4:
return java.net.StandardProtocolFamily.INET; return StandardProtocolFamily.INET;
case IPv6: case IPv6:
return java.net.StandardProtocolFamily.INET6; return StandardProtocolFamily.INET6;
default: default:
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }

View File

@ -73,6 +73,16 @@ abstract class AbstractOioByteChannel extends AbstractOioChannel {
} }
} }
} }
private void expandReadBuffer(ByteBuf byteBuf) {
int available = available();
if (available > 0) {
byteBuf.ensureWritableBytes(available);
} else if (!byteBuf.writable()) {
// FIXME: Magic number
byteBuf.ensureWritableBytes(4096);
}
}
} }
@Override @Override
@ -85,15 +95,5 @@ abstract class AbstractOioByteChannel extends AbstractOioChannel {
protected abstract int available(); protected abstract int available();
protected abstract int doReadBytes(ByteBuf buf) throws Exception; protected abstract int doReadBytes(ByteBuf buf) throws Exception;
protected abstract int doWriteBytes(ByteBuf buf) throws Exception; protected abstract void doWriteBytes(ByteBuf buf) throws Exception;
private void expandReadBuffer(ByteBuf byteBuf) {
int available = available();
if (available > 0) {
byteBuf.ensureWritableBytes(available);
} else if (!byteBuf.writable()) {
// FIXME: Magic number
byteBuf.ensureWritableBytes(4096);
}
}
} }

View File

@ -82,5 +82,5 @@ abstract class AbstractOioMessageChannel extends AbstractOioChannel {
} }
protected abstract int doReadMessages(Queue<Object> buf) throws Exception; protected abstract int doReadMessages(Queue<Object> buf) throws Exception;
protected abstract int doWriteMessages(Queue<Object> buf) throws Exception; protected abstract void doWriteMessages(Queue<Object> buf) throws Exception;
} }

View File

@ -48,7 +48,7 @@ class OioChildEventLoop extends SingleThreadEventLoop {
@Override @Override
protected void run() { protected void run() {
for (;;) { for (;;) {
AbstractOioChannel ch = OioChildEventLoop.this.ch; AbstractOioChannel ch = this.ch;
if (ch == null || !ch.isActive()) { if (ch == null || !ch.isActive()) {
Runnable task; Runnable task;
try { try {

View File

@ -173,7 +173,7 @@ public class OioDatagramChannel extends AbstractOioMessageChannel
} }
@Override @Override
protected int doWriteMessages(Queue<Object> buf) throws Exception { protected void doWriteMessages(Queue<Object> buf) throws Exception {
DatagramPacket p = (DatagramPacket) buf.poll(); DatagramPacket p = (DatagramPacket) buf.poll();
ByteBuf data = p.data(); ByteBuf data = p.data();
int length = data.readableBytes(); int length = data.readableBytes();
@ -187,7 +187,6 @@ public class OioDatagramChannel extends AbstractOioMessageChannel
} }
socket.send(tmpPacket); socket.send(tmpPacket);
return 1;
} }
@Override @Override

View File

@ -270,7 +270,7 @@ public class OioEventLoop implements EventLoop {
if (maxChannels > 0 && activeChildren.size() >= maxChannels) { if (maxChannels > 0 && activeChildren.size() >= maxChannels) {
throw tooManyChannels; throw tooManyChannels;
} }
loop = new OioChildEventLoop(OioEventLoop.this); loop = new OioChildEventLoop(this);
} }
activeChildren.add(loop); activeChildren.add(loop);
return loop; return loop;

View File

@ -169,7 +169,7 @@ public class OioServerSocketChannel extends AbstractOioMessageChannel
} }
@Override @Override
protected int doWriteMessages(Queue<Object> buf) throws Exception { protected void doWriteMessages(Queue<Object> buf) throws Exception {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@ -159,13 +159,11 @@ public class OioSocketChannel extends AbstractOioByteChannel
} }
@Override @Override
protected int doWriteBytes(ByteBuf buf) throws Exception { protected void doWriteBytes(ByteBuf buf) throws Exception {
OutputStream os = this.os; OutputStream os = this.os;
if (os == null) { if (os == null) {
throw new NotYetConnectedException(); throw new NotYetConnectedException();
} }
final int length = buf.readableBytes(); buf.readBytes(os, buf.readableBytes());
buf.readBytes(os, length);
return length;
} }
} }

View File

@ -32,7 +32,7 @@ public class LocalChannelRegistryTest {
private static final InternalLogger logger = private static final InternalLogger logger =
InternalLoggerFactory.getInstance(LocalChannelRegistryTest.class); InternalLoggerFactory.getInstance(LocalChannelRegistryTest.class);
private static String LOCAL_ADDR_ID = "test.id"; private static final String LOCAL_ADDR_ID = "test.id";
@Test @Test
public void testLocalAddressReuse() throws Exception { public void testLocalAddressReuse() throws Exception {