code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) {
if (checkOpen(true)) {
pipeline().fireChannelRead(msg);
}
return checkException(promise);
} | Writes one message to the inbound of this {@link Channel} and does not flush it. This
method is conceptually equivalent to {@link #write(Object, ChannelPromise)}.
@see #writeOneOutbound(Object, ChannelPromise) |
public boolean writeOutbound(Object... msgs) {
ensureOpen();
if (msgs.length == 0) {
return isNotEmpty(outboundMessages);
}
RecyclableArrayList futures = RecyclableArrayList.newInstance(msgs.length);
try {
for (Object m: msgs) {
if (m == null) {
break;
}
futures.add(write(m));
}
flushOutbound0();
int size = futures.size();
for (int i = 0; i < size; i++) {
ChannelFuture future = (ChannelFuture) futures.get(i);
if (future.isDone()) {
recordException(future);
} else {
// The write may be delayed to run later by runPendingTasks()
future.addListener(recordExceptionListener);
}
}
checkException();
return isNotEmpty(outboundMessages);
} finally {
futures.recycle();
}
} | Write messages to the outbound of this {@link Channel}.
@param msgs the messages to be written
@return bufferReadable returns {@code true} if the write operation did add something to the outbound buffer |
public ChannelFuture writeOneOutbound(Object msg, ChannelPromise promise) {
if (checkOpen(true)) {
return write(msg, promise);
}
return checkException(promise);
} | Writes one message to the outbound of this {@link Channel} and does not flush it. This
method is conceptually equivalent to {@link #write(Object, ChannelPromise)}.
@see #writeOneInbound(Object, ChannelPromise) |
private boolean finish(boolean releaseAll) {
close();
try {
checkException();
return isNotEmpty(inboundMessages) || isNotEmpty(outboundMessages);
} finally {
if (releaseAll) {
releaseAll(inboundMessages);
releaseAll(outboundMessages);
}
}
} | Mark this {@link Channel} as finished. Any further try to write data to it will fail.
@param releaseAll if {@code true} all pending message in the inbound and outbound buffer are released.
@return bufferReadable returns {@code true} if any of the used buffers has something left to read |
public void runPendingTasks() {
try {
loop.runTasks();
} catch (Exception e) {
recordException(e);
}
try {
loop.runScheduledTasks();
} catch (Exception e) {
recordException(e);
}
} | Run all tasks (which also includes scheduled tasks) that are pending in the {@link EventLoop}
for this {@link Channel} |
private ChannelFuture checkException(ChannelPromise promise) {
Throwable t = lastException;
if (t != null) {
lastException = null;
if (promise.isVoid()) {
PlatformDependent.throwException(t);
}
return promise.setFailure(t);
}
return promise.setSuccess();
} | Checks for the presence of an {@link Exception}. |
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
// Serve the WebSocket handshake request.
if (!req.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)
|| !HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) {
throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade");
}
// Hixie 75 does not contain these headers while Hixie 76 does
boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) &&
req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
// Create the WebSocket handshake response.
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101,
isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake"));
if (headers != null) {
res.headers().add(headers);
}
res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
// Fill in the headers and contents depending on handshake getMethod.
if (isHixie76) {
// New handshake getMethod with a challenge:
res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN));
res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, uri());
String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
if (subprotocols != null) {
String selectedSubprotocol = selectSubprotocol(subprotocols);
if (selectedSubprotocol == null) {
if (logger.isDebugEnabled()) {
logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
}
} else {
res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
}
}
// Calculate the answer of the challenge.
String key1 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY1);
String key2 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) /
BEGINNING_SPACE.matcher(key1).replaceAll("").length());
int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) /
BEGINNING_SPACE.matcher(key2).replaceAll("").length());
long c = req.content().readLong();
ByteBuf input = Unpooled.wrappedBuffer(new byte[16]).setIndex(0, 0);
input.writeInt(a);
input.writeInt(b);
input.writeLong(c);
res.content().writeBytes(WebSocketUtil.md5(input.array()));
} else {
// Old Hixie 75 handshake getMethod with no challenge:
String origin = req.headers().get(HttpHeaderNames.ORIGIN);
if (origin == null) {
throw new WebSocketHandshakeException("Missing origin header, got only " + req.headers().names());
}
res.headers().add(HttpHeaderNames.WEBSOCKET_ORIGIN, origin);
res.headers().add(HttpHeaderNames.WEBSOCKET_LOCATION, uri());
String protocol = req.headers().get(HttpHeaderNames.WEBSOCKET_PROTOCOL);
if (protocol != null) {
res.headers().add(HttpHeaderNames.WEBSOCKET_PROTOCOL, selectSubprotocol(protocol));
}
}
return res;
} | <p>
Handle the web socket handshake for the web socket specification <a href=
"http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00">HyBi version 0</a> and lower. This standard
is really a rehash of <a href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76" >hixie-76</a> and
<a href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75" >hixie-75</a>.
</p>
<p>
Browser request to the server:
</p>
<pre>
GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Protocol: chat, sample
Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5
Sec-WebSocket-Key2: 12998 5 Y3 1 .P00
^n:ds[4U
</pre>
<p>
Server response:
</p>
<pre>
HTTP/1.1 101 WebSocket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Location: ws://example.com/demo
Sec-WebSocket-Protocol: sample
8jKS'y:G*Co,Wxa-
</pre> |
@Override
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) {
return channel.writeAndFlush(frame, promise);
} | Echo back the closing frame
@param channel
Channel
@param frame
Web Socket frame that was received |
public EpollMode getEpollMode() {
return ((AbstractEpollChannel) channel).isFlagSet(Native.EPOLLET)
? EpollMode.EDGE_TRIGGERED : EpollMode.LEVEL_TRIGGERED;
} | Return the {@link EpollMode} used. Default is
{@link EpollMode#EDGE_TRIGGERED}. If you want to use {@link #isAutoRead()} {@code false} or
{@link #getMaxMessagesPerRead()} and have an accurate behaviour you should use
{@link EpollMode#LEVEL_TRIGGERED}. |
public EpollChannelConfig setEpollMode(EpollMode mode) {
if (mode == null) {
throw new NullPointerException("mode");
}
try {
switch (mode) {
case EDGE_TRIGGERED:
checkChannelNotRegistered();
((AbstractEpollChannel) channel).setFlag(Native.EPOLLET);
break;
case LEVEL_TRIGGERED:
checkChannelNotRegistered();
((AbstractEpollChannel) channel).clearFlag(Native.EPOLLET);
break;
default:
throw new Error();
}
} catch (IOException e) {
throw new ChannelException(e);
}
return this;
} | Set the {@link EpollMode} used. Default is
{@link EpollMode#EDGE_TRIGGERED}. If you want to use {@link #isAutoRead()} {@code false} or
{@link #getMaxMessagesPerRead()} and have an accurate behaviour you should use
{@link EpollMode#LEVEL_TRIGGERED}.
<strong>Be aware this config setting can only be adjusted before the channel was registered.</strong> |
public void setBodyHttpDatas(List<InterfaceHttpData> datas) throws ErrorDataEncoderException {
if (datas == null) {
throw new NullPointerException("datas");
}
globalBodySize = 0;
bodyListDatas.clear();
currentFileUpload = null;
duringMixedMode = false;
multipartHttpDatas.clear();
for (InterfaceHttpData data : datas) {
addBodyHttpData(data);
}
} | Set the Body HttpDatas list
@throws NullPointerException
for datas
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
public void addBodyAttribute(String name, String value) throws ErrorDataEncoderException {
String svalue = value != null? value : StringUtil.EMPTY_STRING;
Attribute data = factory.createAttribute(request, checkNotNull(name, "name"), svalue);
addBodyHttpData(data);
} | Add a simple attribute in the body as Name=Value
@param name
name of the parameter
@param value
the value of the parameter
@throws NullPointerException
for name
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
public void addBodyFileUpload(String name, File file, String contentType, boolean isText)
throws ErrorDataEncoderException {
addBodyFileUpload(name, file.getName(), file, contentType, isText);
} | Add a file as a FileUpload
@param name
the name of the parameter
@param file
the file to be uploaded (if not Multipart mode, only the filename will be included)
@param contentType
the associated contentType for the File
@param isText
True if this file should be transmitted in Text format (else binary)
@throws NullPointerException
for name and file
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
public void addBodyFileUpload(String name, String filename, File file, String contentType, boolean isText)
throws ErrorDataEncoderException {
checkNotNull(name, "name");
checkNotNull(file, "file");
if (filename == null) {
filename = StringUtil.EMPTY_STRING;
}
String scontentType = contentType;
String contentTransferEncoding = null;
if (contentType == null) {
if (isText) {
scontentType = HttpPostBodyUtil.DEFAULT_TEXT_CONTENT_TYPE;
} else {
scontentType = HttpPostBodyUtil.DEFAULT_BINARY_CONTENT_TYPE;
}
}
if (!isText) {
contentTransferEncoding = HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value();
}
FileUpload fileUpload = factory.createFileUpload(request, name, filename, scontentType,
contentTransferEncoding, null, file.length());
try {
fileUpload.setContent(file);
} catch (IOException e) {
throw new ErrorDataEncoderException(e);
}
addBodyHttpData(fileUpload);
} | Add a file as a FileUpload
@param name
the name of the parameter
@param file
the file to be uploaded (if not Multipart mode, only the filename will be included)
@param filename
the filename to use for this File part, empty String will be ignored by
the encoder
@param contentType
the associated contentType for the File
@param isText
True if this file should be transmitted in Text format (else binary)
@throws NullPointerException
for name and file
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
public void addBodyFileUploads(String name, File[] file, String[] contentType, boolean[] isText)
throws ErrorDataEncoderException {
if (file.length != contentType.length && file.length != isText.length) {
throw new IllegalArgumentException("Different array length");
}
for (int i = 0; i < file.length; i++) {
addBodyFileUpload(name, file[i], contentType[i], isText[i]);
}
} | Add a series of Files associated with one File parameter
@param name
the name of the parameter
@param file
the array of files
@param contentType
the array of content Types associated with each file
@param isText
the array of isText attribute (False meaning binary mode) for each file
@throws IllegalArgumentException
also throws if array have different sizes
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
public void addBodyHttpData(InterfaceHttpData data) throws ErrorDataEncoderException {
if (headerFinalized) {
throw new ErrorDataEncoderException("Cannot add value once finalized");
}
bodyListDatas.add(checkNotNull(data, "data"));
if (!isMultipart) {
if (data instanceof Attribute) {
Attribute attribute = (Attribute) data;
try {
// name=value& with encoded name and attribute
String key = encodeAttribute(attribute.getName(), charset);
String value = encodeAttribute(attribute.getValue(), charset);
Attribute newattribute = factory.createAttribute(request, key, value);
multipartHttpDatas.add(newattribute);
globalBodySize += newattribute.getName().length() + 1 + newattribute.length() + 1;
} catch (IOException e) {
throw new ErrorDataEncoderException(e);
}
} else if (data instanceof FileUpload) {
// since not Multipart, only name=filename => Attribute
FileUpload fileUpload = (FileUpload) data;
// name=filename& with encoded name and filename
String key = encodeAttribute(fileUpload.getName(), charset);
String value = encodeAttribute(fileUpload.getFilename(), charset);
Attribute newattribute = factory.createAttribute(request, key, value);
multipartHttpDatas.add(newattribute);
globalBodySize += newattribute.getName().length() + 1 + newattribute.length() + 1;
}
return;
}
/*
* Logic:
* if not Attribute:
* add Data to body list
* if (duringMixedMode)
* add endmixedmultipart delimiter
* currentFileUpload = null
* duringMixedMode = false;
* add multipart delimiter, multipart body header and Data to multipart list
* reset currentFileUpload, duringMixedMode
* if FileUpload: take care of multiple file for one field => mixed mode
* if (duringMixedMode)
* if (currentFileUpload.name == data.name)
* add mixedmultipart delimiter, mixedmultipart body header and Data to multipart list
* else
* add endmixedmultipart delimiter, multipart body header and Data to multipart list
* currentFileUpload = data
* duringMixedMode = false;
* else
* if (currentFileUpload.name == data.name)
* change multipart body header of previous file into multipart list to
* mixedmultipart start, mixedmultipart body header
* add mixedmultipart delimiter, mixedmultipart body header and Data to multipart list
* duringMixedMode = true
* else
* add multipart delimiter, multipart body header and Data to multipart list
* currentFileUpload = data
* duringMixedMode = false;
* Do not add last delimiter! Could be:
* if duringmixedmode: endmixedmultipart + endmultipart
* else only endmultipart
*/
if (data instanceof Attribute) {
if (duringMixedMode) {
InternalAttribute internal = new InternalAttribute(charset);
internal.addValue("\r\n--" + multipartMixedBoundary + "--");
multipartHttpDatas.add(internal);
multipartMixedBoundary = null;
currentFileUpload = null;
duringMixedMode = false;
}
InternalAttribute internal = new InternalAttribute(charset);
if (!multipartHttpDatas.isEmpty()) {
// previously a data field so CRLF
internal.addValue("\r\n");
}
internal.addValue("--" + multipartDataBoundary + "\r\n");
// content-disposition: form-data; name="field1"
Attribute attribute = (Attribute) data;
internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
+ HttpHeaderValues.NAME + "=\"" + attribute.getName() + "\"\r\n");
// Add Content-Length: xxx
internal.addValue(HttpHeaderNames.CONTENT_LENGTH + ": " +
attribute.length() + "\r\n");
Charset localcharset = attribute.getCharset();
if (localcharset != null) {
// Content-Type: text/plain; charset=charset
internal.addValue(HttpHeaderNames.CONTENT_TYPE + ": " +
HttpPostBodyUtil.DEFAULT_TEXT_CONTENT_TYPE + "; " +
HttpHeaderValues.CHARSET + '='
+ localcharset.name() + "\r\n");
}
// CRLF between body header and data
internal.addValue("\r\n");
multipartHttpDatas.add(internal);
multipartHttpDatas.add(data);
globalBodySize += attribute.length() + internal.size();
} else if (data instanceof FileUpload) {
FileUpload fileUpload = (FileUpload) data;
InternalAttribute internal = new InternalAttribute(charset);
if (!multipartHttpDatas.isEmpty()) {
// previously a data field so CRLF
internal.addValue("\r\n");
}
boolean localMixed;
if (duringMixedMode) {
if (currentFileUpload != null && currentFileUpload.getName().equals(fileUpload.getName())) {
// continue a mixed mode
localMixed = true;
} else {
// end a mixed mode
// add endmixedmultipart delimiter, multipart body header
// and
// Data to multipart list
internal.addValue("--" + multipartMixedBoundary + "--");
multipartHttpDatas.add(internal);
multipartMixedBoundary = null;
// start a new one (could be replaced if mixed start again
// from here
internal = new InternalAttribute(charset);
internal.addValue("\r\n");
localMixed = false;
// new currentFileUpload and no more in Mixed mode
currentFileUpload = fileUpload;
duringMixedMode = false;
}
} else {
if (encoderMode != EncoderMode.HTML5 && currentFileUpload != null
&& currentFileUpload.getName().equals(fileUpload.getName())) {
// create a new mixed mode (from previous file)
// change multipart body header of previous file into
// multipart list to
// mixedmultipart start, mixedmultipart body header
// change Internal (size()-2 position in multipartHttpDatas)
// from (line starting with *)
// --AaB03x
// * Content-Disposition: form-data; name="files";
// filename="file1.txt"
// Content-Type: text/plain
// to (lines starting with *)
// --AaB03x
// * Content-Disposition: form-data; name="files"
// * Content-Type: multipart/mixed; boundary=BbC04y
// *
// * --BbC04y
// * Content-Disposition: attachment; filename="file1.txt"
// Content-Type: text/plain
initMixedMultipart();
InternalAttribute pastAttribute = (InternalAttribute) multipartHttpDatas.get(multipartHttpDatas
.size() - 2);
// remove past size
globalBodySize -= pastAttribute.size();
StringBuilder replacement = new StringBuilder(
139 + multipartDataBoundary.length() + multipartMixedBoundary.length() * 2 +
fileUpload.getFilename().length() + fileUpload.getName().length())
.append("--")
.append(multipartDataBoundary)
.append("\r\n")
.append(HttpHeaderNames.CONTENT_DISPOSITION)
.append(": ")
.append(HttpHeaderValues.FORM_DATA)
.append("; ")
.append(HttpHeaderValues.NAME)
.append("=\"")
.append(fileUpload.getName())
.append("\"\r\n")
.append(HttpHeaderNames.CONTENT_TYPE)
.append(": ")
.append(HttpHeaderValues.MULTIPART_MIXED)
.append("; ")
.append(HttpHeaderValues.BOUNDARY)
.append('=')
.append(multipartMixedBoundary)
.append("\r\n\r\n")
.append("--")
.append(multipartMixedBoundary)
.append("\r\n")
.append(HttpHeaderNames.CONTENT_DISPOSITION)
.append(": ")
.append(HttpHeaderValues.ATTACHMENT);
if (!fileUpload.getFilename().isEmpty()) {
replacement.append("; ")
.append(HttpHeaderValues.FILENAME)
.append("=\"")
.append(fileUpload.getFilename())
.append('"');
}
replacement.append("\r\n");
pastAttribute.setValue(replacement.toString(), 1);
pastAttribute.setValue("", 2);
// update past size
globalBodySize += pastAttribute.size();
// now continue
// add mixedmultipart delimiter, mixedmultipart body header
// and
// Data to multipart list
localMixed = true;
duringMixedMode = true;
} else {
// a simple new multipart
// add multipart delimiter, multipart body header and Data
// to multipart list
localMixed = false;
currentFileUpload = fileUpload;
duringMixedMode = false;
}
}
if (localMixed) {
// add mixedmultipart delimiter, mixedmultipart body header and
// Data to multipart list
internal.addValue("--" + multipartMixedBoundary + "\r\n");
if (fileUpload.getFilename().isEmpty()) {
// Content-Disposition: attachment
internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": "
+ HttpHeaderValues.ATTACHMENT + "\r\n");
} else {
// Content-Disposition: attachment; filename="file1.txt"
internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": "
+ HttpHeaderValues.ATTACHMENT + "; "
+ HttpHeaderValues.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n");
}
} else {
internal.addValue("--" + multipartDataBoundary + "\r\n");
if (fileUpload.getFilename().isEmpty()) {
// Content-Disposition: form-data; name="files";
internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
+ HttpHeaderValues.NAME + "=\"" + fileUpload.getName() + "\"\r\n");
} else {
// Content-Disposition: form-data; name="files";
// filename="file1.txt"
internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
+ HttpHeaderValues.NAME + "=\"" + fileUpload.getName() + "\"; "
+ HttpHeaderValues.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n");
}
}
// Add Content-Length: xxx
internal.addValue(HttpHeaderNames.CONTENT_LENGTH + ": " +
fileUpload.length() + "\r\n");
// Content-Type: image/gif
// Content-Type: text/plain; charset=ISO-8859-1
// Content-Transfer-Encoding: binary
internal.addValue(HttpHeaderNames.CONTENT_TYPE + ": " + fileUpload.getContentType());
String contentTransferEncoding = fileUpload.getContentTransferEncoding();
if (contentTransferEncoding != null
&& contentTransferEncoding.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) {
internal.addValue("\r\n" + HttpHeaderNames.CONTENT_TRANSFER_ENCODING + ": "
+ HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value() + "\r\n\r\n");
} else if (fileUpload.getCharset() != null) {
internal.addValue("; " + HttpHeaderValues.CHARSET + '=' + fileUpload.getCharset().name() + "\r\n\r\n");
} else {
internal.addValue("\r\n\r\n");
}
multipartHttpDatas.add(internal);
multipartHttpDatas.add(data);
globalBodySize += fileUpload.length() + internal.size();
}
} | Add the InterfaceHttpData to the Body list
@throws NullPointerException
for data
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
public HttpRequest finalizeRequest() throws ErrorDataEncoderException {
// Finalize the multipartHttpDatas
if (!headerFinalized) {
if (isMultipart) {
InternalAttribute internal = new InternalAttribute(charset);
if (duringMixedMode) {
internal.addValue("\r\n--" + multipartMixedBoundary + "--");
}
internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n");
multipartHttpDatas.add(internal);
multipartMixedBoundary = null;
currentFileUpload = null;
duringMixedMode = false;
globalBodySize += internal.size();
}
headerFinalized = true;
} else {
throw new ErrorDataEncoderException("Header already encoded");
}
HttpHeaders headers = request.headers();
List<String> contentTypes = headers.getAll(HttpHeaderNames.CONTENT_TYPE);
List<String> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING);
if (contentTypes != null) {
headers.remove(HttpHeaderNames.CONTENT_TYPE);
for (String contentType : contentTypes) {
// "multipart/form-data; boundary=--89421926422648"
String lowercased = contentType.toLowerCase();
if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) ||
lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
// ignore
} else {
headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
}
}
}
if (isMultipart) {
String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '='
+ multipartDataBoundary;
headers.add(HttpHeaderNames.CONTENT_TYPE, value);
} else {
// Not multipart
headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
}
// Now consider size for chunk or not
long realSize = globalBodySize;
if (!isMultipart) {
realSize -= 1; // last '&' removed
}
iterator = multipartHttpDatas.listIterator();
headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize));
if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
isChunked = true;
if (transferEncoding != null) {
headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
for (CharSequence v : transferEncoding) {
if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(v)) {
// ignore
} else {
headers.add(HttpHeaderNames.TRANSFER_ENCODING, v);
}
}
}
HttpUtil.setTransferEncodingChunked(request, true);
// wrap to hide the possible content
return new WrappedHttpRequest(request);
} else {
// get the only one body and set it to the request
HttpContent chunk = nextChunk();
if (request instanceof FullHttpRequest) {
FullHttpRequest fullRequest = (FullHttpRequest) request;
ByteBuf chunkContent = chunk.content();
if (fullRequest.content() != chunkContent) {
fullRequest.content().clear().writeBytes(chunkContent);
chunkContent.release();
}
return fullRequest;
} else {
return new WrappedFullHttpRequest(request, chunk);
}
}
} | Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br>
Once finalized, no data must be added.<br>
If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote
server.
@return the request object (chunked or not according to size of body)
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done |
@SuppressWarnings("unchecked")
private String encodeAttribute(String s, Charset charset) throws ErrorDataEncoderException {
if (s == null) {
return "";
}
try {
String encoded = URLEncoder.encode(s, charset.name());
if (encoderMode == EncoderMode.RFC3986) {
for (Map.Entry<Pattern, String> entry : percentEncodings) {
String replacement = entry.getValue();
encoded = entry.getKey().matcher(encoded).replaceAll(replacement);
}
}
return encoded;
} catch (UnsupportedEncodingException e) {
throw new ErrorDataEncoderException(charset.name(), e);
}
} | Encode one attribute
@return the encoded attribute
@throws ErrorDataEncoderException
if the encoding is in error |
private HttpContent encodeNextChunkMultipart(int sizeleft) throws ErrorDataEncoderException {
if (currentData == null) {
return null;
}
ByteBuf buffer;
if (currentData instanceof InternalAttribute) {
buffer = ((InternalAttribute) currentData).toByteBuf();
currentData = null;
} else {
try {
buffer = ((HttpData) currentData).getChunk(sizeleft);
} catch (IOException e) {
throw new ErrorDataEncoderException(e);
}
if (buffer.capacity() == 0) {
// end for current InterfaceHttpData, need more data
currentData = null;
return null;
}
}
if (currentBuffer == null) {
currentBuffer = buffer;
} else {
currentBuffer = wrappedBuffer(currentBuffer, buffer);
}
if (currentBuffer.readableBytes() < HttpPostBodyUtil.chunkSize) {
currentData = null;
return null;
}
buffer = fillByteBuf();
return new DefaultHttpContent(buffer);
} | From the current context (currentBuffer and currentData), returns the next HttpChunk (if possible) trying to get
sizeleft bytes more into the currentBuffer. This is the Multipart version.
@param sizeleft
the number of bytes to try to get from currentData
@return the next HttpChunk or null if not enough bytes were found
@throws ErrorDataEncoderException
if the encoding is in error |
private HttpContent encodeNextChunkUrlEncoded(int sizeleft) throws ErrorDataEncoderException {
if (currentData == null) {
return null;
}
int size = sizeleft;
ByteBuf buffer;
// Set name=
if (isKey) {
String key = currentData.getName();
buffer = wrappedBuffer(key.getBytes());
isKey = false;
if (currentBuffer == null) {
currentBuffer = wrappedBuffer(buffer, wrappedBuffer("=".getBytes()));
} else {
currentBuffer = wrappedBuffer(currentBuffer, buffer, wrappedBuffer("=".getBytes()));
}
// continue
size -= buffer.readableBytes() + 1;
if (currentBuffer.readableBytes() >= HttpPostBodyUtil.chunkSize) {
buffer = fillByteBuf();
return new DefaultHttpContent(buffer);
}
}
// Put value into buffer
try {
buffer = ((HttpData) currentData).getChunk(size);
} catch (IOException e) {
throw new ErrorDataEncoderException(e);
}
// Figure out delimiter
ByteBuf delimiter = null;
if (buffer.readableBytes() < size) {
isKey = true;
delimiter = iterator.hasNext() ? wrappedBuffer("&".getBytes()) : null;
}
// End for current InterfaceHttpData, need potentially more data
if (buffer.capacity() == 0) {
currentData = null;
if (currentBuffer == null) {
currentBuffer = delimiter;
} else {
if (delimiter != null) {
currentBuffer = wrappedBuffer(currentBuffer, delimiter);
}
}
if (currentBuffer.readableBytes() >= HttpPostBodyUtil.chunkSize) {
buffer = fillByteBuf();
return new DefaultHttpContent(buffer);
}
return null;
}
// Put it all together: name=value&
if (currentBuffer == null) {
if (delimiter != null) {
currentBuffer = wrappedBuffer(buffer, delimiter);
} else {
currentBuffer = buffer;
}
} else {
if (delimiter != null) {
currentBuffer = wrappedBuffer(currentBuffer, buffer, delimiter);
} else {
currentBuffer = wrappedBuffer(currentBuffer, buffer);
}
}
// end for current InterfaceHttpData, need more data
if (currentBuffer.readableBytes() < HttpPostBodyUtil.chunkSize) {
currentData = null;
isKey = true;
return null;
}
buffer = fillByteBuf();
return new DefaultHttpContent(buffer);
} | From the current context (currentBuffer and currentData), returns the next HttpChunk (if possible) trying to get
sizeleft bytes more into the currentBuffer. This is the UrlEncoded version.
@param sizeleft
the number of bytes to try to get from currentData
@return the next HttpChunk or null if not enough bytes were found
@throws ErrorDataEncoderException
if the encoding is in error |
@Override
public HttpContent readChunk(ByteBufAllocator allocator) throws Exception {
if (isLastChunkSent) {
return null;
} else {
HttpContent nextChunk = nextChunk();
globalProgress += nextChunk.content().readableBytes();
return nextChunk;
}
} | Returns the next available HttpChunk. The caller is responsible to test if this chunk is the last one (isLast()),
in order to stop calling this getMethod.
@return the next available HttpChunk
@throws ErrorDataEncoderException
if the encoding is in error |
private HttpContent nextChunk() throws ErrorDataEncoderException {
if (isLastChunk) {
isLastChunkSent = true;
return LastHttpContent.EMPTY_LAST_CONTENT;
}
// first test if previous buffer is not empty
int size = calculateRemainingSize();
if (size <= 0) {
// NextChunk from buffer
ByteBuf buffer = fillByteBuf();
return new DefaultHttpContent(buffer);
}
// size > 0
if (currentData != null) {
// continue to read data
HttpContent chunk;
if (isMultipart) {
chunk = encodeNextChunkMultipart(size);
} else {
chunk = encodeNextChunkUrlEncoded(size);
}
if (chunk != null) {
// NextChunk from data
return chunk;
}
size = calculateRemainingSize();
}
if (!iterator.hasNext()) {
return lastChunk();
}
while (size > 0 && iterator.hasNext()) {
currentData = iterator.next();
HttpContent chunk;
if (isMultipart) {
chunk = encodeNextChunkMultipart(size);
} else {
chunk = encodeNextChunkUrlEncoded(size);
}
if (chunk == null) {
// not enough
size = calculateRemainingSize();
continue;
}
// NextChunk from data
return chunk;
}
// end since no more data
return lastChunk();
} | Returns the next available HttpChunk. The caller is responsible to test if this chunk is the last one (isLast()),
in order to stop calling this getMethod.
@return the next available HttpChunk
@throws ErrorDataEncoderException
if the encoding is in error |
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
if (headers != null) {
res.headers().add(headers);
}
CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
if (key == null) {
throw new WebSocketHandshakeException("not a WebSocket request: missing key");
}
String acceptSeed = key + WEBSOCKET_08_ACCEPT_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
String accept = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug("WebSocket version 08 server handshake key: {}, response: {}", key, accept);
}
res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
if (subprotocols != null) {
String selectedSubprotocol = selectSubprotocol(subprotocols);
if (selectedSubprotocol == null) {
if (logger.isDebugEnabled()) {
logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
}
} else {
res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
}
}
return res;
} | <p>
Handle the web socket handshake for the web socket specification <a href=
"http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08">HyBi version 8 to 10</a>. Version 8, 9 and
10 share the same wire protocol.
</p>
<p>
Browser request to the server:
</p>
<pre>
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 8
</pre>
<p>
Server response:
</p>
<pre>
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
</pre> |
void createHuffmanDecodingTables() {
final int alphabetSize = this.alphabetSize;
for (int table = 0; table < tableCodeLengths.length; table++) {
final int[] tableBases = codeBases[table];
final int[] tableLimits = codeLimits[table];
final int[] tableSymbols = codeSymbols[table];
final byte[] codeLengths = tableCodeLengths[table];
int minimumLength = HUFFMAN_DECODE_MAX_CODE_LENGTH;
int maximumLength = 0;
// Find the minimum and maximum code length for the table
for (int i = 0; i < alphabetSize; i++) {
final byte currLength = codeLengths[i];
maximumLength = Math.max(currLength, maximumLength);
minimumLength = Math.min(currLength, minimumLength);
}
minimumLengths[table] = minimumLength;
// Calculate the first output symbol for each code length
for (int i = 0; i < alphabetSize; i++) {
tableBases[codeLengths[i] + 1]++;
}
for (int i = 1, b = tableBases[0]; i < HUFFMAN_DECODE_MAX_CODE_LENGTH + 2; i++) {
b += tableBases[i];
tableBases[i] = b;
}
// Calculate the first and last Huffman code for each code length (codes at a given
// length are sequential in value)
for (int i = minimumLength, code = 0; i <= maximumLength; i++) {
int base = code;
code += tableBases[i + 1] - tableBases[i];
tableBases[i] = base - tableBases[i];
tableLimits[i] = code - 1;
code <<= 1;
}
// Populate the mapping from canonical code index to output symbol
for (int bitLength = minimumLength, codeIndex = 0; bitLength <= maximumLength; bitLength++) {
for (int symbol = 0; symbol < alphabetSize; symbol++) {
if (codeLengths[symbol] == bitLength) {
tableSymbols[codeIndex++] = symbol;
}
}
}
}
currentTable = selectors[0];
} | Constructs Huffman decoding tables from lists of Canonical Huffman code lengths. |
int nextSymbol() {
// Move to next group selector if required
if (++groupPosition % HUFFMAN_GROUP_RUN_LENGTH == 0) {
groupIndex++;
if (groupIndex == selectors.length) {
throw new DecompressionException("error decoding block");
}
currentTable = selectors[groupIndex] & 0xff;
}
final Bzip2BitReader reader = this.reader;
final int currentTable = this.currentTable;
final int[] tableLimits = codeLimits[currentTable];
final int[] tableBases = codeBases[currentTable];
final int[] tableSymbols = codeSymbols[currentTable];
int codeLength = minimumLengths[currentTable];
// Starting with the minimum bit length for the table, read additional bits one at a time
// until a complete code is recognised
int codeBits = reader.readBits(codeLength);
for (; codeLength <= HUFFMAN_DECODE_MAX_CODE_LENGTH; codeLength++) {
if (codeBits <= tableLimits[codeLength]) {
// Convert the code to a symbol index and return
return tableSymbols[codeBits - tableBases[codeLength]];
}
codeBits = codeBits << 1 | reader.readBits(1);
}
throw new DecompressionException("a valid code was not recognised");
} | Decodes and returns the next symbol.
@return The decoded symbol |
public long number() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionNumber(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the current number of sessions in the internal session cache. |
public long connect() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionConnect(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of started SSL/TLS handshakes in client mode. |
public long connectGood() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionConnectGood(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of successfully established SSL/TLS sessions in client mode. |
public long connectRenegotiate() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionConnectRenegotiate(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of start renegotiations in client mode. |
public long accept() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionAccept(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of started SSL/TLS handshakes in server mode. |
public long acceptGood() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionAcceptGood(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of successfully established SSL/TLS sessions in server mode. |
public long acceptRenegotiate() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionAcceptRenegotiate(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of start renegotiations in server mode. |
public long hits() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionHits(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of successfully reused sessions. In client mode, a session set with {@code SSL_set_session}
successfully reused is counted as a hit. In server mode, a session successfully retrieved from internal or
external cache is counted as a hit. |
public long cbHits() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionCbHits(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of successfully retrieved sessions from the external session cache in server mode. |
public long misses() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionMisses(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of sessions proposed by clients that were not found in the internal session cache
in server mode. |
public long timeouts() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionTimeouts(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of sessions proposed by clients and either found in the internal or external session cache
in server mode, but that were invalid due to timeout. These sessions are not included in the {@link #hits()}
count. |
public long cacheFull() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionCacheFull(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of sessions that were removed because the maximum session cache size was exceeded. |
public long ticketKeyFail() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionTicketKeyFail(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of times a client presented a ticket that did not match any key in the list. |
public long ticketKeyNew() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionTicketKeyNew(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of times a client did not present a ticket and we issued a new one |
public long ticketKeyRenew() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionTicketKeyRenew(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of times a client presented a ticket derived from an older key,
and we upgraded to the primary key. |
public long ticketKeyResume() {
Lock readerLock = context.ctxLock.readLock();
readerLock.lock();
try {
return SSLContext.sessionTicketKeyResume(context.ctx);
} finally {
readerLock.unlock();
}
} | Returns the number of times a client presented a ticket derived from the primary key. |
@Setup
public void setup() {
System.setProperty("io.netty.buffer.checkAccessible", checkAccessible);
System.setProperty("io.netty.buffer.checkBounds", checkBounds);
buffer = bufferType.newBuffer();
} | applies only to readBatch benchmark |
static void addIfSupported(Set<String> supported, List<String> enabled, String... names) {
for (String n: names) {
if (supported.contains(n)) {
enabled.add(n);
}
}
} | Add elements from {@code names} into {@code enabled} if they are in {@code supported}. |
static SSLHandshakeException toSSLHandshakeException(Throwable e) {
if (e instanceof SSLHandshakeException) {
return (SSLHandshakeException) e;
}
return (SSLHandshakeException) new SSLHandshakeException(e.getMessage()).initCause(e);
} | Converts the given exception to a {@link SSLHandshakeException}, if it isn't already. |
static int getEncryptedPacketLength(ByteBuf buffer, int offset) {
int packetLength = 0;
// SSLv3 or TLS - Check ContentType
boolean tls;
switch (buffer.getUnsignedByte(offset)) {
case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
case SSL_CONTENT_TYPE_ALERT:
case SSL_CONTENT_TYPE_HANDSHAKE:
case SSL_CONTENT_TYPE_APPLICATION_DATA:
case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT:
tls = true;
break;
default:
// SSLv2 or bad data
tls = false;
}
if (tls) {
// SSLv3 or TLS - Check ProtocolVersion
int majorVersion = buffer.getUnsignedByte(offset + 1);
if (majorVersion == 3) {
// SSLv3 or TLS
packetLength = unsignedShortBE(buffer, offset + 3) + SSL_RECORD_HEADER_LENGTH;
if (packetLength <= SSL_RECORD_HEADER_LENGTH) {
// Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
tls = false;
}
} else {
// Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
tls = false;
}
}
if (!tls) {
// SSLv2 or bad data - Check the version
int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3;
int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1);
if (majorVersion == 2 || majorVersion == 3) {
// SSLv2
packetLength = headerLength == 2 ?
(shortBE(buffer, offset) & 0x7FFF) + 2 : (shortBE(buffer, offset) & 0x3FFF) + 3;
if (packetLength <= headerLength) {
return NOT_ENOUGH_DATA;
}
} else {
return NOT_ENCRYPTED;
}
}
return packetLength;
} | Return how much bytes can be read out of the encrypted data. Be aware that this method will not increase
the readerIndex of the given {@link ByteBuf}.
@param buffer
The {@link ByteBuf} to read from. Be aware that it must have at least
{@link #SSL_RECORD_HEADER_LENGTH} bytes to read,
otherwise it will throw an {@link IllegalArgumentException}.
@return length
The length of the encrypted packet that is included in the buffer or
{@link #SslUtils#NOT_ENOUGH_DATA} if not enough data is present in the
{@link ByteBuf}. This will return {@link SslUtils#NOT_ENCRYPTED} if
the given {@link ByteBuf} is not encrypted at all.
@throws IllegalArgumentException
Is thrown if the given {@link ByteBuf} has not at least {@link #SSL_RECORD_HEADER_LENGTH}
bytes to read. |
@SuppressWarnings("deprecation")
private static int unsignedShortBE(ByteBuf buffer, int offset) {
return buffer.order() == ByteOrder.BIG_ENDIAN ?
buffer.getUnsignedShort(offset) : buffer.getUnsignedShortLE(offset);
} | Reads a big-endian unsigned short integer from the buffer |
@SuppressWarnings("deprecation")
private static short shortBE(ByteBuf buffer, int offset) {
return buffer.order() == ByteOrder.BIG_ENDIAN ?
buffer.getShort(offset) : buffer.getShortLE(offset);
} | Reads a big-endian short integer from the buffer |
private static short shortBE(ByteBuffer buffer, int offset) {
return buffer.order() == ByteOrder.BIG_ENDIAN ?
buffer.getShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset));
} | Reads a big-endian short integer from the buffer |
static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) {
ByteBuf dst = Base64.encode(src, src.readerIndex(),
src.readableBytes(), true, Base64Dialect.STANDARD, allocator);
src.readerIndex(src.writerIndex());
return dst;
} | Same as {@link Base64#encode(ByteBuf, boolean)} but allows the use of a custom {@link ByteBufAllocator}.
@see Base64#encode(ByteBuf, boolean) |
static boolean isValidHostNameForSNI(String hostname) {
return hostname != null &&
hostname.indexOf('.') > 0 &&
!hostname.endsWith(".") &&
!NetUtil.isValidIpV4Address(hostname) &&
!NetUtil.isValidIpV6Address(hostname);
} | Validate that the given hostname can be used in SNI extension. |
private void issueSessionError(
ChannelHandlerContext ctx, SpdySessionStatus status) {
sendGoAwayFrame(ctx, status).addListener(new ClosingChannelFutureListener(ctx, ctx.newPromise()));
} | /*
SPDY Session Error Handling:
When a session error occurs, the endpoint encountering the error must first
send a GOAWAY frame with the Stream-ID of the most recently received stream
from the remote endpoint, and the error code for why the session is terminating.
After sending the GOAWAY frame, the endpoint must close the TCP connection. |
private void issueStreamError(ChannelHandlerContext ctx, int streamId, SpdyStreamStatus status) {
boolean fireChannelRead = !spdySession.isRemoteSideClosed(streamId);
ChannelPromise promise = ctx.newPromise();
removeStream(streamId, promise);
SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, status);
ctx.writeAndFlush(spdyRstStreamFrame, promise);
if (fireChannelRead) {
ctx.fireChannelRead(spdyRstStreamFrame);
}
} | /*
SPDY Stream Error Handling:
Upon a stream error, the endpoint must send a RST_STREAM frame which contains
the Stream-ID for the stream where the error occurred and the error getStatus which
caused the error.
After sending the RST_STREAM, the stream is closed to the sending endpoint.
Note: this is only called by the worker thread |
private void updateInitialSendWindowSize(int newInitialWindowSize) {
int deltaWindowSize = newInitialWindowSize - initialSendWindowSize;
initialSendWindowSize = newInitialWindowSize;
spdySession.updateAllSendWindowSizes(deltaWindowSize);
} | need to synchronize to prevent new streams from being created while updating active streams |
private void updateInitialReceiveWindowSize(int newInitialWindowSize) {
int deltaWindowSize = newInitialWindowSize - initialReceiveWindowSize;
initialReceiveWindowSize = newInitialWindowSize;
spdySession.updateAllReceiveWindowSizes(deltaWindowSize);
} | need to synchronize to prevent new streams from being created while updating active streams |
private boolean acceptStream(
int streamId, byte priority, boolean remoteSideClosed, boolean localSideClosed) {
// Cannot initiate any new streams after receiving or sending GOAWAY
if (receivedGoAwayFrame || sentGoAwayFrame) {
return false;
}
boolean remote = isRemoteInitiatedId(streamId);
int maxConcurrentStreams = remote ? localConcurrentStreams : remoteConcurrentStreams;
if (spdySession.numActiveStreams(remote) >= maxConcurrentStreams) {
return false;
}
spdySession.acceptStream(
streamId, priority, remoteSideClosed, localSideClosed,
initialSendWindowSize, initialReceiveWindowSize, remote);
if (remote) {
lastGoodStreamId = streamId;
}
return true;
} | need to synchronize accesses to sentGoAwayFrame, lastGoodStreamId, and initial window sizes |
public EpollSocketChannelConfig setTcpCork(boolean tcpCork) {
try {
((EpollSocketChannel) channel).socket.setTcpCork(tcpCork);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_CORK} option on the socket. See {@code man 7 tcp} for more details. |
public EpollSocketChannelConfig setSoBusyPoll(int loopMicros) {
try {
((EpollSocketChannel) channel).socket.setSoBusyPoll(loopMicros);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code SO_BUSY_POLL} option on the socket. See {@code man 7 tcp} for more details. |
public EpollSocketChannelConfig setTcpNotSentLowAt(long tcpNotSentLowAt) {
try {
((EpollSocketChannel) channel).socket.setTcpNotSentLowAt(tcpNotSentLowAt);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_NOTSENT_LOWAT} option on the socket. See {@code man 7 tcp} for more details.
@param tcpNotSentLowAt is a uint32_t |
public EpollSocketChannelConfig setTcpKeepIdle(int seconds) {
try {
((EpollSocketChannel) channel).socket.setTcpKeepIdle(seconds);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_KEEPIDLE} option on the socket. See {@code man 7 tcp} for more details. |
public EpollSocketChannelConfig setTcpKeepCnt(int probes) {
try {
((EpollSocketChannel) channel).socket.setTcpKeepCnt(probes);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_KEEPCNT} option on the socket. See {@code man 7 tcp} for more details. |
public EpollSocketChannelConfig setTcpUserTimeout(int milliseconds) {
try {
((EpollSocketChannel) channel).socket.setTcpUserTimeout(milliseconds);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_USER_TIMEOUT} option on the socket. See {@code man 7 tcp} for more details. |
public EpollSocketChannelConfig setIpTransparent(boolean transparent) {
try {
((EpollSocketChannel) channel).socket.setIpTransparent(transparent);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | If {@code true} is used <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_TRANSPARENT</a> is enabled,
{@code false} for disable it. Default is disabled. |
public EpollSocketChannelConfig setTcpMd5Sig(Map<InetAddress, byte[]> keys) {
try {
((EpollSocketChannel) channel).setTcpMd5Sig(keys);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_MD5SIG} option on the socket. See {@code linux/tcp.h} for more details.
Keys can only be set on, not read to prevent a potential leak, as they are confidential.
Allowing them being read would mean anyone with access to the channel could get them. |
public EpollSocketChannelConfig setTcpQuickAck(boolean quickAck) {
try {
((EpollSocketChannel) channel).socket.setTcpQuickAck(quickAck);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_QUICKACK} option on the socket. See <a href="http://linux.die.net/man/7/tcp">TCP_QUICKACK</a>
for more details. |
public EpollSocketChannelConfig setTcpFastOpenConnect(boolean fastOpenConnect) {
try {
((EpollSocketChannel) channel).socket.setTcpFastOpenConnect(fastOpenConnect);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the {@code TCP_FASTOPEN_CONNECT} option on the socket. Requires Linux kernel 4.11 or later.
See
<a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=19f6d3f3">this commit</a>
for more details. |
public B group(EventLoopGroup group) {
if (group == null) {
throw new NullPointerException("group");
}
if (this.group != null) {
throw new IllegalStateException("group set already");
}
this.group = group;
return self();
} | The {@link EventLoopGroup} which is used to handle all the events for the to-be-created
{@link Channel} |
public B channel(Class<? extends C> channelClass) {
if (channelClass == null) {
throw new NullPointerException("channelClass");
}
return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
} | The {@link Class} which is used to create {@link Channel} instances from.
You either use this or {@link #channelFactory(io.netty.channel.ChannelFactory)} if your
{@link Channel} implementation has no no-args constructor. |
@SuppressWarnings({ "unchecked", "deprecation" })
public B channelFactory(io.netty.channel.ChannelFactory<? extends C> channelFactory) {
return channelFactory((ChannelFactory<C>) channelFactory);
} | {@link io.netty.channel.ChannelFactory} which is used to create {@link Channel} instances from
when calling {@link #bind()}. This method is usually only used if {@link #channel(Class)}
is not working for you because of some more complex needs. If your {@link Channel} implementation
has a no-args constructor, its highly recommend to just use {@link #channel(Class)} to
simplify your code. |
public <T> B option(ChannelOption<T> option, T value) {
if (option == null) {
throw new NullPointerException("option");
}
if (value == null) {
synchronized (options) {
options.remove(option);
}
} else {
synchronized (options) {
options.put(option, value);
}
}
return self();
} | Allow to specify a {@link ChannelOption} which is used for the {@link Channel} instances once they got
created. Use a value of {@code null} to remove a previous set {@link ChannelOption}. |
public <T> B attr(AttributeKey<T> key, T value) {
if (key == null) {
throw new NullPointerException("key");
}
if (value == null) {
synchronized (attrs) {
attrs.remove(key);
}
} else {
synchronized (attrs) {
attrs.put(key, value);
}
}
return self();
} | Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is
{@code null}, the attribute of the specified {@code key} is removed. |
public ChannelFuture bind() {
validate();
SocketAddress localAddress = this.localAddress;
if (localAddress == null) {
throw new IllegalStateException("localAddress not set");
}
return doBind(localAddress);
} | Create a new {@link Channel} and bind it. |
public ChannelFuture bind(String inetHost, int inetPort) {
return bind(SocketUtils.socketAddress(inetHost, inetPort));
} | Create a new {@link Channel} and bind it. |
public ChannelFuture bind(SocketAddress localAddress) {
validate();
if (localAddress == null) {
throw new NullPointerException("localAddress");
}
return doBind(localAddress);
} | Create a new {@link Channel} and bind it. |
public B handler(ChannelHandler handler) {
if (handler == null) {
throw new NullPointerException("handler");
}
this.handler = handler;
return self();
} | the {@link ChannelHandler} to use for serving the requests. |
private static int findMatchingLength(ByteBuf in, int minIndex, int inIndex, int maxIndex) {
int matched = 0;
while (inIndex <= maxIndex - 4 &&
in.getInt(inIndex) == in.getInt(minIndex + matched)) {
inIndex += 4;
matched += 4;
}
while (inIndex < maxIndex && in.getByte(minIndex + matched) == in.getByte(inIndex)) {
++inIndex;
++matched;
}
return matched;
} | Iterates over the supplied input buffer between the supplied minIndex and
maxIndex to find how long our matched copy overlaps with an already-written
literal value.
@param in The input buffer to scan over
@param minIndex The index in the input buffer to start scanning from
@param inIndex The index of the start of our copy
@param maxIndex The length of our input buffer
@return The number of bytes for which our candidate copy is a repeat of |
private static int bitsToEncode(int value) {
int highestOneBit = Integer.highestOneBit(value);
int bitLength = 0;
while ((highestOneBit >>= 1) != 0) {
bitLength++;
}
return bitLength;
} | Calculates the minimum number of bits required to encode a value. This can
then in turn be used to calculate the number of septets or octets (as
appropriate) to use to encode a length parameter.
@param value The value to calculate the minimum number of bits required to encode
@return The minimum number of bits required to encode the supplied value |
static void encodeLiteral(ByteBuf in, ByteBuf out, int length) {
if (length < 61) {
out.writeByte(length - 1 << 2);
} else {
int bitLength = bitsToEncode(length - 1);
int bytesToEncode = 1 + bitLength / 8;
out.writeByte(59 + bytesToEncode << 2);
for (int i = 0; i < bytesToEncode; i++) {
out.writeByte(length - 1 >> i * 8 & 0x0ff);
}
}
out.writeBytes(in, length);
} | Writes a literal to the supplied output buffer by directly copying from
the input buffer. The literal is taken from the current readerIndex
up to the supplied length.
@param in The input buffer to copy from
@param out The output buffer to copy to
@param length The length of the literal to copy |
private static void encodeCopy(ByteBuf out, int offset, int length) {
while (length >= 68) {
encodeCopyWithOffset(out, offset, 64);
length -= 64;
}
if (length > 64) {
encodeCopyWithOffset(out, offset, 60);
length -= 60;
}
encodeCopyWithOffset(out, offset, length);
} | Encodes a series of copies, each at most 64 bytes in length.
@param out The output buffer to write the copy pointer to
@param offset The offset at which the original instance lies
@param length The length of the original instance |
private static int readPreamble(ByteBuf in) {
int length = 0;
int byteIndex = 0;
while (in.isReadable()) {
int current = in.readUnsignedByte();
length |= (current & 0x7f) << byteIndex++ * 7;
if ((current & 0x80) == 0) {
return length;
}
if (byteIndex >= 4) {
throw new DecompressionException("Preamble is greater than 4 bytes");
}
}
return 0;
} | Reads the length varint (a series of bytes, where the lower 7 bits
are data and the upper bit is a flag to indicate more bytes to be
read).
@param in The input buffer to read the preamble from
@return The calculated length based on the input buffer, or 0 if
no preamble is able to be calculated |
static int decodeLiteral(byte tag, ByteBuf in, ByteBuf out) {
in.markReaderIndex();
int length;
switch(tag >> 2 & 0x3F) {
case 60:
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedByte();
break;
case 61:
if (in.readableBytes() < 2) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedShortLE();
break;
case 62:
if (in.readableBytes() < 3) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedMediumLE();
break;
case 63:
if (in.readableBytes() < 4) {
return NOT_ENOUGH_INPUT;
}
length = in.readIntLE();
break;
default:
length = tag >> 2 & 0x3F;
}
length += 1;
if (in.readableBytes() < length) {
in.resetReaderIndex();
return NOT_ENOUGH_INPUT;
}
out.writeBytes(in, length);
return length;
} | Reads a literal from the input buffer directly to the output buffer.
A "literal" is an uncompressed segment of data stored directly in the
byte stream.
@param tag The tag that identified this segment as a literal is also
used to encode part of the length of the data
@param in The input buffer to read the literal from
@param out The output buffer to write the literal to
@return The number of bytes appended to the output buffer, or -1 to indicate "try again later" |
private static int decodeCopyWith1ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) {
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
int initialIndex = out.writerIndex();
int length = 4 + ((tag & 0x01c) >> 2);
int offset = (tag & 0x0e0) << 8 >> 5 | in.readUnsignedByte();
validateOffset(offset, writtenSoFar);
out.markReaderIndex();
if (offset < length) {
int copies = length / offset;
for (; copies > 0; copies--) {
out.readerIndex(initialIndex - offset);
out.readBytes(out, offset);
}
if (length % offset != 0) {
out.readerIndex(initialIndex - offset);
out.readBytes(out, length % offset);
}
} else {
out.readerIndex(initialIndex - offset);
out.readBytes(out, length);
}
out.resetReaderIndex();
return length;
} | Reads a compressed reference offset and length from the supplied input
buffer, seeks back to the appropriate place in the input buffer and
writes the found data to the supplied output stream.
@param tag The tag used to identify this as a copy is also used to encode
the length and part of the offset
@param in The input buffer to read from
@param out The output buffer to write to
@return The number of bytes appended to the output buffer, or -1 to indicate
"try again later"
@throws DecompressionException If the read offset is invalid |
private static void validateOffset(int offset, int chunkSizeSoFar) {
if (offset == 0) {
throw new DecompressionException("Offset is less than minimum permissible value");
}
if (offset < 0) {
// Due to arithmetic overflow
throw new DecompressionException("Offset is greater than maximum value supported by this implementation");
}
if (offset > chunkSizeSoFar) {
throw new DecompressionException("Offset exceeds size of chunk");
}
} | Validates that the offset extracted from a compressed reference is within
the permissible bounds of an offset (0 < offset < Integer.MAX_VALUE), and does not
exceed the length of the chunk currently read so far.
@param offset The offset extracted from the compressed reference
@param chunkSizeSoFar The number of bytes read so far from this chunk
@throws DecompressionException if the offset is invalid |
static int calculateChecksum(ByteBuf data, int offset, int length) {
Crc32c crc32 = new Crc32c();
try {
crc32.update(data, offset, length);
return maskChecksum((int) crc32.getValue());
} finally {
crc32.reset();
}
} | Computes the CRC32C checksum of the supplied data and performs the "mask" operation
on the computed checksum
@param data The input data to calculate the CRC32C checksum of |
static void validateChecksum(int expectedChecksum, ByteBuf data) {
validateChecksum(expectedChecksum, data, data.readerIndex(), data.readableBytes());
} | Computes the CRC32C checksum of the supplied data, performs the "mask" operation
on the computed checksum, and then compares the resulting masked checksum to the
supplied checksum.
@param expectedChecksum The checksum decoded from the stream to compare against
@param data The input data to calculate the CRC32C checksum of
@throws DecompressionException If the calculated and supplied checksums do not match |
static void validateChecksum(int expectedChecksum, ByteBuf data, int offset, int length) {
final int actualChecksum = calculateChecksum(data, offset, length);
if (actualChecksum != expectedChecksum) {
throw new DecompressionException(
"mismatching checksum: " + Integer.toHexString(actualChecksum) +
" (expected: " + Integer.toHexString(expectedChecksum) + ')');
}
} | Computes the CRC32C checksum of the supplied data, performs the "mask" operation
on the computed checksum, and then compares the resulting masked checksum to the
supplied checksum.
@param expectedChecksum The checksum decoded from the stream to compare against
@param data The input data to calculate the CRC32C checksum of
@throws DecompressionException If the calculated and supplied checksums do not match |
private static void encodeHeader(DnsQuery query, ByteBuf buf) {
buf.writeShort(query.id());
int flags = 0;
flags |= (query.opCode().byteValue() & 0xFF) << 14;
if (query.isRecursionDesired()) {
flags |= 1 << 8;
}
buf.writeShort(flags);
buf.writeShort(query.count(DnsSection.QUESTION));
buf.writeShort(0); // answerCount
buf.writeShort(0); // authorityResourceCount
buf.writeShort(query.count(DnsSection.ADDITIONAL));
} | Encodes the header that is always 12 bytes long.
@param query the query header being encoded
@param buf the buffer the encoded data should be written to |
public EpollDatagramChannelConfig setReusePort(boolean reusePort) {
try {
((EpollDatagramChannel) channel).socket.setReusePort(reusePort);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Set the SO_REUSEPORT option on the underlying Channel. This will allow to bind multiple
{@link EpollSocketChannel}s to the same port and so accept connections with multiple threads.
Be aware this method needs be called before {@link EpollDatagramChannel#bind(java.net.SocketAddress)} to have
any affect. |
public EpollDatagramChannelConfig setIpTransparent(boolean ipTransparent) {
try {
((EpollDatagramChannel) channel).socket.setIpTransparent(ipTransparent);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | If {@code true} is used <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_TRANSPARENT</a> is enabled,
{@code false} for disable it. Default is disabled. |
public EpollDatagramChannelConfig setFreeBind(boolean freeBind) {
try {
((EpollDatagramChannel) channel).socket.setIpFreeBind(freeBind);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} | If {@code true} is used <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_FREEBIND</a> is enabled,
{@code false} for disable it. Default is disabled. |
static boolean isJ2OCached(String key, String value) {
return value.equals(j2o.get(key));
} | Tests if the specified key-value pair has been cached in Java-to-OpenSSL cache. |
static boolean isO2JCached(String key, String protocol, String value) {
Map<String, String> p2j = o2j.get(key);
if (p2j == null) {
return false;
} else {
return value.equals(p2j.get(protocol));
}
} | Tests if the specified key-value pair has been cached in OpenSSL-to-Java cache. |
static String toOpenSsl(String javaCipherSuite, boolean boringSSL) {
String converted = j2o.get(javaCipherSuite);
if (converted != null) {
return converted;
}
return cacheFromJava(javaCipherSuite, boringSSL);
} | Converts the specified Java cipher suite to its corresponding OpenSSL cipher suite name.
@return {@code null} if the conversion has failed |
static String toJava(String openSslCipherSuite, String protocol) {
Map<String, String> p2j = o2j.get(openSslCipherSuite);
if (p2j == null) {
p2j = cacheFromOpenSsl(openSslCipherSuite);
// This may happen if this method is queried when OpenSSL doesn't yet have a cipher setup. It will return
// "(NONE)" in this case.
if (p2j == null) {
return null;
}
}
String javaCipherSuite = p2j.get(protocol);
if (javaCipherSuite == null) {
String cipher = p2j.get("");
if (cipher == null) {
return null;
}
javaCipherSuite = protocol + '_' + cipher;
}
return javaCipherSuite;
} | Convert from OpenSSL cipher suite name convention to java cipher suite name convention.
@param openSslCipherSuite An OpenSSL cipher suite name.
@param protocol The cryptographic protocol (i.e. SSL, TLS, ...).
@return The translated cipher suite name according to java conventions. This will not be {@code null}. |
static void convertToCipherStrings(Iterable<String> cipherSuites, StringBuilder cipherBuilder,
StringBuilder cipherTLSv13Builder, boolean boringSSL) {
for (String c: cipherSuites) {
if (c == null) {
break;
}
String converted = toOpenSsl(c, boringSSL);
if (converted == null) {
converted = c;
}
if (!OpenSsl.isCipherSuiteAvailable(converted)) {
throw new IllegalArgumentException("unsupported cipher suite: " + c + '(' + converted + ')');
}
if (SslUtils.isTLSv13Cipher(converted) || SslUtils.isTLSv13Cipher(c)) {
cipherTLSv13Builder.append(converted);
cipherTLSv13Builder.append(':');
} else {
cipherBuilder.append(converted);
cipherBuilder.append(':');
}
}
if (cipherBuilder.length() == 0 && cipherTLSv13Builder.length() == 0) {
throw new IllegalArgumentException("empty cipher suites");
}
if (cipherBuilder.length() > 0) {
cipherBuilder.setLength(cipherBuilder.length() - 1);
}
if (cipherTLSv13Builder.length() > 0) {
cipherTLSv13Builder.setLength(cipherTLSv13Builder.length() - 1);
}
} | Convert the given ciphers if needed to OpenSSL format and append them to the correct {@link StringBuilder}
depending on if its a TLSv1.3 cipher or not. If this methods returns without throwing an exception its
guaranteed that at least one of the {@link StringBuilder}s contain some ciphers that can be used to configure
OpenSSL. |
@UnstableApi
public final void executeAfterEventLoopIteration(Runnable task) {
ObjectUtil.checkNotNull(task, "task");
if (isShutdown()) {
reject();
}
if (!tailTasks.offer(task)) {
reject(task);
}
if (wakesUpForTask(task)) {
wakeup(inEventLoop());
}
} | Adds a task to be run once at the end of next (or current) {@code eventloop} iteration.
@param task to be added. |
protected void interruptThread() {
Thread currentThread = thread;
if (currentThread == null) {
interrupted = true;
} else {
currentThread.interrupt();
}
} | Interrupt the current running {@link Thread}. |
protected Runnable takeTask() {
assert inEventLoop();
if (!(taskQueue instanceof BlockingQueue)) {
throw new UnsupportedOperationException();
}
BlockingQueue<Runnable> taskQueue = (BlockingQueue<Runnable>) this.taskQueue;
for (;;) {
ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
if (scheduledTask == null) {
Runnable task = null;
try {
task = taskQueue.take();
if (task == WAKEUP_TASK) {
task = null;
}
} catch (InterruptedException e) {
// Ignore
}
return task;
} else {
long delayNanos = scheduledTask.delayNanos();
Runnable task = null;
if (delayNanos > 0) {
try {
task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
// Waken up.
return null;
}
}
if (task == null) {
// We need to fetch the scheduled tasks now as otherwise there may be a chance that
// scheduled tasks are never executed if there is always one task in the taskQueue.
// This is for example true for the read task of OIO Transport
// See https://github.com/netty/netty/issues/1614
fetchFromScheduledTaskQueue();
task = taskQueue.poll();
}
if (task != null) {
return task;
}
}
}
} | Take the next {@link Runnable} from the task queue and so will block if no task is currently present.
<p>
Be aware that this method will throw an {@link UnsupportedOperationException} if the task queue, which was
created via {@link #newTaskQueue()}, does not implement {@link BlockingQueue}.
</p>
@return {@code null} if the executor thread has been interrupted or waken up. |
protected void addTask(Runnable task) {
if (task == null) {
throw new NullPointerException("task");
}
if (!offerTask(task)) {
reject(task);
}
} | Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown
before. |
protected boolean runAllTasks() {
assert inEventLoop();
boolean fetchedAll;
boolean ranAtLeastOne = false;
do {
fetchedAll = fetchFromScheduledTaskQueue();
if (runAllTasksFrom(taskQueue)) {
ranAtLeastOne = true;
}
} while (!fetchedAll); // keep on processing until we fetched all scheduled tasks.
if (ranAtLeastOne) {
lastExecutionTime = ScheduledFutureTask.nanoTime();
}
afterRunningAllTasks();
return ranAtLeastOne;
} | Poll all tasks from the task queue and run them via {@link Runnable#run()} method.
@return {@code true} if and only if at least one task was run |
protected final boolean runAllTasksFrom(Queue<Runnable> taskQueue) {
Runnable task = pollTaskFrom(taskQueue);
if (task == null) {
return false;
}
for (;;) {
safeExecute(task);
task = pollTaskFrom(taskQueue);
if (task == null) {
return true;
}
}
} | Runs all tasks from the passed {@code taskQueue}.
@param taskQueue To poll and execute all tasks.
@return {@code true} if at least one task was executed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.