merge upstream master

This commit is contained in:
Jestan Nirojan 2012-02-19 12:37:50 +05:30
commit 20d7379c53
54 changed files with 1509 additions and 314 deletions

View File

@ -155,11 +155,21 @@ public class QueryStringDecoder {
"maxParams: " + maxParams + " (expected: a positive integer)");
}
String rawPath = uri.getRawPath();
if (rawPath != null) {
hasPath = true;
} else {
rawPath ="";
hasPath = false;
}
// Also take care of cut of things like "http://localhost"
String newUri = rawPath + "?" + uri.getRawQuery();
// http://en.wikipedia.org/wiki/Query_string
this.uri = uri.toASCIIString().replace(';', '&');
this.uri = newUri.replace(';', '&');
this.charset = charset;
this.maxParams = maxParams;
hasPath = false;
}
/**

View File

@ -139,6 +139,14 @@ final class SpdyCodecUtil {
(buf.getByte(offset + 3) & 0xFF));
}
/**
* Returns {@code true} if ID is for a server initiated stream or ping.
*/
static boolean isServerID(int ID) {
// Server initiated streams and pings have even IDs
return ID % 2 == 0;
}
/**
* Validate a SPDY header name.
*/

View File

@ -43,10 +43,27 @@ import io.netty.channel.ChannelUpstreamHandler;
public class SpdyFrameCodec implements ChannelUpstreamHandler,
ChannelDownstreamHandler {
private final SpdyFrameDecoder decoder = new SpdyFrameDecoder();
private final SpdyFrameEncoder encoder = new SpdyFrameEncoder();
private final SpdyFrameDecoder decoder;
private final SpdyFrameEncoder encoder;
/**
* Creates a new instance with the default decoder and encoder options
* ({@code maxChunkSize (8192)}, {@code maxFrameSize (65536)},
* {@code maxHeaderSize (16384)}, {@code compressionLevel (6)},
* {@code windowBits (15)}, and {@code memLevel (8)}).
*/
public SpdyFrameCodec() {
this(8192, 65536, 16384, 6, 15, 8);
}
/**
* Creates a new instance with the specified decoder and encoder options.
*/
public SpdyFrameCodec(
int maxChunkSize, int maxFrameSize, int maxHeaderSize,
int compressionLevel, int windowBits, int memLevel) {
decoder = new SpdyFrameDecoder(maxChunkSize, maxFrameSize, maxHeaderSize);
encoder = new SpdyFrameEncoder(compressionLevel, windowBits, memLevel);
}
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)

View File

@ -44,11 +44,42 @@ import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
*/
public class SpdyFrameDecoder extends FrameDecoder {
private final int maxChunkSize;
private final int maxFrameSize;
private final int maxHeaderSize;
private final DecoderEmbedder<ChannelBuffer> headerBlockDecompressor =
new DecoderEmbedder<ChannelBuffer>(new ZlibDecoder(SPDY_DICT));
/**
* Creates a new instance with the default {@code maxChunkSize (8192)},
* {@code maxFrameSize (65536)}, and {@code maxHeaderSize (16384)}.
*/
public SpdyFrameDecoder() {
super();
this(8192, 65536, 16384);
}
/**
* Creates a new instance with the specified parameters.
*/
public SpdyFrameDecoder(
int maxChunkSize, int maxFrameSize, int maxHeaderSize) {
super(true); // Enable unfold for data frames
if (maxChunkSize <= 0) {
throw new IllegalArgumentException(
"maxChunkSize must be a positive integer: " + maxChunkSize);
}
if (maxFrameSize <= 0) {
throw new IllegalArgumentException(
"maxFrameSize must be a positive integer: " + maxFrameSize);
}
if (maxHeaderSize <= 0) {
throw new IllegalArgumentException(
"maxHeaderSize must be a positive integer: " + maxHeaderSize);
}
this.maxChunkSize = maxChunkSize;
this.maxFrameSize = maxFrameSize;
this.maxHeaderSize = maxHeaderSize;
}
@Override
@ -67,6 +98,12 @@ public class SpdyFrameDecoder extends FrameDecoder {
int dataLength = getUnsignedMedium(buffer, lengthOffset);
int frameLength = SPDY_HEADER_SIZE + dataLength;
// Throw exception if frameLength exceeds maxFrameSize
if (frameLength > maxFrameSize) {
throw new SpdyProtocolException(
"Frame length exceeds " + maxFrameSize + ": " + frameLength);
}
// Wait until entire frame is readable
if (buffer.readableBytes() < frameLength) {
return null;
@ -98,12 +135,25 @@ public class SpdyFrameDecoder extends FrameDecoder {
int streamID = getUnsignedInt(buffer, frameOffset);
buffer.skipBytes(SPDY_HEADER_SIZE);
SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(streamID);
spdyDataFrame.setLast((flags & SPDY_DATA_FLAG_FIN) != 0);
spdyDataFrame.setCompressed((flags & SPDY_DATA_FLAG_COMPRESS) != 0);
spdyDataFrame.setData(buffer.readBytes(dataLength));
// Generate data frames that do not exceed maxChunkSize
int numFrames = dataLength / maxChunkSize;
if (dataLength % maxChunkSize != 0) {
numFrames ++;
}
SpdyDataFrame[] frames = new SpdyDataFrame[numFrames];
for (int i = 0; i < numFrames; i++) {
int chunkSize = Math.min(maxChunkSize, dataLength);
SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(streamID);
spdyDataFrame.setCompressed((flags & SPDY_DATA_FLAG_COMPRESS) != 0);
spdyDataFrame.setData(buffer.readBytes(chunkSize));
dataLength -= chunkSize;
if (dataLength == 0) {
spdyDataFrame.setLast((flags & SPDY_DATA_FLAG_FIN) != 0);
}
frames[i] = spdyDataFrame;
}
return spdyDataFrame;
return frames;
}
}
@ -276,6 +326,7 @@ public class SpdyFrameDecoder extends FrameDecoder {
throw new SpdyProtocolException(
"Received invalid header block");
}
int headerSize = 0;
int numEntries = getUnsignedShort(headerBlock, headerBlock.readerIndex());
headerBlock.skipBytes(2);
for (int i = 0; i < numEntries; i ++) {
@ -289,6 +340,11 @@ public class SpdyFrameDecoder extends FrameDecoder {
headerFrame.setInvalid();
return;
}
headerSize += nameLength;
if (headerSize > maxHeaderSize) {
throw new SpdyProtocolException(
"Header block exceeds " + maxHeaderSize);
}
if (headerBlock.readableBytes() < nameLength) {
throw new SpdyProtocolException(
"Received invalid header block");
@ -310,6 +366,11 @@ public class SpdyFrameDecoder extends FrameDecoder {
headerFrame.setInvalid();
return;
}
headerSize += valueLength;
if (headerSize > maxHeaderSize) {
throw new SpdyProtocolException(
"Header block exceeds " + maxHeaderSize);
}
if (headerBlock.readableBytes() < valueLength) {
throw new SpdyProtocolException(
"Received invalid header block");

View File

@ -48,11 +48,23 @@ import static io.netty.handler.codec.spdy.SpdyCodecUtil.*;
*/
public class SpdyFrameEncoder extends OneToOneEncoder {
private final EncoderEmbedder<ChannelBuffer> headerBlockCompressor =
new EncoderEmbedder<ChannelBuffer>(new ZlibEncoder(9, SPDY_DICT));
private final EncoderEmbedder<ChannelBuffer> headerBlockCompressor;
/**
* Creates a new instance with the default {@code compressionLevel (6)},
* {@code windowBits (15)}, and {@code memLevel (8)}.
*/
public SpdyFrameEncoder() {
this(6, 15, 8);
}
/**
* Creates a new instance with the specified parameters.
*/
public SpdyFrameEncoder(int compressionLevel, int windowBits, int memLevel) {
super();
headerBlockCompressor = new EncoderEmbedder<ChannelBuffer>(
new ZlibEncoder(compressionLevel, windowBits, memLevel, SPDY_DICT));
}
@Override

View File

@ -0,0 +1,64 @@
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.netty.handler.codec.spdy;
import io.netty.channel.ChannelDownstreamHandler;
import io.netty.channel.ChannelEvent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelUpstreamHandler;
/**
* A combination of {@link SpdyHttpDecoder} and {@link SpdyHttpEncoder}
* @apiviz.has io.netty.handler.codec.sdpy.SpdyHttpDecoder
* @apiviz.has io.netty.handler.codec.spdy.SpdyHttpEncoder
*/
public class SpdyHttpCodec implements ChannelUpstreamHandler, ChannelDownstreamHandler {
private final SpdyHttpDecoder decoder;
private final SpdyHttpEncoder encoder = new SpdyHttpEncoder();
/**
* Creates a new instance with the specified decoder options.
*/
public SpdyHttpCodec(int maxContentLength) {
decoder = new SpdyHttpDecoder(maxContentLength);
}
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
throws Exception {
decoder.handleUpstream(ctx, e);
}
public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e)
throws Exception {
encoder.handleDownstream(ctx, e);
}
}

View File

@ -0,0 +1,296 @@
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.netty.handler.codec.spdy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.netty.buffer.ChannelBuffer;
import io.netty.buffer.ChannelBuffers;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.Channels;
import io.netty.handler.codec.frame.TooLongFrameException;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.oneone.OneToOneDecoder;
/**
* Decodes {@link SpdySynStreamFrame}s, {@link SpdySynReplyFrame}s,
* and {@link SpdyDataFrame}s into {@link HttpRequest}s and {@link HttpResponse}s.
*/
public class SpdyHttpDecoder extends OneToOneDecoder {
private final int maxContentLength;
private final Map<Integer, HttpMessage> messageMap = new HashMap<Integer, HttpMessage>();
/**
* Creates a new instance.
*
* @param maxContentLength the maximum length of the message content.
* If the length of the message content exceeds this value,
* a {@link TooLongFrameException} will be raised.
*/
public SpdyHttpDecoder(int maxContentLength) {
super();
if (maxContentLength <= 0) {
throw new IllegalArgumentException(
"maxContentLength must be a positive integer: " + maxContentLength);
}
this.maxContentLength = maxContentLength;
}
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg)
throws Exception {
if (msg instanceof SpdySynStreamFrame) {
// HTTP requests/responses are mapped one-to-one to SPDY streams.
SpdySynStreamFrame spdySynStreamFrame = (SpdySynStreamFrame) msg;
int streamID = spdySynStreamFrame.getStreamID();
if (SpdyCodecUtil.isServerID(streamID)) {
// SYN_STREAM frames inititated by the server are pushed resources
int associatedToStreamID = spdySynStreamFrame.getAssociatedToStreamID();
// If a client receives a SYN_STREAM with an Associated-To-Stream-ID of 0
// it must reply with a RST_STREAM with error code INVALID_STREAM
if (associatedToStreamID == 0) {
SpdyRstStreamFrame spdyRstStreamFrame =
new DefaultSpdyRstStreamFrame(streamID, SpdyStreamStatus.INVALID_STREAM);
Channels.write(ctx, Channels.future(channel), spdyRstStreamFrame);
}
String URL = SpdyHeaders.getUrl(spdySynStreamFrame);
// If a client receives a SYN_STREAM without a 'url' header
// it must reply with a RST_STREAM with error code PROTOCOL_ERROR
if (URL == null) {
SpdyRstStreamFrame spdyRstStreamFrame =
new DefaultSpdyRstStreamFrame(streamID, SpdyStreamStatus.PROTOCOL_ERROR);
Channels.write(ctx, Channels.future(channel), spdyRstStreamFrame);
}
try {
HttpResponse httpResponse = createHttpResponse(spdySynStreamFrame);
// Set the Stream-ID, Associated-To-Stream-ID, Priority, and URL as headers
SpdyHttpHeaders.setStreamID(httpResponse, streamID);
SpdyHttpHeaders.setAssociatedToStreamID(httpResponse, associatedToStreamID);
SpdyHttpHeaders.setPriority(httpResponse, spdySynStreamFrame.getPriority());
SpdyHttpHeaders.setUrl(httpResponse, URL);
if (spdySynStreamFrame.isLast()) {
HttpHeaders.setContentLength(httpResponse, 0);
return httpResponse;
} else {
// Response body will follow in a series of Data Frames
messageMap.put(new Integer(streamID), httpResponse);
}
} catch (Exception e) {
SpdyRstStreamFrame spdyRstStreamFrame =
new DefaultSpdyRstStreamFrame(streamID, SpdyStreamStatus.PROTOCOL_ERROR);
Channels.write(ctx, Channels.future(channel), spdyRstStreamFrame);
}
} else {
// SYN_STREAM frames initiated by the client are HTTP requests
try {
HttpRequest httpRequest = createHttpRequest(spdySynStreamFrame);
// Set the Stream-ID as a header
SpdyHttpHeaders.setStreamID(httpRequest, streamID);
if (spdySynStreamFrame.isLast()) {
return httpRequest;
} else {
// Request body will follow in a series of Data Frames
messageMap.put(new Integer(streamID), httpRequest);
}
} catch (Exception e) {
// If a client sends a SYN_STREAM without method, url, and version headers
// the server must reply with a HTTP 400 BAD REQUEST reply
// Also sends HTTP 400 BAD REQUEST reply if header name/value pairs are invalid
SpdySynReplyFrame spdySynReplyFrame = new DefaultSpdySynReplyFrame(streamID);
spdySynReplyFrame.setLast(true);
SpdyHeaders.setStatus(spdySynReplyFrame, HttpResponseStatus.BAD_REQUEST);
SpdyHeaders.setVersion(spdySynReplyFrame, HttpVersion.HTTP_1_0);
Channels.write(ctx, Channels.future(channel), spdySynReplyFrame);
}
}
} else if (msg instanceof SpdySynReplyFrame) {
SpdySynReplyFrame spdySynReplyFrame = (SpdySynReplyFrame) msg;
int streamID = spdySynReplyFrame.getStreamID();
try {
HttpResponse httpResponse = createHttpResponse(spdySynReplyFrame);
// Set the Stream-ID as a header
SpdyHttpHeaders.setStreamID(httpResponse, streamID);
if (spdySynReplyFrame.isLast()) {
HttpHeaders.setContentLength(httpResponse, 0);
return httpResponse;
} else {
// Response body will follow in a series of Data Frames
messageMap.put(new Integer(streamID), httpResponse);
}
} catch (Exception e) {
// If a client receives a SYN_REPLY without valid status and version headers
// the client must reply with a RST_STREAM frame indicating a PROTOCOL_ERROR
SpdyRstStreamFrame spdyRstStreamFrame =
new DefaultSpdyRstStreamFrame(streamID, SpdyStreamStatus.PROTOCOL_ERROR);
Channels.write(ctx, Channels.future(channel), spdyRstStreamFrame);
}
} else if (msg instanceof SpdyHeadersFrame) {
SpdyHeadersFrame spdyHeadersFrame = (SpdyHeadersFrame) msg;
Integer streamID = new Integer(spdyHeadersFrame.getStreamID());
HttpMessage httpMessage = messageMap.get(streamID);
// If message is not in map discard HEADERS frame.
// SpdySessionHandler should prevent this from happening.
if (httpMessage == null) {
return null;
}
for (Map.Entry<String, String> e: spdyHeadersFrame.getHeaders()) {
httpMessage.addHeader(e.getKey(), e.getValue());
}
} else if (msg instanceof SpdyDataFrame) {
SpdyDataFrame spdyDataFrame = (SpdyDataFrame) msg;
Integer streamID = new Integer(spdyDataFrame.getStreamID());
HttpMessage httpMessage = messageMap.get(streamID);
// If message is not in map discard Data Frame.
// SpdySessionHandler should prevent this from happening.
if (httpMessage == null) {
return null;
}
ChannelBuffer content = httpMessage.getContent();
if (content.readableBytes() > maxContentLength - spdyDataFrame.getData().readableBytes()) {
messageMap.remove(streamID);
throw new TooLongFrameException(
"HTTP content length exceeded " + maxContentLength + " bytes.");
}
if (content == ChannelBuffers.EMPTY_BUFFER) {
content = ChannelBuffers.dynamicBuffer(channel.getConfig().getBufferFactory());
content.writeBytes(spdyDataFrame.getData());
httpMessage.setContent(content);
} else {
content.writeBytes(spdyDataFrame.getData());
}
if (spdyDataFrame.isLast()) {
HttpHeaders.setContentLength(httpMessage, content.readableBytes());
messageMap.remove(streamID);
return httpMessage;
}
}
return null;
}
private HttpRequest createHttpRequest(SpdyHeaderBlock requestFrame)
throws Exception {
// Create the first line of the request from the name/value pairs
HttpMethod method = SpdyHeaders.getMethod(requestFrame);
String url = SpdyHeaders.getUrl(requestFrame);
HttpVersion version = SpdyHeaders.getVersion(requestFrame);
SpdyHeaders.removeMethod(requestFrame);
SpdyHeaders.removeUrl(requestFrame);
SpdyHeaders.removeVersion(requestFrame);
HttpRequest httpRequest = new DefaultHttpRequest(version, method, url);
for (Map.Entry<String, String> e: requestFrame.getHeaders()) {
httpRequest.addHeader(e.getKey(), e.getValue());
}
// Chunked encoding is no longer valid
List<String> encodings = httpRequest.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
encodings.remove(HttpHeaders.Values.CHUNKED);
if (encodings.isEmpty()) {
httpRequest.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
} else {
httpRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, encodings);
}
// The Connection and Keep-Alive headers are no longer valid
HttpHeaders.setKeepAlive(httpRequest, true);
return httpRequest;
}
private HttpResponse createHttpResponse(SpdyHeaderBlock responseFrame)
throws Exception {
// Create the first line of the response from the name/value pairs
HttpResponseStatus status = SpdyHeaders.getStatus(responseFrame);
HttpVersion version = SpdyHeaders.getVersion(responseFrame);
SpdyHeaders.removeStatus(responseFrame);
SpdyHeaders.removeVersion(responseFrame);
HttpResponse httpResponse = new DefaultHttpResponse(version, status);
for (Map.Entry<String, String> e: responseFrame.getHeaders()) {
httpResponse.addHeader(e.getKey(), e.getValue());
}
// Chunked encoding is no longer valid
List<String> encodings = httpResponse.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
encodings.remove(HttpHeaders.Values.CHUNKED);
if (encodings.isEmpty()) {
httpResponse.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
} else {
httpResponse.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, encodings);
}
httpResponse.removeHeader(HttpHeaders.Names.TRAILER);
// The Connection and Keep-Alive headers are no longer valid
HttpHeaders.setKeepAlive(httpResponse, true);
return httpResponse;
}
}

View File

@ -0,0 +1,325 @@
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.netty.handler.codec.spdy;
import java.util.List;
import java.util.Map;
import io.netty.channel.ChannelDownstreamHandler;
import io.netty.channel.ChannelEvent;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.Channels;
import io.netty.channel.MessageEvent;
import io.netty.handler.codec.http.HttpChunk;
import io.netty.handler.codec.http.HttpChunkTrailer;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
/**
* Encodes {@link HttpRequest}s, {@link HttpResponse}s, and {@link HttpChunk}s
* into {@link SpdySynStreamFrame}s and {@link SpdySynReplyFrame}s.
*
* <h3>Request Annotations</h3>
*
* SPDY specific headers must be added to {@link HttpRequest}s:
* <table border=1>
* <tr>
* <th>Header Name</th><th>Header Value</th>
* </tr>
* <tr>
* <td>{@code "X-SPDY-Stream-ID"}</td>
* <td>The Stream-ID for this request.
* Stream-IDs must be odd, positive integers, and must increase monotonically.</td>
* </tr>
* <tr>
* <td>{@code "X-SPDY-Priority"}</td>
* <td>The priority value for this request.
* The priority should be between 0 and 3 inclusive.
* 0 represents the highest priority and 3 represents the lowest.
* This header is optional and defaults to 0.</td>
* </tr>
* </table>
*
* <h3>Response Annotations</h3>
*
* SPDY specific headers must be added to {@link HttpResponse}s:
* <table border=1>
* <tr>
* <th>Header Name</th><th>Header Value</th>
* </tr>
* <tr>
* <td>{@code "X-SPDY-Stream-ID"}</td>
* <td>The Stream-ID of the request corresponding to this response.</td>
* </tr>
* </table>
*
* <h3>Pushed Resource Annotations</h3>
*
* SPDY specific headers must be added to pushed {@link HttpResponse}s:
* <table border=1>
* <tr>
* <th>Header Name</th><th>Header Value</th>
* </tr>
* <tr>
* <td>{@code "X-SPDY-Stream-ID"}</td>
* <td>The Stream-ID for this resource.
* Stream-IDs must be even, positive integers, and must increase monotonically.</td>
* </tr>
* <tr>
* <td>{@code "X-SPDY-Associated-To-Stream-ID"}</td>
* <td>The Stream-ID of the request that inititated this pushed resource.</td>
* </tr>
* <tr>
* <td>{@code "X-SPDY-Priority"}</td>
* <td>The priority value for this resource.
* The priority should be between 0 and 3 inclusive.
* 0 represents the highest priority and 3 represents the lowest.
* This header is optional and defaults to 0.</td>
* </tr>
* <tr>
* <td>{@code "X-SPDY-URL"}</td>
* <td>The full URL for the resource being pushed.</td>
* </tr>
* </table>
*
* <h3>Chunked Content</h3>
*
* This encoder associates all {@link HttpChunk}s that it receives
* with the most recently received 'chunked' {@link HttpRequest}
* or {@link HttpResponse}.
*
* <h3>Pushed Resources</h3>
*
* All pushed resources should be sent before sending the response
* that corresponds to the initial request.
*/
public class SpdyHttpEncoder implements ChannelDownstreamHandler {
private volatile int currentStreamID;
public SpdyHttpEncoder() {
}
public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt)
throws Exception {
if (!(evt instanceof MessageEvent)) {
ctx.sendDownstream(evt);
return;
}
MessageEvent e = (MessageEvent) evt;
Object msg = e.getMessage();
if (msg instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) msg;
SpdySynStreamFrame spdySynStreamFrame = createSynStreamFrame(httpRequest);
int streamID = spdySynStreamFrame.getStreamID();
ChannelFuture future = getContentFuture(ctx, e, streamID, httpRequest);
Channels.write(ctx, future, spdySynStreamFrame, e.getRemoteAddress());
} else if (msg instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse) msg;
if (httpResponse.containsHeader(SpdyHttpHeaders.Names.ASSOCIATED_TO_STREAM_ID)) {
SpdySynStreamFrame spdySynStreamFrame = createSynStreamFrame(httpResponse);
int streamID = spdySynStreamFrame.getStreamID();
ChannelFuture future = getContentFuture(ctx, e, streamID, httpResponse);
Channels.write(ctx, future, spdySynStreamFrame, e.getRemoteAddress());
} else {
SpdySynReplyFrame spdySynReplyFrame = createSynReplyFrame(httpResponse);
int streamID = spdySynReplyFrame.getStreamID();
ChannelFuture future = getContentFuture(ctx, e, streamID, httpResponse);
Channels.write(ctx, future, spdySynReplyFrame, e.getRemoteAddress());
}
} else if (msg instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) msg;
SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(currentStreamID);
spdyDataFrame.setData(chunk.getContent());
spdyDataFrame.setLast(chunk.isLast());
if (chunk instanceof HttpChunkTrailer) {
HttpChunkTrailer trailer = (HttpChunkTrailer) chunk;
List<Map.Entry<String, String>> trailers = trailer.getHeaders();
if (trailers.isEmpty()) {
Channels.write(ctx, e.getFuture(), spdyDataFrame, e.getRemoteAddress());
} else {
// Create SPDY HEADERS frame out of trailers
SpdyHeadersFrame spdyHeadersFrame = new DefaultSpdyHeadersFrame(currentStreamID);
for (Map.Entry<String, String> entry: trailers) {
spdyHeadersFrame.addHeader(entry.getKey(), entry.getValue());
}
// Write HEADERS frame and append Data Frame
ChannelFuture future = Channels.future(e.getChannel());
future.addListener(new SpdyFrameWriter(ctx, e, spdyDataFrame));
Channels.write(ctx, future, spdyHeadersFrame, e.getRemoteAddress());
}
} else {
Channels.write(ctx, e.getFuture(), spdyDataFrame, e.getRemoteAddress());
}
} else {
// Unknown message type
ctx.sendDownstream(evt);
}
}
private ChannelFuture getContentFuture(
ChannelHandlerContext ctx, MessageEvent e, int streamID, HttpMessage httpMessage) {
if (httpMessage.getContent().readableBytes() == 0) {
return e.getFuture();
}
// Create SPDY Data Frame out of message content
SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(streamID);
spdyDataFrame.setData(httpMessage.getContent());
spdyDataFrame.setLast(true);
// Create new future and add listener
ChannelFuture future = Channels.future(e.getChannel());
future.addListener(new SpdyFrameWriter(ctx, e, spdyDataFrame));
return future;
}
private class SpdyFrameWriter implements ChannelFutureListener {
private final ChannelHandlerContext ctx;
private final MessageEvent e;
private final Object spdyFrame;
SpdyFrameWriter(ChannelHandlerContext ctx, MessageEvent e, Object spdyFrame) {
this.ctx = ctx;
this.e = e;
this.spdyFrame = spdyFrame;
}
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
Channels.write(ctx, e.getFuture(), spdyFrame, e.getRemoteAddress());
} else if (future.isCancelled()) {
e.getFuture().cancel();
} else {
e.getFuture().setFailure(future.getCause());
}
}
}
private SpdySynStreamFrame createSynStreamFrame(HttpMessage httpMessage)
throws Exception {
boolean chunked = httpMessage.isChunked();
// Get the Stream-ID, Associated-To-Stream-ID, Priority, and URL from the headers
int streamID = SpdyHttpHeaders.getStreamID(httpMessage);
int associatedToStreamID = SpdyHttpHeaders.getAssociatedToStreamID(httpMessage);
byte priority = SpdyHttpHeaders.getPriority(httpMessage);
String URL = SpdyHttpHeaders.getUrl(httpMessage);
SpdyHttpHeaders.removeStreamID(httpMessage);
SpdyHttpHeaders.removeAssociatedToStreamID(httpMessage);
SpdyHttpHeaders.removePriority(httpMessage);
SpdyHttpHeaders.removeUrl(httpMessage);
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent.
httpMessage.removeHeader(HttpHeaders.Names.CONNECTION);
httpMessage.removeHeader("Keep-Alive");
httpMessage.removeHeader("Proxy-Connection");
httpMessage.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
SpdySynStreamFrame spdySynStreamFrame = new DefaultSpdySynStreamFrame(streamID, associatedToStreamID, priority);
for (Map.Entry<String, String> entry: httpMessage.getHeaders()) {
spdySynStreamFrame.addHeader(entry.getKey(), entry.getValue());
}
// Unfold the first line of the message into name/value pairs
SpdyHeaders.setVersion(spdySynStreamFrame, httpMessage.getProtocolVersion());
if (httpMessage instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) httpMessage;
SpdyHeaders.setMethod(spdySynStreamFrame, httpRequest.getMethod());
SpdyHeaders.setUrl(spdySynStreamFrame, httpRequest.getUri());
}
if (httpMessage instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse) httpMessage;
SpdyHeaders.setStatus(spdySynStreamFrame, httpResponse.getStatus());
SpdyHeaders.setUrl(spdySynStreamFrame, URL);
spdySynStreamFrame.setUnidirectional(true);
}
if (chunked) {
currentStreamID = streamID;
spdySynStreamFrame.setLast(false);
} else {
spdySynStreamFrame.setLast(httpMessage.getContent().readableBytes() == 0);
}
return spdySynStreamFrame;
}
private SpdySynReplyFrame createSynReplyFrame(HttpResponse httpResponse)
throws Exception {
boolean chunked = httpResponse.isChunked();
// Get the Stream-ID from the headers
int streamID = SpdyHttpHeaders.getStreamID(httpResponse);
SpdyHttpHeaders.removeStreamID(httpResponse);
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-ENcoding
// headers are not valid and MUST not be sent.
httpResponse.removeHeader(HttpHeaders.Names.CONNECTION);
httpResponse.removeHeader("Keep-Alive");
httpResponse.removeHeader("Proxy-Connection");
httpResponse.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
SpdySynReplyFrame spdySynReplyFrame = new DefaultSpdySynReplyFrame(streamID);
for (Map.Entry<String, String> entry: httpResponse.getHeaders()) {
spdySynReplyFrame.addHeader(entry.getKey(), entry.getValue());
}
// Unfold the first line of the repsonse into name/value pairs
SpdyHeaders.setStatus(spdySynReplyFrame, httpResponse.getStatus());
SpdyHeaders.setVersion(spdySynReplyFrame, httpResponse.getProtocolVersion());
if (chunked) {
currentStreamID = streamID;
spdySynReplyFrame.setLast(false);
} else {
spdySynReplyFrame.setLast(httpResponse.getContent().readableBytes() == 0);
}
return spdySynReplyFrame;
}
}

View File

@ -0,0 +1,162 @@
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.netty.handler.codec.spdy;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
/**
* Provides the constants for the header names and the utility methods
* used by the {@link SpdyHttpDecoder} and {@link SpdyHttpEncoder}.
* @apiviz.sterotype static
*/
public final class SpdyHttpHeaders {
/**
* SPDY HTTP header names
* @apiviz.sterotype static
*/
public static final class Names {
/**
* {@code "X-SPDY-Stream-ID"}
*/
public static final String STREAM_ID = "X-SPDY-Stream-ID";
/**
* {@code "X-SPDY-Associated-To-Stream-ID"}
*/
public static final String ASSOCIATED_TO_STREAM_ID = "X-SPDY-Associated-To-Stream-ID";
/**
* {@code "X-SPDY-Priority"}
*/
public static final String PRIORITY = "X-SPDY-Priority";
/**
* {@code "X-SPDY-URL"}
*/
public static final String URL = "X-SPDY-URL";
private Names() {
super();
}
}
private SpdyHttpHeaders() {
}
/**
* Removes the {@code "X-SPDY-Stream-ID"} header.
*/
public static void removeStreamID(HttpMessage message) {
message.removeHeader(Names.STREAM_ID);
}
/**
* Returns the value of the {@code "X-SPDY-Stream-ID"} header.
*/
public static int getStreamID(HttpMessage message) {
return HttpHeaders.getIntHeader(message, Names.STREAM_ID);
}
/**
* Sets the {@code "X-SPDY-Stream-ID"} header.
*/
public static void setStreamID(HttpMessage message, int streamID) {
HttpHeaders.setIntHeader(message, Names.STREAM_ID, streamID);
}
/**
* Removes the {@code "X-SPDY-Associated-To-Stream-ID"} header.
*/
public static void removeAssociatedToStreamID(HttpMessage message) {
message.removeHeader(Names.ASSOCIATED_TO_STREAM_ID);
}
/**
* Returns the value of the {@code "X-SPDY-Associated-To-Stream-ID"} header.
*
* @return the header value or {@code 0} if there is no such header or
* if the header value is not a number
*/
public static int getAssociatedToStreamID(HttpMessage message) {
return HttpHeaders.getIntHeader(message, Names.ASSOCIATED_TO_STREAM_ID, 0);
}
/**
* Sets the {@code "X-SPDY-Associated-To-Stream-ID"} header.
*/
public static void setAssociatedToStreamID(HttpMessage message, int associatedToStreamID) {
HttpHeaders.setIntHeader(message, Names.ASSOCIATED_TO_STREAM_ID, associatedToStreamID);
}
/**
* Removes the {@code "X-SPDY-Priority"} header.
*/
public static void removePriority(HttpMessage message) {
message.removeHeader(Names.PRIORITY);
}
/**
* Returns the value of the {@code "X-SPDY-Priority"} header.
*
* @return the header value or {@code 0} if there is no such header or
* if the header value is not a number
*/
public static byte getPriority(HttpMessage message) {
return (byte) HttpHeaders.getIntHeader(message, Names.PRIORITY, 0);
}
/**
* Sets the {@code "X-SPDY-Priority"} header.
*/
public static void setPriority(HttpMessage message, byte priority) {
HttpHeaders.setIntHeader(message, Names.PRIORITY, priority);
}
/**
* Removes the {@code "X-SPDY-URL"} header.
*/
public static void removeUrl(HttpMessage message) {
message.removeHeader(Names.URL);
}
/**
* Returns the value of the {@code "X-SPDY-URL"} header.
*/
public static String getUrl(HttpMessage message) {
return message.getHeader(Names.URL);
}
/**
* Sets the {@code "X-SPDY-URL"} header.
*/
public static void setUrl(HttpMessage message, String url) {
message.setHeader(Names.URL, url);
}
}

View File

@ -393,12 +393,8 @@ public class SpdySessionHandler extends SimpleChannelUpstreamHandler
* Helper functions
*/
private boolean isServerID(int ID) {
return ID % 2 == 0;
}
private boolean isRemoteInitiatedID(int ID) {
boolean serverID = isServerID(ID);
boolean serverID = SpdyCodecUtil.isServerID(ID);
return (server && !serverID) || (!server && serverID);
}

View File

@ -15,8 +15,11 @@
*/
package io.netty.handler.codec.http;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import io.netty.util.CharsetUtil;
import org.junit.Assert;
@ -165,4 +168,91 @@ public class QueryStringDecoderTest {
Assert.assertEquals(ed.getPath(), ad.getPath());
Assert.assertEquals(ed.getParameters(), ad.getParameters());
}
// See #189
@Test
public void testURI() {
URI uri = URI.create("http://localhost:8080/foo?param1=value1&param2=value2&param3=value3");
QueryStringDecoder decoder = new QueryStringDecoder(uri);
Assert.assertEquals("/foo", decoder.getPath());
Map<String, List<String>> params = decoder.getParameters();
Assert.assertEquals(3, params.size());
Iterator<Entry<String, List<String>>> entries = params.entrySet().iterator();
Entry<String, List<String>> entry = entries.next();
Assert.assertEquals("param1", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value1", entry.getValue().get(0));
entry = entries.next();
Assert.assertEquals("param2", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value2", entry.getValue().get(0));
entry = entries.next();
Assert.assertEquals("param3", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value3", entry.getValue().get(0));
Assert.assertFalse(entries.hasNext());
}
// See #189
@Test
public void testURISlashPath() {
URI uri = URI.create("http://localhost:8080/?param1=value1&param2=value2&param3=value3");
QueryStringDecoder decoder = new QueryStringDecoder(uri);
Assert.assertEquals("/", decoder.getPath());
Map<String, List<String>> params = decoder.getParameters();
Assert.assertEquals(3, params.size());
Iterator<Entry<String, List<String>>> entries = params.entrySet().iterator();
Entry<String, List<String>> entry = entries.next();
Assert.assertEquals("param1", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value1", entry.getValue().get(0));
entry = entries.next();
Assert.assertEquals("param2", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value2", entry.getValue().get(0));
entry = entries.next();
Assert.assertEquals("param3", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value3", entry.getValue().get(0));
Assert.assertFalse(entries.hasNext());
}
// See #189
@Test
public void testURINoPath() {
URI uri = URI.create("http://localhost:8080?param1=value1&param2=value2&param3=value3");
QueryStringDecoder decoder = new QueryStringDecoder(uri);
Assert.assertEquals("", decoder.getPath());
Map<String, List<String>> params = decoder.getParameters();
Assert.assertEquals(3, params.size());
Iterator<Entry<String, List<String>>> entries = params.entrySet().iterator();
Entry<String, List<String>> entry = entries.next();
Assert.assertEquals("param1", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value1", entry.getValue().get(0));
entry = entries.next();
Assert.assertEquals("param2", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value2", entry.getValue().get(0));
entry = entries.next();
Assert.assertEquals("param3", entry.getKey());
Assert.assertEquals(1, entry.getValue().size());
Assert.assertEquals("value3", entry.getValue().get(0));
Assert.assertFalse(entries.hasNext());
}
}

View File

@ -518,9 +518,12 @@ public class HashedWheelTimer implements Timer {
try {
task.run(this);
} catch (Throwable t) {
logger.warn(
"An exception was thrown by " +
TimerTask.class.getSimpleName() + ".", t);
if (logger.isWarnEnabled()) {
logger.warn(
"An exception was thrown by " +
TimerTask.class.getSimpleName() + ".", t);
}
}
}

View File

@ -43,12 +43,14 @@ public class SharedResourceMisuseDetector {
public void increase() {
if (activeInstances.incrementAndGet() > MAX_ACTIVE_INSTANCES) {
if (logged.compareAndSet(false, true)) {
logger.warn(
"You are creating too many " + type.getSimpleName() +
" instances. " + type.getSimpleName() +
" is a shared resource that must be reused across the" +
" application, so that only a few instances are created.");
if (logger.isWarnEnabled()) {
if (logged.compareAndSet(false, true)) {
logger.warn(
"You are creating too many " + type.getSimpleName() +
" instances. " + type.getSimpleName() +
" is a shared resource that must be reused across the" +
" application, so that only a few instances are created.");
}
}
}
}

View File

@ -83,7 +83,7 @@ public class HttpSnoopClient {
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
request.setHeader(HttpHeaders.Names.HOST, host);
request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

View File

@ -81,8 +81,11 @@ public class AutobahnServerHandler extends SimpleChannelUpstreamHandler {
}
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
logger.debug(String
.format("Channel %s received %s", ctx.getChannel().getId(), frame.getClass().getSimpleName()));
if (logger.isDebugEnabled()) {
logger.debug(String
.format("Channel %s received %s", ctx.getChannel().getId(), frame.getClass().getSimpleName()));
}
if (frame instanceof CloseWebSocketFrame) {
this.handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame);

View File

@ -116,7 +116,9 @@ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler {
// Send the uppercase string back.
String request = ((TextWebSocketFrame) frame).getText();
logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request));
if (logger.isDebugEnabled()) {
logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request));
}
ctx.getChannel().write(new TextWebSocketFrame(request.toUpperCase()));
}

View File

@ -116,7 +116,9 @@ public class WebSocketSslServerHandler extends SimpleChannelUpstreamHandler {
// Send the uppercase string back.
String request = ((TextWebSocketFrame) frame).getText();
logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request));
if (logger.isDebugEnabled()) {
logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request));
}
ctx.getChannel().write(new TextWebSocketFrame(request.toUpperCase()));
}

View File

@ -86,7 +86,9 @@ public final class WebSocketSslServerSslContext {
}
_serverContext = serverContext;
} catch (Exception ex) {
logger.error("Error initializing SslContextManager. " + ex.getMessage(), ex);
if (logger.isErrorEnabled()) {
logger.error("Error initializing SslContextManager. " + ex.getMessage(), ex);
}
System.exit(1);
}

View File

@ -58,7 +58,9 @@ public class CIDR6 extends CIDR {
try {
return bigIntToIPv6Address(addressEndBigInt);
} catch (UnknownHostException e) {
logger.error("invalid ip address calculated as an end address");
if (logger.isErrorEnabled()) {
logger.error("invalid ip address calculated as an end address");
}
return null;
}
}

View File

@ -69,7 +69,9 @@ public class IpFilterRuleList extends ArrayList<IpFilterRule> {
return;
}
if (!(rule.startsWith("+") || rule.startsWith("-"))) {
logger.error("syntax error in ip filter rule:" + rule);
if (logger.isErrorEnabled()) {
logger.error("syntax error in ip filter rule:" + rule);
}
return;
}
@ -80,10 +82,14 @@ public class IpFilterRuleList extends ArrayList<IpFilterRule> {
try {
this.add(new IpSubnetFilterRule(allow, rule.substring(3)));
} catch (UnknownHostException e) {
logger.error("error parsing ip filter " + rule, e);
if (logger.isErrorEnabled()) {
logger.error("error parsing ip filter " + rule, e);
}
}
} else {
logger.error("syntax error in ip filter rule:" + rule);
if (logger.isErrorEnabled()) {
logger.error("syntax error in ip filter rule:" + rule);
}
}
}
}

View File

@ -158,7 +158,9 @@ public class PatternRule implements IpFilterRule, Comparable<Object> {
return true;
}
} catch (UnknownHostException e) {
logger.info("error getting ip of localhost", e);
if (logger.isInfoEnabled()) {
logger.info("error getting ip of localhost", e);
}
}
try {
InetAddress[] addrs = InetAddress.getAllByName("127.0.0.1");
@ -168,7 +170,9 @@ public class PatternRule implements IpFilterRule, Comparable<Object> {
}
}
} catch (UnknownHostException e) {
logger.info("error getting ip of localhost", e);
if (logger.isInfoEnabled()) {
logger.info("error getting ip of localhost", e);
}
}
return false;

View File

@ -497,7 +497,9 @@ public class SslHandler extends FrameDecoder
try {
engine.closeInbound();
} catch (SSLException ex) {
logger.debug("Failed to clean up SSLEngine.", ex);
if (logger.isDebugEnabled()) {
logger.debug("Failed to clean up SSLEngine.", ex);
}
}
}
}
@ -513,9 +515,12 @@ public class SslHandler extends FrameDecoder
synchronized (ignoreClosedChannelExceptionLock) {
if (ignoreClosedChannelException > 0) {
ignoreClosedChannelException --;
logger.debug(
"Swallowing an exception raised while " +
"writing non-app data", cause);
if (logger.isDebugEnabled()) {
logger.debug(
"Swallowing an exception raised while " +
"writing non-app data", cause);
}
return;
}
}
@ -524,10 +529,12 @@ public class SslHandler extends FrameDecoder
if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
// It is safe to ignore the 'connection reset by peer' or
// 'broken pipe' error after sending closure_notify.
logger.debug(
"Swallowing a 'connection reset by peer / " +
"broken pipe' error occurred while writing " +
"'closure_notify'", cause);
if (logger.isDebugEnabled()) {
logger.debug(
"Swallowing a 'connection reset by peer / " +
"broken pipe' error occurred while writing " +
"'closure_notify'", cause);
}
// Close the connection explicitly just in case the transport
// did not close the connection automatically.
@ -1085,9 +1092,12 @@ public class SslHandler extends FrameDecoder
try {
engine.closeInbound();
} catch (SSLException e) {
logger.debug(
"SSLEngine.closeInbound() raised an exception after " +
"a handshake failure.", e);
if (logger.isDebugEnabled()) {
logger.debug(
"SSLEngine.closeInbound() raised an exception after " +
"a handshake failure.", e);
}
}
}
@ -1106,7 +1116,9 @@ public class SslHandler extends FrameDecoder
try {
unwrap(context, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
} catch (SSLException ex) {
logger.debug("Failed to unwrap before sending a close_notify message", ex);
if (logger.isDebugEnabled()) {
logger.debug("Failed to unwrap before sending a close_notify message", ex);
}
}
if (!engine.isInboundDone()) {
@ -1118,7 +1130,9 @@ public class SslHandler extends FrameDecoder
new ClosingChannelFutureListener(context, e));
success = true;
} catch (SSLException ex) {
logger.debug("Failed to encode a close_notify message", ex);
if (logger.isDebugEnabled()) {
logger.debug("Failed to encode a close_notify message", ex);
}
}
}
} else {

View File

@ -92,7 +92,9 @@ public class ChunkedWriteHandler implements ChannelUpstreamHandler, ChannelDowns
try {
flush(ctx);
} catch (Exception e) {
logger.warn("Unexpected exception while sending chunks.", e);
if (logger.isWarnEnabled()) {
logger.warn("Unexpected exception while sending chunks.", e);
}
}
}
@ -270,7 +272,9 @@ public class ChunkedWriteHandler implements ChannelUpstreamHandler, ChannelDowns
try {
chunks.close();
} catch (Throwable t) {
logger.warn("Failed to close a chunked input.", t);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a chunked input.", t);
}
}
}
}

View File

@ -129,7 +129,9 @@ public abstract class AbstractSocketSslEchoTest {
ChannelFuture ccf = cb.connect(new InetSocketAddress(SocketAddresses.LOCALHOST, port));
ccf.awaitUninterruptibly();
if (!ccf.isSuccess()) {
logger.error("Connection attempt failed", ccf.getCause());
if(logger.isErrorEnabled()) {
logger.error("Connection attempt failed", ccf.getCause());
}
sc.close().awaitUninterruptibly();
}
assertTrue(ccf.isSuccess());
@ -238,9 +240,11 @@ public abstract class AbstractSocketSslEchoTest {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
logger.warn(
"Unexpected exception from the " +
(server? "server" : "client") + " side", e.getCause());
if (logger.isWarnEnabled()) {
logger.warn(
"Unexpected exception from the " +
(server? "server" : "client") + " side", e.getCause());
}
exception.compareAndSet(null, e.getCause());
e.getChannel().close();

View File

@ -53,11 +53,13 @@ class DefaultNioSctpChannelConfig extends DefaultSctpChannelConfig implements Ni
if (getWriteBufferHighWaterMark() < getWriteBufferLowWaterMark()) {
// Recover the integrity of the configuration with a sensible value.
setWriteBufferLowWaterMark0(getWriteBufferHighWaterMark() >>> 1);
// Notify the user about misconfiguration.
logger.warn(
"writeBufferLowWaterMark cannot be greater than " +
"writeBufferHighWaterMark; setting to the half of the " +
"writeBufferHighWaterMark.");
if (logger.isWarnEnabled()) {
// Notify the user about misconfiguration.
logger.warn(
"writeBufferLowWaterMark cannot be greater than " +
"writeBufferHighWaterMark; setting to the half of the " +
"writeBufferHighWaterMark.");
}
}
}

View File

@ -55,9 +55,11 @@ final class SctpClientChannel extends SctpChannelImpl {
try {
underlayingChannel.close();
} catch (IOException e) {
logger.warn(
"Failed to close a partially initialized sctp channel.",
e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.",
e);
}
}
}
}

View File

@ -324,8 +324,10 @@ class SctpClientPipelineSink extends AbstractChannelSink {
try {
selector.close();
} catch (IOException e) {
logger.warn(
"Failed to close a selector.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a selector.", e);
}
} finally {
this.selector = null;
}
@ -342,8 +344,10 @@ class SctpClientPipelineSink extends AbstractChannelSink {
shutdown = false;
}
} catch (Throwable t) {
logger.warn(
"Unexpected exception in the selector loop.", t);
if (logger.isWarnEnabled()) {
logger.warn(
"Unexpected exception in the selector loop.", t);
}
// Prevent possible consecutive immediate failures.
try {

View File

@ -25,17 +25,12 @@ import com.sun.nio.sctp.ShutdownNotification;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.Channels;
import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
/**
*/
class SctpNotificationHandler extends AbstractNotificationHandler {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(SctpNotificationHandler.class);
private final SctpChannelImpl sctpChannel;
private final ChannelPipeline pipeline;

View File

@ -61,8 +61,10 @@ final class SctpProviderMetadata {
}
if (constraintLevel >= 0) {
logger.debug(
"Setting the NIO constraint level to: " + constraintLevel);
if (logger.isDebugEnabled()) {
logger.debug(
"Setting the NIO constraint level to: " + constraintLevel);
}
}
if (constraintLevel < 0) {
@ -70,18 +72,24 @@ final class SctpProviderMetadata {
if (constraintLevel < 0) {
constraintLevel = 2;
logger.debug(
"Couldn't determine the NIO constraint level from " +
"the system properties; using the safest level (2)");
if (logger.isDebugEnabled()) {
logger.debug(
"Couldn't determine the NIO constraint level from " +
"the system properties; using the safest level (2)");
}
} else if (constraintLevel != 0) {
logger.info(
"Using the autodetected NIO constraint level: " +
constraintLevel +
" (Use better NIO provider for better performance)");
if (logger.isInfoEnabled()) {
logger.info(
"Using the autodetected NIO constraint level: " +
constraintLevel +
" (Use better NIO provider for better performance)");
}
} else {
logger.debug(
"Using the autodetected NIO constraint level: " +
constraintLevel);
if (logger.isDebugEnabled()) {
logger.debug(
"Using the autodetected NIO constraint level: " +
constraintLevel);
}
}
}
@ -236,7 +244,9 @@ final class SctpProviderMetadata {
ch.bind(new InetSocketAddress(0));
ch.configureBlocking(false);
} catch (Throwable e) {
logger.warn("Failed to configure a temporary socket.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to configure a temporary socket.", e);
}
return -1;
}
@ -244,7 +254,9 @@ final class SctpProviderMetadata {
try {
loop = new SelectorLoop();
} catch (Throwable e) {
logger.warn("Failed to open a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to open a temporary selector.", e);
}
return -1;
}
@ -252,7 +264,9 @@ final class SctpProviderMetadata {
try {
ch.register(loop.selector, 0);
} catch (Throwable e) {
logger.warn("Failed to register a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to register a temporary selector.", e);
}
return -1;
}
@ -338,7 +352,9 @@ final class SctpProviderMetadata {
try {
ch.close();
} catch (Throwable e) {
logger.warn("Failed to close a temporary socket.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a temporary socket.", e);
}
}
}
@ -368,7 +384,9 @@ final class SctpProviderMetadata {
try {
loop.selector.close();
} catch (Throwable e) {
logger.warn("Failed to close a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a temporary selector.", e);
}
}
}
}
@ -406,7 +424,9 @@ final class SctpProviderMetadata {
}
keys.clear();
} catch (IOException e) {
logger.warn("Failed to wait for a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to wait for a temporary selector.", e);
}
}
}
}

View File

@ -73,8 +73,10 @@ class SctpServerChannelImpl extends AbstractServerChannel
try {
serverChannel.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially initialized sctp channel.", e2);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
}
throw new ChannelException("Failed to enter non-blocking mode.", e);

View File

@ -281,8 +281,10 @@ class SctpServerPipelineSink extends AbstractChannelSink {
// Closed as requested.
break;
} catch (Throwable e) {
logger.warn(
"Failed to accept a connection.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to accept a connection.", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
@ -306,14 +308,18 @@ class SctpServerPipelineSink extends AbstractChannelSink {
SctpServerPipelineSink.this, acceptedSocket,
worker, currentThread), null);
} catch (Exception e) {
logger.warn(
"Failed to initialize an accepted socket.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to initialize an accepted socket.", e);
}
try {
acceptedSocket.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
}
}
}
}
@ -323,7 +329,9 @@ class SctpServerPipelineSink extends AbstractChannelSink {
try {
selector.close();
} catch (Exception e) {
logger.warn("Failed to close a selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a selector.", e);
}
}
}
}

View File

@ -110,7 +110,9 @@ class SctpWorker implements Runnable {
try {
selector.close();
} catch (Throwable t) {
logger.warn("Failed to close a selector.", t);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a selector.", t);
}
}
this.selector = selector = null;
// The method will return to the caller at this point.
@ -204,8 +206,10 @@ class SctpWorker implements Runnable {
try {
selector.close();
} catch (IOException e) {
logger.warn(
"Failed to close a selector.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a selector.", e);
}
} finally {
this.selector = null;
}
@ -222,9 +226,10 @@ class SctpWorker implements Runnable {
shutdown = false;
}
} catch (Throwable t) {
logger.warn(
"Unexpected exception in the selector loop.", t);
if (logger.isWarnEnabled()) {
logger.warn(
"Unexpected exception in the selector loop.", t);
}
// Prevent possible consecutive immediate failures that lead to
// excessive CPU consumption.
try {
@ -313,7 +318,9 @@ class SctpWorker implements Runnable {
if (!messageInfo.isUnordered()) {
failure = false;
} else {
logger.error("Received unordered SCTP Packet");
if (logger.isErrorEnabled()) {
logger.error("Received unordered SCTP Packet");
}
failure = true;
}
} else {

View File

@ -32,10 +32,13 @@ final class SelectorUtil {
try {
selector.select(10); // does small timeout give more throughput + less CPU usage?
} catch (CancelledKeyException e) {
// Harmless exception - log anyway
logger.debug(
CancelledKeyException.class.getSimpleName() +
" raised by a Selector - JDK bug?", e);
if (logger.isDebugEnabled()) {
// Harmless exception - log anyway
logger.debug(
CancelledKeyException.class.getSimpleName() +
" raised by a Selector - JDK bug?", e);
}
}
}

View File

@ -48,9 +48,11 @@ public abstract class CompleteChannelFuture implements ChannelFuture {
try {
listener.operationComplete(this);
} catch (Throwable t) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
if (logger.isWarnEnabled()) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
}
}
}

View File

@ -56,10 +56,12 @@ public class DefaultChannelFuture implements ChannelFuture {
public static void setUseDeadLockChecker(boolean useDeadLockChecker) {
if (!useDeadLockChecker && !disabledDeadLockCheckerOnce) {
disabledDeadLockCheckerOnce = true;
logger.debug(
"The dead lock checker in " +
DefaultChannelFuture.class.getSimpleName() +
" has been disabled as requested at your own risk.");
if (logger.isDebugEnabled()) {
logger.debug(
"The dead lock checker in " +
DefaultChannelFuture.class.getSimpleName() +
" has been disabled as requested at your own risk.");
}
}
DefaultChannelFuture.useDeadLockChecker = useDeadLockChecker;
}
@ -413,9 +415,11 @@ public class DefaultChannelFuture implements ChannelFuture {
try {
l.operationComplete(this);
} catch (Throwable t) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
if (logger.isWarnEnabled()) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
}
}
}
@ -453,9 +457,11 @@ public class DefaultChannelFuture implements ChannelFuture {
try {
l.operationProgressed(this, amount, current, total);
} catch (Throwable t) {
logger.warn(
"An exception was thrown by " +
ChannelFutureProgressListener.class.getSimpleName() + ".", t);
if (logger.isWarnEnabled()) {
logger.warn(
"An exception was thrown by " +
ChannelFutureProgressListener.class.getSimpleName() + ".", t);
}
}
}
}

View File

@ -357,7 +357,9 @@ public class DefaultChannelPipeline implements ChannelPipeline {
remove((DefaultChannelHandlerContext) ctx);
removed = true;
} catch (Throwable t2) {
logger.warn("Failed to remove a handler: " + ctx.getName(), t2);
if (logger.isWarnEnabled()) {
logger.warn("Failed to remove a handler: " + ctx.getName(), t2);
}
}
if (removed) {
@ -564,8 +566,9 @@ public class DefaultChannelPipeline implements ChannelPipeline {
public void sendUpstream(ChannelEvent e) {
DefaultChannelHandlerContext head = getActualUpstreamContext(this.head);
if (head == null) {
logger.warn(
"The pipeline contains no upstream handlers; discarding: " + e);
if (logger.isWarnEnabled()) {
logger.warn("The pipeline contains no upstream handlers; discarding: " + e);
}
return;
}
@ -648,9 +651,11 @@ public class DefaultChannelPipeline implements ChannelPipeline {
protected void notifyHandlerException(ChannelEvent e, Throwable t) {
if (e instanceof ExceptionEvent) {
logger.warn(
"An exception was thrown by a user handler " +
"while handling an exception event (" + e + ")", t);
if (logger.isWarnEnabled()) {
logger.warn(
"An exception was thrown by a user handler " +
"while handling an exception event (" + e + ")", t);
}
return;
}
@ -664,7 +669,9 @@ public class DefaultChannelPipeline implements ChannelPipeline {
try {
sink.exceptionCaught(this, e, pe);
} catch (Exception e1) {
logger.warn("An exception was thrown by an exception handler.", e1);
if (logger.isWarnEnabled()) {
logger.warn("An exception was thrown by an exception handler.", e1);
}
}
}
@ -815,7 +822,9 @@ public class DefaultChannelPipeline implements ChannelPipeline {
@Override
public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) {
logger.warn("Not attached yet; discarding: " + e);
if (logger.isWarnEnabled()) {
logger.warn("Not attached yet; discarding: " + e);
}
}
@Override

View File

@ -81,7 +81,9 @@ public class DefaultFileRegion implements FileRegion {
try {
file.close();
} catch (IOException e) {
logger.warn("Failed to close a file.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a file.", e);
}
}
}
}

View File

@ -382,9 +382,11 @@ public class DefaultChannelGroupFuture implements ChannelGroupFuture {
try {
l.operationComplete(this);
} catch (Throwable t) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
if (logger.isWarnEnabled()) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
}
}
}
}

View File

@ -116,8 +116,10 @@ final class LocalClientChannelSink extends AbstractChannelSink {
} catch (Exception e) {
future.setFailure(e);
fireExceptionCaught(channel, e);
logger.warn(
"Failed to initialize an accepted socket.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to initialize an accepted socket.", e);
}
return;
}

View File

@ -47,10 +47,13 @@ class DefaultNioDatagramChannelConfig extends DefaultDatagramChannelConfig
if (getWriteBufferHighWaterMark() < getWriteBufferLowWaterMark()) {
// Recover the integrity of the configuration with a sensible value.
setWriteBufferLowWaterMark0(getWriteBufferHighWaterMark() >>> 1);
// Notify the user about misconfiguration.
logger.warn("writeBufferLowWaterMark cannot be greater than "
+ "writeBufferHighWaterMark; setting to the half of the "
+ "writeBufferHighWaterMark.");
if (logger.isWarnEnabled()) {
// Notify the user about misconfiguration.
logger.warn("writeBufferLowWaterMark cannot be greater than "
+ "writeBufferHighWaterMark; setting to the half of the "
+ "writeBufferHighWaterMark.");
}
}
}

View File

@ -55,11 +55,14 @@ class DefaultNioSocketChannelConfig extends DefaultSocketChannelConfig
if (getWriteBufferHighWaterMark() < getWriteBufferLowWaterMark()) {
// Recover the integrity of the configuration with a sensible value.
setWriteBufferLowWaterMark0(getWriteBufferHighWaterMark() >>> 1);
// Notify the user about misconfiguration.
logger.warn(
"writeBufferLowWaterMark cannot be greater than " +
"writeBufferHighWaterMark; setting to the half of the " +
"writeBufferHighWaterMark.");
if (logger.isWarnEnabled()) {
// Notify the user about misconfiguration.
logger.warn(
"writeBufferLowWaterMark cannot be greater than " +
"writeBufferHighWaterMark; setting to the half of the " +
"writeBufferHighWaterMark.");
}
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.socket.nio;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
/**
* Special {@link ChannelConfig} sub-type which offers extra methods which are useful for NIO.
*
*/
public interface NioChannelConfig extends ChannelConfig{
/**
* Returns the high water mark of the write buffer. If the number of bytes
* queued in the write buffer exceeds this value, {@link Channel#isWritable()}
* will start to return {@code true}.
*/
int getWriteBufferHighWaterMark();
/**
* Sets the high water mark of the write buffer. If the number of bytes
* queued in the write buffer exceeds this value, {@link Channel#isWritable()}
* will start to return {@code true}.
*/
void setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
/**
* Returns the low water mark of the write buffer. Once the number of bytes
* queued in the write buffer exceeded the
* {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
* dropped down below this value, {@link Channel#isWritable()} will return
* {@code false} again.
*/
int getWriteBufferLowWaterMark();
/**
* Sets the low water mark of the write buffer. Once the number of bytes
* queued in the write buffer exceeded the
* {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
* dropped down below this value, {@link Channel#isWritable()} will return
* {@code false} again.
*/
void setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
/**
* Returns the maximum loop count for a write operation until
* {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
* It is similar to what a spin lock is used for in concurrency programming.
* It improves memory utilization and write throughput depending on
* the platform that JVM runs on. The default value is {@code 16}.
*/
int getWriteSpinCount();
/**
* Sets the maximum loop count for a write operation until
* {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
* It is similar to what a spin lock is used for in concurrency programming.
* It improves memory utilization and write throughput depending on
* the platform that JVM runs on. The default value is {@code 16}.
*
* @throws IllegalArgumentException
* if the specified value is {@code 0} or less than {@code 0}
*/
void setWriteSpinCount(int writeSpinCount);
}

View File

@ -52,9 +52,12 @@ final class NioClientSocketChannel extends NioSocketChannel {
try {
socket.close();
} catch (IOException e) {
logger.warn(
"Failed to close a partially initialized socket.",
e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.",
e);
}
}
}
}

View File

@ -208,7 +208,9 @@ class NioClientSocketPipelineSink extends AbstractChannelSink {
try {
selector.close();
} catch (Throwable t) {
logger.warn("Failed to close a selector.", t);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a selector.", t);
}
}
this.selector = selector = null;
// The method will return to the caller at this point.
@ -302,8 +304,11 @@ class NioClientSocketPipelineSink extends AbstractChannelSink {
try {
selector.close();
} catch (IOException e) {
logger.warn(
"Failed to close a selector.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a selector.", e);
}
} finally {
this.selector = null;
}
@ -320,8 +325,11 @@ class NioClientSocketPipelineSink extends AbstractChannelSink {
shutdown = false;
}
} catch (Throwable t) {
logger.warn(
"Unexpected exception in the selector loop.", t);
if (logger.isWarnEnabled()) {
logger.warn(
"Unexpected exception in the selector loop.", t);
}
// Prevent possible consecutive immediate failures.
try {

View File

@ -15,10 +15,6 @@
*/
package io.netty.channel.socket.nio;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramChannelConfig;
@ -44,58 +40,7 @@ import io.netty.channel.socket.DatagramChannelConfig;
* </tr><tr>
* </table>
*/
public interface NioDatagramChannelConfig extends DatagramChannelConfig {
public interface NioDatagramChannelConfig extends DatagramChannelConfig, NioChannelConfig {
/**
* Returns the high water mark of the write buffer. If the number of bytes
* queued in the write buffer exceeds this value, {@link Channel#isWritable()}
* will start to return {@code true}.
*/
int getWriteBufferHighWaterMark();
/**
* Sets the high water mark of the write buffer. If the number of bytes
* queued in the write buffer exceeds this value, {@link Channel#isWritable()}
* will start to return {@code true}.
*/
void setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
/**
* Returns the low water mark of the write buffer. Once the number of bytes
* queued in the write buffer exceeded the
* {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
* dropped down below this value, {@link Channel#isWritable()} will return
* {@code false} again.
*/
int getWriteBufferLowWaterMark();
/**
* Sets the low water mark of the write buffer. Once the number of bytes
* queued in the write buffer exceeded the
* {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
* dropped down below this value, {@link Channel#isWritable()} will return
* {@code false} again.
*/
void setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
/**
* Returns the maximum loop count for a write operation until
* {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
* It is similar to what a spin lock is used for in concurrency programming.
* It improves memory utilization and write throughput depending on
* the platform that JVM runs on. The default value is {@code 16}.
*/
int getWriteSpinCount();
/**
* Sets the maximum loop count for a write operation until
* {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
* It is similar to what a spin lock is used for in concurrency programming.
* It improves memory utilization and write throughput depending on
* the platform that JVM runs on. The default value is {@code 16}.
*
* @throws IllegalArgumentException
* if the specified value is {@code 0} or less than {@code 0}
*/
void setWriteSpinCount(int writeSpinCount);
}

View File

@ -155,7 +155,9 @@ class NioDatagramWorker implements Runnable {
// Release the Selector if the execution fails.
selector.close();
} catch (final Throwable t) {
logger.warn("Failed to close a selector.", t);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a selector.", t);
}
}
this.selector = selector = null;
// The method will return to the caller at this point.

View File

@ -70,18 +70,25 @@ final class NioProviderMetadata {
if (constraintLevel < 0) {
constraintLevel = 2;
logger.debug(
"Couldn't determine the NIO constraint level from " +
"the system properties; using the safest level (2)");
if (logger.isDebugEnabled()) {
logger.debug(
"Couldn't determine the NIO constraint level from " +
"the system properties; using the safest level (2)");
}
} else if (constraintLevel != 0) {
logger.info(
"Using the autodetected NIO constraint level: " +
constraintLevel +
" (Use better NIO provider for better performance)");
if (logger.isInfoEnabled()) {
logger.info(
"Using the autodetected NIO constraint level: " +
constraintLevel +
" (Use better NIO provider for better performance)");
}
} else {
logger.debug(
"Using the autodetected NIO constraint level: " +
constraintLevel);
if (logger.isDebugEnabled()) {
logger.debug(
"Using the autodetected NIO constraint level: " +
constraintLevel);
}
}
}
@ -235,7 +242,9 @@ final class NioProviderMetadata {
ch.socket().bind(new InetSocketAddress(0));
ch.configureBlocking(false);
} catch (Throwable e) {
logger.warn("Failed to configure a temporary socket.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to configure a temporary socket.", e);
}
return -1;
}
@ -243,7 +252,9 @@ final class NioProviderMetadata {
try {
loop = new SelectorLoop();
} catch (Throwable e) {
logger.warn("Failed to open a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to open a temporary selector.", e);
}
return -1;
}
@ -251,7 +262,9 @@ final class NioProviderMetadata {
try {
ch.register(loop.selector, 0);
} catch (Throwable e) {
logger.warn("Failed to register a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to register a temporary selector.", e);
}
return -1;
}
@ -337,7 +350,9 @@ final class NioProviderMetadata {
try {
ch.close();
} catch (Throwable e) {
logger.warn("Failed to close a temporary socket.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a temporary socket.", e);
}
}
}
@ -367,7 +382,9 @@ final class NioProviderMetadata {
try {
loop.selector.close();
} catch (Throwable e) {
logger.warn("Failed to close a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a temporary selector.", e);
}
}
}
}
@ -405,7 +422,9 @@ final class NioProviderMetadata {
}
keys.clear();
} catch (IOException e) {
logger.warn("Failed to wait for a temporary selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to wait for a temporary selector.", e);
}
}
}
}

View File

@ -73,8 +73,11 @@ final class NioServerSocketChannel extends AbstractServerChannel
try {
socket.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
}
throw new ChannelException("Failed to enter non-blocking mode.", e);

View File

@ -243,8 +243,10 @@ class NioServerSocketPipelineSink extends AbstractChannelSink {
// Closed as requested.
break;
} catch (Throwable e) {
logger.warn(
"Failed to accept a connection.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to accept a connection.", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
@ -266,14 +268,18 @@ class NioServerSocketPipelineSink extends AbstractChannelSink {
worker.register(NioAcceptedSocketChannel.create(channel.getFactory(), pipeline, channel,
NioServerSocketPipelineSink.this, acceptedSocket, worker, currentThread), null);
} catch (Exception e) {
logger.warn(
"Failed to initialize an accepted socket.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to initialize an accepted socket.", e);
}
try {
acceptedSocket.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
}
}
}
}
@ -283,7 +289,9 @@ class NioServerSocketPipelineSink extends AbstractChannelSink {
try {
selector.close();
} catch (Exception e) {
logger.warn("Failed to close a selector.", e);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a selector.", e);
}
}
}
}

View File

@ -15,12 +15,8 @@
*/
package io.netty.channel.socket.nio;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import io.netty.channel.AdaptiveReceiveBufferSizePredictor;
import io.netty.channel.AdaptiveReceiveBufferSizePredictorFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ReceiveBufferSizePredictor;
import io.netty.channel.ReceiveBufferSizePredictorFactory;
@ -52,60 +48,8 @@ import io.netty.channel.socket.SocketChannelConfig;
* </tr>
* </table>
*/
public interface NioSocketChannelConfig extends SocketChannelConfig {
public interface NioSocketChannelConfig extends SocketChannelConfig, NioChannelConfig {
/**
* Returns the high water mark of the write buffer. If the number of bytes
* queued in the write buffer exceeds this value, {@link Channel#isWritable()}
* will start to return {@code false}.
*/
int getWriteBufferHighWaterMark();
/**
* Sets the high water mark of the write buffer. If the number of bytes
* queued in the write buffer exceeds this value, {@link Channel#isWritable()}
* will start to return {@code false}.
*/
void setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
/**
* Returns the low water mark of the write buffer. Once the number of bytes
* queued in the write buffer exceeded the
* {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
* dropped down below this value, {@link Channel#isWritable()} will return
* {@code true} again.
*/
int getWriteBufferLowWaterMark();
/**
* Sets the low water mark of the write buffer. Once the number of bytes
* queued in the write buffer exceeded the
* {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
* dropped down below this value, {@link Channel#isWritable()} will return
* {@code true} again.
*/
void setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
/**
* Returns the maximum loop count for a write operation until
* {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
* It is similar to what a spin lock is used for in concurrency programming.
* It improves memory utilization and write throughput depending on
* the platform that JVM runs on. The default value is {@code 16}.
*/
int getWriteSpinCount();
/**
* Sets the maximum loop count for a write operation until
* {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
* It is similar to what a spin lock is used for in concurrency programming.
* It improves memory utilization and write throughput depending on
* the platform that JVM runs on. The default value is {@code 16}.
*
* @throws IllegalArgumentException
* if the specified value is {@code 0} or less than {@code 0}
*/
void setWriteSpinCount(int writeSpinCount);
/**
* Returns the {@link ReceiveBufferSizePredictor} which predicts the

View File

@ -103,7 +103,9 @@ class NioWorker implements Runnable {
try {
selector.close();
} catch (Throwable t) {
logger.warn("Failed to close a selector.", t);
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a selector.", t);
}
}
this.selector = selector = null;
// The method will return to the caller at this point.
@ -197,8 +199,10 @@ class NioWorker implements Runnable {
try {
selector.close();
} catch (IOException e) {
logger.warn(
"Failed to close a selector.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a selector.", e);
}
} finally {
this.selector = null;
}
@ -215,8 +219,11 @@ class NioWorker implements Runnable {
shutdown = false;
}
} catch (Throwable t) {
logger.warn(
"Unexpected exception in the selector loop.", t);
if (logger.isWarnEnabled()) {
logger.warn(
"Unexpected exception in the selector loop.", t);
}
// Prevent possible consecutive immediate failures that lead to
// excessive CPU consumption.

View File

@ -32,10 +32,13 @@ final class SelectorUtil {
try {
selector.select(500);
} catch (CancelledKeyException e) {
if (logger.isDebugEnabled()) {
logger.debug(
CancelledKeyException.class.getSimpleName() +
" raised by a Selector - JDK bug?", e);
}
// Harmless exception - log anyway
logger.debug(
CancelledKeyException.class.getSimpleName() +
" raised by a Selector - JDK bug?", e);
}
}

View File

@ -72,8 +72,11 @@ final class OioServerSocketChannel extends AbstractServerChannel
try {
socket.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
}
throw new ChannelException(
"Failed to set the server socket timeout.", e);

View File

@ -203,14 +203,18 @@ class OioServerSocketPipelineSink extends AbstractChannelSink {
workerExecutor,
new OioWorker(acceptedChannel));
} catch (Exception e) {
logger.warn(
"Failed to initialize an accepted socket.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to initialize an accepted socket.", e);
}
try {
acceptedSocket.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
}
}
}
} catch (SocketTimeoutException e) {
@ -222,8 +226,11 @@ class OioServerSocketPipelineSink extends AbstractChannelSink {
break;
}
logger.warn(
"Failed to accept a connection.", e);
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to accept a connection.", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {