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

View File

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

View File

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

View File

@ -269,7 +269,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
return readFixedLengthContent(buffer);
}
case READ_FIXED_LENGTH_CONTENT_AS_CHUNKS: {
assert this.chunkSize <= Integer.MAX_VALUE;
assert chunkSize <= Integer.MAX_VALUE;
int chunkSize = (int) this.chunkSize;
int readLimit = actualReadableBytes();
int toRead = chunkSize;
@ -322,7 +322,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
return chunk;
}
case READ_CHUNKED_CONTENT_AS_CHUNKS: {
assert this.chunkSize <= Integer.MAX_VALUE;
assert chunkSize <= Integer.MAX_VALUE;
int chunkSize = (int) this.chunkSize;
int readLimit = actualReadableBytes();
int toRead = chunkSize;
@ -440,7 +440,7 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<Object, HttpMe
if (toRead > actualReadableBytes()) {
toRead = actualReadableBytes();
}
contentRead = contentRead + toRead;
contentRead += toRead;
if (length < contentRead) {
if (!message.isChunked()) {
message.setChunked(true);

View File

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

View File

@ -103,27 +103,26 @@ public class WebSocket08FrameEncoder extends MessageToByteEncoder<WebSocketFrame
WebSocketFrame msg, ByteBuf out) throws Exception {
byte[] mask;
WebSocketFrame frame = msg;
ByteBuf data = frame.getBinaryData();
ByteBuf data = msg.getBinaryData();
if (data == null) {
data = Unpooled.EMPTY_BUFFER;
}
byte opcode;
if (frame instanceof TextWebSocketFrame) {
if (msg instanceof TextWebSocketFrame) {
opcode = OPCODE_TEXT;
} else if (frame instanceof PingWebSocketFrame) {
} else if (msg instanceof PingWebSocketFrame) {
opcode = OPCODE_PING;
} else if (frame instanceof PongWebSocketFrame) {
} else if (msg instanceof PongWebSocketFrame) {
opcode = OPCODE_PONG;
} else if (frame instanceof CloseWebSocketFrame) {
} else if (msg instanceof CloseWebSocketFrame) {
opcode = OPCODE_CLOSE;
} else if (frame instanceof BinaryWebSocketFrame) {
} else if (msg instanceof BinaryWebSocketFrame) {
opcode = OPCODE_BINARY;
} else if (frame instanceof ContinuationWebSocketFrame) {
} else if (msg instanceof ContinuationWebSocketFrame) {
opcode = OPCODE_CONT;
} 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();
@ -133,10 +132,10 @@ public class WebSocket08FrameEncoder extends MessageToByteEncoder<WebSocketFrame
}
int b0 = 0;
if (frame.isFinalFragment()) {
if (msg.isFinalFragment()) {
b0 |= 1 << 7;
}
b0 |= frame.getRsv() % 8 << 4;
b0 |= msg.getRsv() % 8 << 4;
b0 |= opcode % 128;
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.handler.codec.http.HttpRequest;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
@ -79,9 +80,7 @@ public abstract class WebSocketServerHandshaker {
*/
public Set<String> getSubprotocols() {
Set<String> ret = new LinkedHashSet<String>();
for (String p: subprotocols) {
ret.add(p);
}
Collections.addAll(ret, subprotocols);
return ret;
}

View File

@ -383,10 +383,8 @@ public final class RtspHeaders {
*/
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
@Deprecated
public boolean isCompressed() {
return compressed;
}
@Override
@Deprecated
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,6 @@
*/
package io.netty.handler.codec.spdy;
import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
@ -26,6 +25,8 @@ import io.netty.handler.codec.UnsupportedMessageTypeException;
import java.util.Set;
import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
/**
* 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.
*/
public SpdyFrameEncoder(int version, int compressionLevel, int windowBits, int memLevel) {
super();
if (version < SpdyConstants.SPDY_MIN_VERSION || version > SpdyConstants.SPDY_MAX_VERSION) {
throw new IllegalArgumentException(
"unknown version: " + version);

View File

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

View File

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

View File

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

View File

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

View File

@ -259,11 +259,6 @@ final class SpdySession {
}
private final class PriorityComparator implements Comparator<Integer> {
public PriorityComparator() {
super();
}
@Override
public int compare(Integer id1, Integer id2) {
StreamState state1 = activeStreams.get(id1);

View File

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

View File

@ -15,7 +15,7 @@
*/
package io.netty.handler.codec.http;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
@ -23,7 +23,7 @@ import java.util.Iterator;
import java.util.Set;
import java.util.TimeZone;
import org.junit.Test;
import static org.junit.Assert.*;
public class CookieDecoderTest {
@Test
@ -350,7 +350,7 @@ public class CookieDecoderTest {
@Test
public void testDecodingLongDates() {
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;
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.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class SpdySessionHandlerTest {
private static final InternalLogger logger =
@ -278,7 +277,6 @@ public class SpdySessionHandlerTest {
private final boolean server;
EchoHandler(int closeSignal, boolean server) {
super();
this.closeSignal = closeSignal;
this.server = server;
}

View File

@ -29,9 +29,7 @@ public class PrematureChannelClosureException extends CodecException {
/**
* Creates a new instance.
*/
public PrematureChannelClosureException() {
super();
}
public PrematureChannelClosureException() { }
/**
* 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.
*/
protected ReplayingDecoder(S initialState) {
this.state = initialState;
state = initialState;
}
/**

View File

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

View File

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

View File

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

View File

@ -294,8 +294,7 @@ public class ZlibEncoder extends ByteToByteEncoder {
z.next_out = out.array();
z.next_out_index = out.arrayOffset() + out.writerIndex();
} else {
byte[] array = new byte[maxOutputLength];
z.next_out = array;
z.next_out = new byte[maxOutputLength];
z.next_out_index = 0;
}
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.TooLongFrameException;
import io.netty.util.VoidEnum;
import java.io.ObjectStreamConstants;
import org.jboss.marshalling.ByteInput;
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}.
*
@ -88,8 +87,7 @@ public class CompatibleMarshallingDecoder extends ReplayingDecoder<Object, VoidE
}
}
Object decoded = decode(ctx, buffer);
return decoded;
return decode(ctx, buffer);
}
@Override

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@
*/
package io.netty.handler.codec.serialization;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
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
@Deprecated

View File

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

View File

@ -39,7 +39,7 @@ public final class DetectionUtil {
static {
String os = System.getProperty("os.name").toLowerCase();
// 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;
static {
String newLine = null;
String newLine;
try {
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.InternalLoggerFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.Security;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
/**
* Creates a {@link SSLContext} for just server certificates.
*/
@ -48,7 +47,6 @@ public final class WebSocketSslServerSslContext {
* See http://en.wikipedia.org/wiki/Singleton_pattern
*/
private static class SingletonHolder {
public static final WebSocketSslServerSslContext INSTANCE = new WebSocketSslServerSslContext();
}
@ -63,7 +61,7 @@ public final class WebSocketSslServerSslContext {
algorithm = "SunX509";
}
SSLContext serverContext = null;
SSLContext serverContext;
try {
String keyStoreFilePath = System.getProperty("keystore.file.path");
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 java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
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
@ -62,8 +61,8 @@ public final class SecureChatSslContextFactory {
algorithm = "SunX509";
}
SSLContext serverContext = null;
SSLContext clientContext = null;
SSLContext serverContext;
SSLContext clientContext;
try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(SecureChatKeyStore.asInputStream(),

View File

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

View File

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

View File

@ -344,7 +344,7 @@ public class SslHandler
boolean unwrapLater = false;
int bytesProduced = 0;
try {
loop: for (;;) {
for (;;) {
SSLEngineResult result = wrap(engine, in, out);
bytesProduced += result.bytesProduced();
if (result.getStatus() == Status.CLOSED) {
@ -380,7 +380,7 @@ public class SslHandler
}
if (result.bytesConsumed() == 0 && result.bytesProduced() == 0) {
break loop;
break;
}
}
}
@ -503,7 +503,7 @@ public class SslHandler
}
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 {
private final FileChannel in;
private long startOffset;
private final long startOffset;
private final long endOffset;
private final int chunkSize;
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
* 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}
* implementation. {@link ChunkedWriteHandler} manages such complicated states
* so that you can send a large data stream without difficulties.
@ -71,7 +71,6 @@ public class ChunkedWriteHandler
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(ChunkedWriteHandler.class);
private final MessageBuf<Object> queue = Unpooled.messageBuffer();
private final int maxPendingWrites;
private volatile ChannelHandlerContext ctx;

View File

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

View File

@ -15,7 +15,6 @@
*/
package io.netty.testsuite.transport.socket;
import static org.junit.Assert.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
@ -27,7 +26,15 @@ import io.netty.channel.ChannelInboundByteHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
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.IOException;
import java.io.InputStream;
@ -40,15 +47,7 @@ import java.security.cert.X509Certificate;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
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 org.junit.Test;
import static org.junit.Assert.*;
public class SocketSslEchoTest extends AbstractSocketTest {
@ -209,8 +208,8 @@ public class SocketSslEchoTest extends AbstractSocketTest {
algorithm = "SunX509";
}
SSLContext serverContext = null;
SSLContext clientContext = null;
SSLContext serverContext;
SSLContext clientContext;
try {
KeyStore ks = KeyStore.getInstance("JKS");
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.
*/
private static class BogusTrustManagerFactory extends TrustManagerFactorySpi {

View File

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

View File

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

View File

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

View File

@ -728,18 +728,18 @@ public abstract class AbstractChannel extends DefaultAttributeMap implements Cha
return;
}
final long writeCounter = AbstractChannel.this.writeCounter;
final long writeCounter = this.writeCounter;
for (;;) {
FlushCheckpoint cp = flushCheckpoints.peek();
if (cp == null) {
// Reset the counter if there's nothing in the notification list.
AbstractChannel.this.writeCounter = 0;
this.writeCounter = 0;
break;
}
if (cp.flushCheckpoint() > writeCounter) {
if (writeCounter > 0 && flushCheckpoints.size() == 1) {
AbstractChannel.this.writeCounter = 0;
this.writeCounter = 0;
cp.flushCheckpoint(cp.flushCheckpoint() - writeCounter);
}
break;
@ -750,11 +750,11 @@ public abstract class AbstractChannel extends DefaultAttributeMap implements Cha
}
// Avoid overflow
final long newWriteCounter = AbstractChannel.this.writeCounter;
final long newWriteCounter = this.writeCounter;
if (newWriteCounter >= 0x1000000000000000L) {
// 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.
AbstractChannel.this.writeCounter = 0;
this.writeCounter = 0;
for (FlushCheckpoint cp: flushCheckpoints) {
cp.flushCheckpoint(cp.flushCheckpoint() - newWriteCounter);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -514,8 +514,8 @@ public abstract class SingleThreadEventExecutor extends AbstractExecutorService
ScheduledFutureTask(Runnable runnable, V result, long nanoTime) {
super(runnable, result);
this.deadlineNanos = nanoTime;
this.periodNanos = 0;
deadlineNanos = nanoTime;
periodNanos = 0;
}
ScheduledFutureTask(Runnable runnable, V result, long nanoTime, long period) {
@ -524,14 +524,14 @@ public abstract class SingleThreadEventExecutor extends AbstractExecutorService
throw new IllegalArgumentException(
String.format("period: %d (expected: != 0)", period));
}
this.deadlineNanos = nanoTime;
this.periodNanos = period;
deadlineNanos = nanoTime;
periodNanos = period;
}
ScheduledFutureTask(Callable<V> callable, long nanoTime) {
super(callable);
this.deadlineNanos = nanoTime;
this.periodNanos = 0;
deadlineNanos = nanoTime;
periodNanos = 0;
}
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 final EmbeddedEventLoop loop = new EmbeddedEventLoop();
private final ChannelConfig config = new DefaultChannelConfig();
private final SocketAddress localAddress = new EmbeddedSocketAddress();
private final SocketAddress remoteAddress = new EmbeddedSocketAddress();
@ -83,7 +82,7 @@ public abstract class AbstractEmbeddedChannel extends AbstractChannel {
}
p.addLast(new LastInboundMessageHandler(), new LastInboundByteHandler());
loop.register(this);
new EmbeddedEventLoop().register(this);
}
@Override

View File

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

View File

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

View File

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

View File

@ -15,7 +15,6 @@
*/
package io.netty.channel.socket;
import static io.netty.channel.ChannelOption.*;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultChannelConfig;
@ -28,12 +27,14 @@ import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Map;
import static io.netty.channel.ChannelOption.*;
/**
* The default {@link DatagramChannelConfig} implementation.
*/
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 volatile int receivePacketSize = DEFAULT_RECEIVE_PACKET_SIZE;

View File

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

View File

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

View File

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

View File

@ -17,6 +17,9 @@ package io.netty.channel.socket.nio;
import io.netty.channel.socket.InternetProtocolFamily;
import java.net.ProtocolFamily;
import java.net.StandardProtocolFamily;
/**
* 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.
*/
public static java.net.ProtocolFamily convert(InternetProtocolFamily family) {
public static ProtocolFamily convert(InternetProtocolFamily family) {
switch (family) {
case IPv4:
return java.net.StandardProtocolFamily.INET;
return StandardProtocolFamily.INET;
case IPv6:
return java.net.StandardProtocolFamily.INET6;
return StandardProtocolFamily.INET6;
default:
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
@ -85,15 +95,5 @@ abstract class AbstractOioByteChannel extends AbstractOioChannel {
protected abstract int available();
protected abstract int doReadBytes(ByteBuf buf) throws Exception;
protected abstract int 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);
}
}
protected abstract void doWriteBytes(ByteBuf buf) throws Exception;
}

View File

@ -82,5 +82,5 @@ abstract class AbstractOioMessageChannel extends AbstractOioChannel {
}
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
protected void run() {
for (;;) {
AbstractOioChannel ch = OioChildEventLoop.this.ch;
AbstractOioChannel ch = this.ch;
if (ch == null || !ch.isActive()) {
Runnable task;
try {

View File

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

View File

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

View File

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

View File

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

View File

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