code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static HostsFileEntries parse(Reader reader) throws IOException {
checkNotNull(reader, "reader");
BufferedReader buff = new BufferedReader(reader);
try {
Map<String, Inet4Address> ipv4Entries = new HashMap<String, Inet4Address>();
Map<String, Inet6Address> ipv6Entries = new HashMap<String, Inet6Address>();
String line;
while ((line = buff.readLine()) != null) {
// remove comment
int commentPosition = line.indexOf('#');
if (commentPosition != -1) {
line = line.substring(0, commentPosition);
}
// skip empty lines
line = line.trim();
if (line.isEmpty()) {
continue;
}
// split
List<String> lineParts = new ArrayList<String>();
for (String s: WHITESPACES.split(line)) {
if (!s.isEmpty()) {
lineParts.add(s);
}
}
// a valid line should be [IP, hostname, alias*]
if (lineParts.size() < 2) {
// skip invalid line
continue;
}
byte[] ipBytes = NetUtil.createByteArrayFromIpAddressString(lineParts.get(0));
if (ipBytes == null) {
// skip invalid IP
continue;
}
// loop over hostname and aliases
for (int i = 1; i < lineParts.size(); i ++) {
String hostname = lineParts.get(i);
String hostnameLower = hostname.toLowerCase(Locale.ENGLISH);
InetAddress address = InetAddress.getByAddress(hostname, ipBytes);
if (address instanceof Inet4Address) {
Inet4Address previous = ipv4Entries.put(hostnameLower, (Inet4Address) address);
if (previous != null) {
// restore, we want to keep the first entry
ipv4Entries.put(hostnameLower, previous);
}
} else {
Inet6Address previous = ipv6Entries.put(hostnameLower, (Inet6Address) address);
if (previous != null) {
// restore, we want to keep the first entry
ipv6Entries.put(hostnameLower, previous);
}
}
}
}
return ipv4Entries.isEmpty() && ipv6Entries.isEmpty() ?
HostsFileEntries.EMPTY :
new HostsFileEntries(ipv4Entries, ipv6Entries);
} finally {
try {
buff.close();
} catch (IOException e) {
logger.warn("Failed to close a reader", e);
}
}
} | Parse a reader of hosts file format.
@param reader the file to be parsed
@return a {@link HostsFileEntries}
@throws IOException file could not be read |
private static void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
if (data.isEndStream()) {
sendResponse(ctx, data.content());
} else {
// We do not send back the response to the remote-peer, so we need to release it.
data.release();
}
} | If receive a frame with end-of-stream set, send a pre-canned response. |
private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers)
throws Exception {
if (headers.isEndStream()) {
ByteBuf content = ctx.alloc().buffer();
content.writeBytes(RESPONSE_BYTES.duplicate());
ByteBufUtil.writeAscii(content, " - via HTTP/2");
sendResponse(ctx, content);
}
} | If receive a frame with end-of-stream set, send a pre-canned response. |
private static void sendResponse(ChannelHandlerContext ctx, ByteBuf payload) {
// Send a frame for the response status
Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
ctx.write(new DefaultHttp2HeadersFrame(headers));
ctx.write(new DefaultHttp2DataFrame(payload, true));
} | Sends a "Hello World" DATA frame to the client. |
final int calculateOutNetBufSize(int plaintextBytes, int numBuffers) {
// Assuming a max of one frame per component in a composite buffer.
long maxOverhead = (long) Conscrypt.maxSealOverhead(getWrappedEngine()) * numBuffers;
// TODO(nmittler): update this to use MAX_ENCRYPTED_PACKET_LENGTH instead of Integer.MAX_VALUE
return (int) min(Integer.MAX_VALUE, plaintextBytes + maxOverhead);
} | Calculates the maximum size of the encrypted output buffer required to wrap the given plaintext bytes. Assumes
as a worst case that there is one TLS record per buffer.
@param plaintextBytes the number of plaintext bytes to be wrapped.
@param numBuffers the number of buffers that the plaintext bytes are spread across.
@return the maximum size of the encrypted output buffer required for the wrap operation. |
private static int findVersion(final ByteBuf buffer) {
final int n = buffer.readableBytes();
// per spec, the version number is found in the 13th byte
if (n < 13) {
return -1;
}
int idx = buffer.readerIndex();
return match(BINARY_PREFIX, buffer, idx) ? buffer.getByte(idx + BINARY_PREFIX_LENGTH) : 1;
} | Returns the proxy protocol specification version in the buffer if the version is found.
Returns -1 if no version was found in the buffer. |
private static int findEndOfHeader(final ByteBuf buffer) {
final int n = buffer.readableBytes();
// per spec, the 15th and 16th bytes contain the address length in bytes
if (n < 16) {
return -1;
}
int offset = buffer.readerIndex() + 14;
// the total header length will be a fixed 16 byte sequence + the dynamic address information block
int totalHeaderBytes = 16 + buffer.getUnsignedShort(offset);
// ensure we actually have the full header available
if (n >= totalHeaderBytes) {
return totalHeaderBytes;
} else {
return -1;
}
} | Returns the index in the buffer of the end of header if found.
Returns -1 if no end of header was found in the buffer. |
private static int findEndOfLine(final ByteBuf buffer) {
final int n = buffer.writerIndex();
for (int i = buffer.readerIndex(); i < n; i++) {
final byte b = buffer.getByte(i);
if (b == '\r' && i < n - 1 && buffer.getByte(i + 1) == '\n') {
return i; // \r\n
}
}
return -1; // Not found.
} | Returns the index in the buffer of the end of line found.
Returns -1 if no end of line was found in the buffer. |
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
final int eoh = findEndOfHeader(buffer);
if (!discarding) {
if (eoh >= 0) {
final int length = eoh - buffer.readerIndex();
if (length > v2MaxHeaderSize) {
buffer.readerIndex(eoh);
failOverLimit(ctx, length);
return null;
}
return buffer.readSlice(length);
} else {
final int length = buffer.readableBytes();
if (length > v2MaxHeaderSize) {
discardedBytes = length;
buffer.skipBytes(length);
discarding = true;
failOverLimit(ctx, "over " + discardedBytes);
}
return null;
}
} else {
if (eoh >= 0) {
buffer.readerIndex(eoh);
discardedBytes = 0;
discarding = false;
} else {
discardedBytes = buffer.readableBytes();
buffer.skipBytes(discardedBytes);
}
return null;
}
} | Create a frame out of the {@link ByteBuf} and return it.
Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
@param ctx the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
@param buffer the {@link ByteBuf} from which to read data
@return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
be created |
private ByteBuf decodeLine(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
final int eol = findEndOfLine(buffer);
if (!discarding) {
if (eol >= 0) {
final int length = eol - buffer.readerIndex();
if (length > V1_MAX_LENGTH) {
buffer.readerIndex(eol + DELIMITER_LENGTH);
failOverLimit(ctx, length);
return null;
}
ByteBuf frame = buffer.readSlice(length);
buffer.skipBytes(DELIMITER_LENGTH);
return frame;
} else {
final int length = buffer.readableBytes();
if (length > V1_MAX_LENGTH) {
discardedBytes = length;
buffer.skipBytes(length);
discarding = true;
failOverLimit(ctx, "over " + discardedBytes);
}
return null;
}
} else {
if (eol >= 0) {
final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
buffer.readerIndex(eol + delimLength);
discardedBytes = 0;
discarding = false;
} else {
discardedBytes = buffer.readableBytes();
buffer.skipBytes(discardedBytes);
}
return null;
}
} | Create a frame out of the {@link ByteBuf} and return it.
Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
@param ctx the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
@param buffer the {@link ByteBuf} from which to read data
@return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
be created |
public static ProtocolDetectionResult<HAProxyProtocolVersion> detectProtocol(ByteBuf buffer) {
if (buffer.readableBytes() < 12) {
return ProtocolDetectionResult.needsMoreData();
}
int idx = buffer.readerIndex();
if (match(BINARY_PREFIX, buffer, idx)) {
return DETECTION_RESULT_V2;
}
if (match(TEXT_PREFIX, buffer, idx)) {
return DETECTION_RESULT_V1;
}
return ProtocolDetectionResult.invalid();
} | Returns the {@link ProtocolDetectionResult} for the given {@link ByteBuf}. |
public EpollTcpInfo tcpInfo(EpollTcpInfo info) {
try {
socket.getTcpInfo(info);
return info;
} catch (IOException e) {
throw new ChannelException(e);
}
} | Updates and returns the {@code TCP_INFO} for the current socket.
See <a href="http://linux.die.net/man/7/tcp">man 7 tcp</a>. |
void createGlobalTrafficCounter(ScheduledExecutorService executor) {
// Default
setMaxDeviation(DEFAULT_DEVIATION, DEFAULT_SLOWDOWN, DEFAULT_ACCELERATION);
if (executor == null) {
throw new IllegalArgumentException("Executor must not be null");
}
TrafficCounter tc = new GlobalChannelTrafficCounter(this, executor, "GlobalChannelTC", checkInterval);
setTrafficCounter(tc);
tc.start();
} | Create the global TrafficCounter |
public Collection<TrafficCounter> channelTrafficCounters() {
return new AbstractCollection<TrafficCounter>() {
@Override
public Iterator<TrafficCounter> iterator() {
return new Iterator<TrafficCounter>() {
final Iterator<PerChannel> iter = channelQueues.values().iterator();
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public TrafficCounter next() {
return iter.next().channelTrafficCounter;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return channelQueues.size();
}
};
} | To allow for instance doAccounting to use the TrafficCounter per channel.
@return the list of TrafficCounters that exists at the time of the call. |
int readBits(final int count) {
if (count < 0 || count > 32) {
throw new IllegalArgumentException("count: " + count + " (expected: 0-32 )");
}
int bitCount = this.bitCount;
long bitBuffer = this.bitBuffer;
if (bitCount < count) {
long readData;
int offset;
switch (in.readableBytes()) {
case 1: {
readData = in.readUnsignedByte();
offset = 8;
break;
}
case 2: {
readData = in.readUnsignedShort();
offset = 16;
break;
}
case 3: {
readData = in.readUnsignedMedium();
offset = 24;
break;
}
default: {
readData = in.readUnsignedInt();
offset = 32;
break;
}
}
bitBuffer = bitBuffer << offset | readData;
bitCount += offset;
this.bitBuffer = bitBuffer;
}
this.bitCount = bitCount -= count;
return (int) (bitBuffer >>> bitCount & (count != 32 ? (1 << count) - 1 : 0xFFFFFFFFL));
} | Reads up to 32 bits from the {@link ByteBuf}.
@param count The number of bits to read (maximum {@code 32} as a size of {@code int})
@return The bits requested, right-aligned within the integer |
boolean hasReadableBits(int count) {
if (count < 0) {
throw new IllegalArgumentException("count: " + count + " (expected value greater than 0)");
}
return bitCount >= count || (in.readableBytes() << 3 & Integer.MAX_VALUE) >= count - bitCount;
} | Checks that the specified number of bits available for reading.
@param count The number of bits to check
@return {@code true} if {@code count} bits are available for reading, otherwise {@code false} |
boolean hasReadableBytes(int count) {
if (count < 0 || count > MAX_COUNT_OF_READABLE_BYTES) {
throw new IllegalArgumentException("count: " + count
+ " (expected: 0-" + MAX_COUNT_OF_READABLE_BYTES + ')');
}
return hasReadableBits(count << 3);
} | Checks that the specified number of bytes available for reading.
@param count The number of bytes to check
@return {@code true} if {@code count} bytes are available for reading, otherwise {@code false} |
private static int parseCode(ByteBuf buffer) {
final int first = parseNumber(buffer.readByte()) * 100;
final int second = parseNumber(buffer.readByte()) * 10;
final int third = parseNumber(buffer.readByte());
return first + second + third;
} | Parses the io.netty.handler.codec.smtp code without any allocation, which is three digits. |
public String substring(int start, int end) {
int length = end - start;
if (start > pos || length > pos) {
throw new IndexOutOfBoundsException();
}
return new String(chars, start, length);
} | Create a new {@link String} from the given start to end. |
private static boolean isLineBased(final ByteBuf[] delimiters) {
if (delimiters.length != 2) {
return false;
}
ByteBuf a = delimiters[0];
ByteBuf b = delimiters[1];
if (a.capacity() < b.capacity()) {
a = delimiters[1];
b = delimiters[0];
}
return a.capacity() == 2 && b.capacity() == 1
&& a.getByte(0) == '\r' && a.getByte(1) == '\n'
&& b.getByte(0) == '\n';
} | Returns true if the delimiters are "\n" and "\r\n". |
private int getStreamId(HttpHeaders httpHeaders) throws Exception {
return httpHeaders.getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(),
connection().local().incrementAndGetNextStreamId());
} | Get the next stream id either from the {@link HttpHeaders} object or HTTP/2 codec
@param httpHeaders The HTTP/1.x headers object to look for the stream id
@return The stream id to use with this {@link HttpHeaders} object
@throws Exception If the {@code httpHeaders} object specifies an invalid stream id |
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) {
ctx.write(msg, promise);
return;
}
boolean release = true;
SimpleChannelPromiseAggregator promiseAggregator =
new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.executor());
try {
Http2ConnectionEncoder encoder = encoder();
boolean endStream = false;
if (msg instanceof HttpMessage) {
final HttpMessage httpMsg = (HttpMessage) msg;
// Provide the user the opportunity to specify the streamId
currentStreamId = getStreamId(httpMsg.headers());
// Convert and write the headers.
Http2Headers http2Headers = HttpConversionUtil.toHttp2Headers(httpMsg, validateHeaders);
endStream = msg instanceof FullHttpMessage && !((FullHttpMessage) msg).content().isReadable();
writeHeaders(ctx, encoder, currentStreamId, httpMsg.headers(), http2Headers,
endStream, promiseAggregator);
}
if (!endStream && msg instanceof HttpContent) {
boolean isLastContent = false;
HttpHeaders trailers = EmptyHttpHeaders.INSTANCE;
Http2Headers http2Trailers = EmptyHttp2Headers.INSTANCE;
if (msg instanceof LastHttpContent) {
isLastContent = true;
// Convert any trailing headers.
final LastHttpContent lastContent = (LastHttpContent) msg;
trailers = lastContent.trailingHeaders();
http2Trailers = HttpConversionUtil.toHttp2Headers(trailers, validateHeaders);
}
// Write the data
final ByteBuf content = ((HttpContent) msg).content();
endStream = isLastContent && trailers.isEmpty();
release = false;
encoder.writeData(ctx, currentStreamId, content, 0, endStream, promiseAggregator.newPromise());
if (!trailers.isEmpty()) {
// Write trailing headers.
writeHeaders(ctx, encoder, currentStreamId, trailers, http2Trailers, true, promiseAggregator);
}
}
} catch (Throwable t) {
onError(ctx, true, t);
promiseAggregator.setFailure(t);
} finally {
if (release) {
ReferenceCountUtil.release(msg);
}
promiseAggregator.doneAllocatingPromises();
}
} | Handles conversion of {@link HttpMessage} and {@link HttpContent} to HTTP/2 frames. |
public final <T> ResourceLeakDetector<T> newResourceLeakDetector(Class<T> resource) {
return newResourceLeakDetector(resource, ResourceLeakDetector.SAMPLING_INTERVAL);
} | Returns a new instance of a {@link ResourceLeakDetector} with the given resource class.
@param resource the resource class used to initialize the {@link ResourceLeakDetector}
@param <T> the type of the resource class
@return a new instance of {@link ResourceLeakDetector} |
@SuppressWarnings("deprecation")
public <T> ResourceLeakDetector<T> newResourceLeakDetector(Class<T> resource, int samplingInterval) {
return newResourceLeakDetector(resource, ResourceLeakDetector.SAMPLING_INTERVAL, Long.MAX_VALUE);
} | Returns a new instance of a {@link ResourceLeakDetector} with the given resource class.
@param resource the resource class used to initialize the {@link ResourceLeakDetector}
@param samplingInterval the interval on which sampling takes place
@param <T> the type of the resource class
@return a new instance of {@link ResourceLeakDetector} |
public static ProtocolFamily convert(InternetProtocolFamily family) {
switch (family) {
case IPv4:
return StandardProtocolFamily.INET;
case IPv6:
return StandardProtocolFamily.INET6;
default:
throw new IllegalArgumentException();
}
} | Convert the {@link InternetProtocolFamily}. This MUST only be called on jdk version >= 7. |
protected S state(S newState) {
S oldState = state;
state = newState;
return oldState;
} | Sets the current state of this decoder.
@return the old state of this decoder |
public final void setMaxCumulationBufferComponents(int maxCumulationBufferComponents) {
if (maxCumulationBufferComponents < 2) {
throw new IllegalArgumentException(
"maxCumulationBufferComponents: " + maxCumulationBufferComponents +
" (expected: >= 2)");
}
if (ctx == null) {
this.maxCumulationBufferComponents = maxCumulationBufferComponents;
} else {
throw new IllegalStateException(
"decoder properties cannot be changed once the decoder is added to a pipeline.");
}
} | Sets the maximum number of components in the cumulation buffer. If the number of
the components in the cumulation buffer exceeds this value, the components of the
cumulation buffer are consolidated into a single component, involving memory copies.
The default value of this property is {@value #DEFAULT_MAX_COMPOSITEBUFFER_COMPONENTS}
and its minimum allowed value is {@code 2}. |
protected void handleOversizedMessage(ChannelHandlerContext ctx, S oversized) throws Exception {
ctx.fireExceptionCaught(
new TooLongFrameException("content length exceeded " + maxContentLength() + " bytes."));
} | Invoked when an incoming request exceeds the maximum content length. The default behvaior is to trigger an
{@code exceptionCaught()} event with a {@link TooLongFrameException}.
@param ctx the {@link ChannelHandlerContext}
@param oversized the accumulated message up to this point, whose type is {@code S} or {@code O} |
protected NameResolver<InetAddress> newNameResolver(EventLoop eventLoop,
ChannelFactory<? extends DatagramChannel> channelFactory,
DnsServerAddressStreamProvider nameServerProvider)
throws Exception {
// once again, channelFactory and nameServerProvider are most probably set in builder already,
// but I do reassign them again to avoid corner cases with override methods
return dnsResolverBuilder.eventLoop(eventLoop)
.channelFactory(channelFactory)
.nameServerProvider(nameServerProvider)
.build();
} | Creates a new {@link NameResolver}. Override this method to create an alternative {@link NameResolver}
implementation or override the default configuration. |
protected AddressResolver<InetSocketAddress> newAddressResolver(EventLoop eventLoop,
NameResolver<InetAddress> resolver)
throws Exception {
return new InetSocketAddressResolver(eventLoop, resolver);
} | Creates a new {@link AddressResolver}. Override this method to create an alternative {@link AddressResolver}
implementation or override the default configuration. |
private void readHttpDataChunkByChunk() {
try {
while (decoder.hasNext()) {
InterfaceHttpData data = decoder.next();
if (data != null) {
// check if current HttpData is a FileUpload and previously set as partial
if (partialContent == data) {
logger.info(" 100% (FinalSize: " + partialContent.length() + ")");
partialContent = null;
}
// new value
writeHttpData(data);
}
}
// Check partial decoding for a FileUpload
InterfaceHttpData data = decoder.currentPartialHttpData();
if (data != null) {
StringBuilder builder = new StringBuilder();
if (partialContent == null) {
partialContent = (HttpData) data;
if (partialContent instanceof FileUpload) {
builder.append("Start FileUpload: ")
.append(((FileUpload) partialContent).getFilename()).append(" ");
} else {
builder.append("Start Attribute: ")
.append(partialContent.getName()).append(" ");
}
builder.append("(DefinedSize: ").append(partialContent.definedLength()).append(")");
}
if (partialContent.definedLength() > 0) {
builder.append(" ").append(partialContent.length() * 100 / partialContent.definedLength())
.append("% ");
logger.info(builder.toString());
} else {
builder.append(" ").append(partialContent.length()).append(" ");
logger.info(builder.toString());
}
}
} catch (EndOfDataDecoderException e1) {
// end
responseContent.append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n");
}
} | Example of reading request by chunk and getting values from chunk to chunk |
public final boolean remove(K key) {
P pool = map.remove(checkNotNull(key, "key"));
if (pool != null) {
pool.close();
return true;
}
return false;
} | Remove the {@link ChannelPool} from this {@link AbstractChannelPoolMap}. Returns {@code true} if removed,
{@code false} otherwise.
Please note that {@code null} keys are not allowed. |
@SuppressWarnings("unchecked")
public static <T> AttributeKey<T> valueOf(String name) {
return (AttributeKey<T>) pool.valueOf(name);
} | Returns the singleton instance of the {@link AttributeKey} which has the specified {@code name}. |
@SuppressWarnings("unchecked")
public static <T> AttributeKey<T> newInstance(String name) {
return (AttributeKey<T>) pool.newInstance(name);
} | Creates a new {@link AttributeKey} for the given {@code name} or fail with an
{@link IllegalArgumentException} if a {@link AttributeKey} for the given {@code name} exists. |
private ChannelFuture writeContinuationFrames(ChannelHandlerContext ctx, int streamId,
ByteBuf headerBlock, int padding, SimpleChannelPromiseAggregator promiseAggregator) {
Http2Flags flags = new Http2Flags().paddingPresent(padding > 0);
int maxFragmentLength = maxFrameSize - padding;
// TODO: same padding is applied to all frames, is this desired?
if (maxFragmentLength <= 0) {
return promiseAggregator.setFailure(new IllegalArgumentException(
"Padding [" + padding + "] is too large for max frame size [" + maxFrameSize + "]"));
}
if (headerBlock.isReadable()) {
// The frame header (and padding) only changes on the last frame, so allocate it once and re-use
int fragmentReadableBytes = min(headerBlock.readableBytes(), maxFragmentLength);
int payloadLength = fragmentReadableBytes + padding;
ByteBuf buf = ctx.alloc().buffer(CONTINUATION_FRAME_HEADER_LENGTH);
writeFrameHeaderInternal(buf, payloadLength, CONTINUATION, flags, streamId);
writePaddingLength(buf, padding);
do {
fragmentReadableBytes = min(headerBlock.readableBytes(), maxFragmentLength);
ByteBuf fragment = headerBlock.readRetainedSlice(fragmentReadableBytes);
payloadLength = fragmentReadableBytes + padding;
if (headerBlock.isReadable()) {
ctx.write(buf.retain(), promiseAggregator.newPromise());
} else {
// The frame header is different for the last frame, so re-allocate and release the old buffer
flags = flags.endOfHeaders(true);
buf.release();
buf = ctx.alloc().buffer(CONTINUATION_FRAME_HEADER_LENGTH);
writeFrameHeaderInternal(buf, payloadLength, CONTINUATION, flags, streamId);
writePaddingLength(buf, padding);
ctx.write(buf, promiseAggregator.newPromise());
}
ctx.write(fragment, promiseAggregator.newPromise());
// Write out the padding, if any.
if (paddingBytes(padding) > 0) {
ctx.write(ZERO_BUFFER.slice(0, paddingBytes(padding)), promiseAggregator.newPromise());
}
} while (headerBlock.isReadable());
}
return promiseAggregator;
} | Writes as many continuation frames as needed until {@code padding} and {@code headerBlock} are consumed. |
private static boolean isLast(HttpMessage httpMessage) {
if (httpMessage instanceof FullHttpMessage) {
FullHttpMessage fullMessage = (FullHttpMessage) httpMessage;
if (fullMessage.trailingHeaders().isEmpty() && !fullMessage.content().isReadable()) {
return true;
}
}
return false;
} | Checks if the given HTTP message should be considered as a last SPDY frame.
@param httpMessage check this HTTP message
@return whether the given HTTP message should generate a <em>last</em> SPDY frame. |
public static URI ocspUri(X509Certificate certificate) throws IOException {
byte[] value = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
if (value == null) {
return null;
}
ASN1Primitive authorityInfoAccess = X509ExtensionUtil.fromExtensionValue(value);
if (!(authorityInfoAccess instanceof DLSequence)) {
return null;
}
DLSequence aiaSequence = (DLSequence) authorityInfoAccess;
DERTaggedObject taggedObject = findObject(aiaSequence, OCSP_RESPONDER_OID, DERTaggedObject.class);
if (taggedObject == null) {
return null;
}
if (taggedObject.getTagNo() != BERTags.OBJECT_IDENTIFIER) {
return null;
}
byte[] encoded = taggedObject.getEncoded();
int length = (int) encoded[1] & 0xFF;
String uri = new String(encoded, 2, length, CharsetUtil.UTF_8);
return URI.create(uri);
} | Returns the OCSP responder {@link URI} or {@code null} if it doesn't have one. |
public static OCSPResp request(URI uri, OCSPReq request, long timeout, TimeUnit unit) throws IOException {
byte[] encoded = request.getEncoded();
URL url = uri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setConnectTimeout((int) unit.toMillis(timeout));
connection.setReadTimeout((int) unit.toMillis(timeout));
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("host", uri.getHost());
connection.setRequestProperty("content-type", OCSP_REQUEST_TYPE);
connection.setRequestProperty("accept", OCSP_RESPONSE_TYPE);
connection.setRequestProperty("content-length", String.valueOf(encoded.length));
OutputStream out = connection.getOutputStream();
try {
out.write(encoded);
out.flush();
InputStream in = connection.getInputStream();
try {
int code = connection.getResponseCode();
if (code != HttpsURLConnection.HTTP_OK) {
throw new IOException("Unexpected status-code=" + code);
}
String contentType = connection.getContentType();
if (!contentType.equalsIgnoreCase(OCSP_RESPONSE_TYPE)) {
throw new IOException("Unexpected content-type=" + contentType);
}
int contentLength = connection.getContentLength();
if (contentLength == -1) {
// Probably a terrible idea!
contentLength = Integer.MAX_VALUE;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[8192];
int length = -1;
while ((length = in.read(buffer)) != -1) {
baos.write(buffer, 0, length);
if (baos.size() >= contentLength) {
break;
}
}
} finally {
baos.close();
}
return new OCSPResp(baos.toByteArray());
} finally {
in.close();
}
} finally {
out.close();
}
} finally {
connection.disconnect();
}
} | TODO: This is a very crude and non-scalable HTTP client to fetch the OCSP response from the
CA's OCSP responder server. It's meant to demonstrate the basic building blocks on how to
interact with the responder server and you should consider using Netty's HTTP client instead. |
public void register(final SelectableChannel ch, final int interestOps, final NioTask<?> task) {
if (ch == null) {
throw new NullPointerException("ch");
}
if (interestOps == 0) {
throw new IllegalArgumentException("interestOps must be non-zero.");
}
if ((interestOps & ~ch.validOps()) != 0) {
throw new IllegalArgumentException(
"invalid interestOps: " + interestOps + "(validOps: " + ch.validOps() + ')');
}
if (task == null) {
throw new NullPointerException("task");
}
if (isShutdown()) {
throw new IllegalStateException("event loop shut down");
}
if (inEventLoop()) {
register0(ch, interestOps, task);
} else {
try {
// Offload to the EventLoop as otherwise java.nio.channels.spi.AbstractSelectableChannel.register
// may block for a long time while trying to obtain an internal lock that may be hold while selecting.
submit(new Runnable() {
@Override
public void run() {
register0(ch, interestOps, task);
}
}).sync();
} catch (InterruptedException ignore) {
// Even if interrupted we did schedule it so just mark the Thread as interrupted.
Thread.currentThread().interrupt();
}
}
} | Registers an arbitrary {@link SelectableChannel}, not necessarily created by Netty, to the {@link Selector}
of this event loop. Once the specified {@link SelectableChannel} is registered, the specified {@code task} will
be executed by this event loop when the {@link SelectableChannel} is ready. |
@Deprecated
@Override
public WebSocketFrame readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
} | @deprecated Use {@link #readChunk(ByteBufAllocator)}.
Fetches a chunked data from the stream. Once this method returns the last chunk
and thus the stream has reached at its end, any subsequent {@link #isEndOfInput()}
call must return {@code true}.
@param ctx {@link ChannelHandlerContext} context of channelHandler
@return {@link WebSocketFrame} contain chunk of data |
@Override
public WebSocketFrame readChunk(ByteBufAllocator allocator) throws Exception {
ByteBuf buf = input.readChunk(allocator);
if (buf == null) {
return null;
}
return new ContinuationWebSocketFrame(input.isEndOfInput(), rsv, buf);
} | Fetches a chunked data from the stream. Once this method returns the last chunk
and thus the stream has reached at its end, any subsequent {@link #isEndOfInput()}
call must return {@code true}.
@param allocator {@link ByteBufAllocator}
@return {@link WebSocketFrame} contain chunk of data |
@Override
protected final AddressResolver<InetSocketAddress> newAddressResolver(EventLoop eventLoop,
NameResolver<InetAddress> resolver)
throws Exception {
return new RoundRobinInetAddressResolver(eventLoop, resolver).asAddressResolver();
} | We need to override this method, not
{@link #newNameResolver(EventLoop, ChannelFactory, DnsServerAddressStreamProvider)},
because we need to eliminate possible caching of {@link io.netty.resolver.NameResolver#resolve}
by {@link InflightNameResolver} created in
{@link #newResolver(EventLoop, ChannelFactory, DnsServerAddressStreamProvider)}. |
protected Object decode(
@SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {
if (in.readableBytes() < frameLength) {
return null;
} else {
return in.readRetainedSlice(frameLength);
}
} | Create a frame out of the {@link ByteBuf} and return it.
@param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
@param in the {@link ByteBuf} from which to read data
@return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
be created. |
Map<Integer, StreamState> activeStreams() {
Map<Integer, StreamState> streams = new TreeMap<Integer, StreamState>(streamComparator);
streams.putAll(activeStreams);
return streams;
} | Stream-IDs should be iterated in priority order |
boolean hasReceivedReply(int streamId) {
StreamState state = activeStreams.get(streamId);
return state != null && state.hasReceivedReply();
} | /*
hasReceivedReply and receivedReply are only called from channelRead()
no need to synchronize access to the StreamState |
public Set<String> subprotocols() {
Set<String> ret = new LinkedHashSet<String>();
Collections.addAll(ret, subprotocols);
return ret;
} | Returns the CSV of supported sub protocols |
public ChannelFuture handshake(Channel channel, FullHttpRequest req) {
return handshake(channel, req, null, channel.newPromise());
} | Performs the opening handshake. When call this method you <strong>MUST NOT</strong> retain the
{@link FullHttpRequest} which is passed in.
@param channel
Channel
@param req
HTTP Request
@return future
The {@link ChannelFuture} which is notified once the opening handshake completes |
public final ChannelFuture handshake(Channel channel, FullHttpRequest req,
HttpHeaders responseHeaders, final ChannelPromise promise) {
if (logger.isDebugEnabled()) {
logger.debug("{} WebSocket version {} server handshake", channel, version());
}
FullHttpResponse response = newHandshakeResponse(req, responseHeaders);
ChannelPipeline p = channel.pipeline();
if (p.get(HttpObjectAggregator.class) != null) {
p.remove(HttpObjectAggregator.class);
}
if (p.get(HttpContentCompressor.class) != null) {
p.remove(HttpContentCompressor.class);
}
ChannelHandlerContext ctx = p.context(HttpRequestDecoder.class);
final String encoderName;
if (ctx == null) {
// this means the user use a HttpServerCodec
ctx = p.context(HttpServerCodec.class);
if (ctx == null) {
promise.setFailure(
new IllegalStateException("No HttpDecoder and no HttpServerCodec in the pipeline"));
return promise;
}
p.addBefore(ctx.name(), "wsdecoder", newWebsocketDecoder());
p.addBefore(ctx.name(), "wsencoder", newWebSocketEncoder());
encoderName = ctx.name();
} else {
p.replace(ctx.name(), "wsdecoder", newWebsocketDecoder());
encoderName = p.context(HttpResponseEncoder.class).name();
p.addBefore(encoderName, "wsencoder", newWebSocketEncoder());
}
channel.writeAndFlush(response).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ChannelPipeline p = future.channel().pipeline();
p.remove(encoderName);
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
}
});
return promise;
} | Performs the opening handshake
When call this method you <strong>MUST NOT</strong> retain the {@link FullHttpRequest} which is passed in.
@param channel
Channel
@param req
HTTP Request
@param responseHeaders
Extra headers to add to the handshake response or {@code null} if no extra headers should be added
@param promise
the {@link ChannelPromise} to be notified when the opening handshake is done
@return future
the {@link ChannelFuture} which is notified when the opening handshake is done |
public ChannelFuture handshake(Channel channel, HttpRequest req) {
return handshake(channel, req, null, channel.newPromise());
} | Performs the opening handshake. When call this method you <strong>MUST NOT</strong> retain the
{@link FullHttpRequest} which is passed in.
@param channel
Channel
@param req
HTTP Request
@return future
The {@link ChannelFuture} which is notified once the opening handshake completes |
public final ChannelFuture handshake(final Channel channel, HttpRequest req,
final HttpHeaders responseHeaders, final ChannelPromise promise) {
if (req instanceof FullHttpRequest) {
return handshake(channel, (FullHttpRequest) req, responseHeaders, promise);
}
if (logger.isDebugEnabled()) {
logger.debug("{} WebSocket version {} server handshake", channel, version());
}
ChannelPipeline p = channel.pipeline();
ChannelHandlerContext ctx = p.context(HttpRequestDecoder.class);
if (ctx == null) {
// this means the user use a HttpServerCodec
ctx = p.context(HttpServerCodec.class);
if (ctx == null) {
promise.setFailure(
new IllegalStateException("No HttpDecoder and no HttpServerCodec in the pipeline"));
return promise;
}
}
// Add aggregator and ensure we feed the HttpRequest so it is aggregated. A limit o 8192 should be more then
// enough for the websockets handshake payload.
//
// TODO: Make handshake work without HttpObjectAggregator at all.
String aggregatorName = "httpAggregator";
p.addAfter(ctx.name(), aggregatorName, new HttpObjectAggregator(8192));
p.addAfter(aggregatorName, "handshaker", new SimpleChannelInboundHandler<FullHttpRequest>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
// Remove ourself and do the actual handshake
ctx.pipeline().remove(this);
handshake(channel, msg, responseHeaders, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// Remove ourself and fail the handshake promise.
ctx.pipeline().remove(this);
promise.tryFailure(cause);
ctx.fireExceptionCaught(cause);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// Fail promise if Channel was closed
promise.tryFailure(CLOSED_CHANNEL_EXCEPTION);
ctx.fireChannelInactive();
}
});
try {
ctx.fireChannelRead(ReferenceCountUtil.retain(req));
} catch (Throwable cause) {
promise.setFailure(cause);
}
return promise;
} | Performs the opening handshake
When call this method you <strong>MUST NOT</strong> retain the {@link HttpRequest} which is passed in.
@param channel
Channel
@param req
HTTP Request
@param responseHeaders
Extra headers to add to the handshake response or {@code null} if no extra headers should be added
@param promise
the {@link ChannelPromise} to be notified when the opening handshake is done
@return future
the {@link ChannelFuture} which is notified when the opening handshake is done |
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) {
if (channel == null) {
throw new NullPointerException("channel");
}
return channel.writeAndFlush(frame, promise).addListener(ChannelFutureListener.CLOSE);
} | Performs the closing handshake
@param channel
Channel
@param frame
Closing Frame that was received
@param promise
the {@link ChannelPromise} to be notified when the closing handshake is done |
protected String selectSubprotocol(String requestedSubprotocols) {
if (requestedSubprotocols == null || subprotocols.length == 0) {
return null;
}
String[] requestedSubprotocolArray = requestedSubprotocols.split(",");
for (String p: requestedSubprotocolArray) {
String requestedSubprotocol = p.trim();
for (String supportedSubprotocol: subprotocols) {
if (SUB_PROTOCOL_WILDCARD.equals(supportedSubprotocol)
|| requestedSubprotocol.equals(supportedSubprotocol)) {
selectedSubprotocol = requestedSubprotocol;
return requestedSubprotocol;
}
}
}
// No match found
return null;
} | Selects the first matching supported sub protocol
@param requestedSubprotocols
CSV of protocols to be supported. e.g. "chat, superchat"
@return First matching supported sub protocol. Null if not found. |
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) {
if (msgs instanceof CodecOutputList) {
fireChannelRead(ctx, (CodecOutputList) msgs, numElements);
} else {
for (int i = 0; i < numElements; i++) {
ctx.fireChannelRead(msgs.get(i));
}
}
} | Get {@code numElements} out of the {@link List} and forward these through the pipeline. |
static void fireChannelRead(ChannelHandlerContext ctx, CodecOutputList msgs, int numElements) {
for (int i = 0; i < numElements; i ++) {
ctx.fireChannelRead(msgs.getUnsafe(i));
}
} | Get {@code numElements} out of the {@link CodecOutputList} and forward these through the pipeline. |
void channelInputClosed(ChannelHandlerContext ctx, List<Object> out) throws Exception {
if (cumulation != null) {
callDecode(ctx, cumulation, out);
decodeLast(ctx, cumulation, out);
} else {
decodeLast(ctx, Unpooled.EMPTY_BUFFER, out);
}
} | Called when the input of the channel was closed which may be because it changed to inactive or because of
{@link ChannelInputShutdownEvent}. |
protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
try {
while (in.isReadable()) {
int outSize = out.size();
if (outSize > 0) {
fireChannelRead(ctx, out, outSize);
out.clear();
// Check if this handler was removed before continuing with decoding.
// If it was removed, it is not safe to continue to operate on the buffer.
//
// See:
// - https://github.com/netty/netty/issues/4635
if (ctx.isRemoved()) {
break;
}
outSize = 0;
}
int oldInputLength = in.readableBytes();
decodeRemovalReentryProtection(ctx, in, out);
// Check if this handler was removed before continuing the loop.
// If it was removed, it is not safe to continue to operate on the buffer.
//
// See https://github.com/netty/netty/issues/1664
if (ctx.isRemoved()) {
break;
}
if (outSize == out.size()) {
if (oldInputLength == in.readableBytes()) {
break;
} else {
continue;
}
}
if (oldInputLength == in.readableBytes()) {
throw new DecoderException(
StringUtil.simpleClassName(getClass()) +
".decode() did not read anything but decoded a message.");
}
if (isSingleDecode()) {
break;
}
}
} catch (DecoderException e) {
throw e;
} catch (Exception cause) {
throw new DecoderException(cause);
}
} | Called once data should be decoded from the given {@link ByteBuf}. This method will call
{@link #decode(ChannelHandlerContext, ByteBuf, List)} as long as decoding should take place.
@param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
@param in the {@link ByteBuf} from which to read data
@param out the {@link List} to which decoded messages should be added |
final void decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
throws Exception {
decodeState = STATE_CALLING_CHILD_DECODE;
try {
decode(ctx, in, out);
} finally {
boolean removePending = decodeState == STATE_HANDLER_REMOVED_PENDING;
decodeState = STATE_INIT;
if (removePending) {
handlerRemoved(ctx);
}
}
} | Decode the from one {@link ByteBuf} to an other. This method will be called till either the input
{@link ByteBuf} has nothing to read when return from this method or till nothing was read from the input
{@link ByteBuf}.
@param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
@param in the {@link ByteBuf} from which to read data
@param out the {@link List} to which decoded messages should be added
@throws Exception is thrown if an error occurs |
@SuppressWarnings("deprecation")
static JdkApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config, boolean isServer) {
if (config == null) {
return JdkDefaultApplicationProtocolNegotiator.INSTANCE;
}
switch(config.protocol()) {
case NONE:
return JdkDefaultApplicationProtocolNegotiator.INSTANCE;
case ALPN:
if (isServer) {
switch(config.selectorFailureBehavior()) {
case FATAL_ALERT:
return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols());
case NO_ADVERTISE:
return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectorFailureBehavior()).append(" failure behavior").toString());
}
} else {
switch(config.selectedListenerFailureBehavior()) {
case ACCEPT:
return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols());
case FATAL_ALERT:
return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString());
}
}
case NPN:
if (isServer) {
switch(config.selectedListenerFailureBehavior()) {
case ACCEPT:
return new JdkNpnApplicationProtocolNegotiator(false, config.supportedProtocols());
case FATAL_ALERT:
return new JdkNpnApplicationProtocolNegotiator(true, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString());
}
} else {
switch(config.selectorFailureBehavior()) {
case FATAL_ALERT:
return new JdkNpnApplicationProtocolNegotiator(true, config.supportedProtocols());
case NO_ADVERTISE:
return new JdkNpnApplicationProtocolNegotiator(false, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectorFailureBehavior()).append(" failure behavior").toString());
}
}
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.protocol()).append(" protocol").toString());
}
} | Translate a {@link ApplicationProtocolConfig} object to a {@link JdkApplicationProtocolNegotiator} object.
@param config The configuration which defines the translation
@param isServer {@code true} if a server {@code false} otherwise.
@return The results of the translation |
@Deprecated
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile,
String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf)
throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeySpecException, InvalidAlgorithmParameterException, IOException,
CertificateException, KeyException, UnrecoverableKeyException {
return buildKeyManagerFactory(toX509Certificates(certChainFile), keyAlgorithm,
toPrivateKey(keyFile, keyPassword), keyPassword, kmf);
} | Build a {@link KeyManagerFactory} based upon a key algorithm, key file, key file password,
and a certificate chain.
@param certChainFile a X.509 certificate chain file in PEM format
@param keyAlgorithm the standard name of the requested algorithm. See the Java Secure Socket Extension
Reference Guide for information about standard algorithm names.
@param keyFile a PKCS#8 private key file in PEM format
@param keyPassword the password of the {@code keyFile}.
{@code null} if it's not password-protected.
@param kmf The existing {@link KeyManagerFactory} that will be used if not {@code null}
@return A {@link KeyManagerFactory} based upon a key algorithm, key file, key file password,
and a certificate chain.
@deprecated will be removed. |
public static String hexDump(ByteBuf buffer) {
return hexDump(buffer, buffer.readerIndex(), buffer.readableBytes());
} | Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
of the specified buffer's readable bytes. |
public static String hexDump(ByteBuf buffer, int fromIndex, int length) {
return HexUtil.hexDump(buffer, fromIndex, length);
} | Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
of the specified buffer's sub-region. |
public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) {
return StringUtil.decodeHexDump(hexDump, fromIndex, length);
} | Decodes part of a string generated by {@link #hexDump(byte[])} |
public static int indexOf(ByteBuf needle, ByteBuf haystack) {
// TODO: maybe use Boyer Moore for efficiency.
int attempts = haystack.readableBytes() - needle.readableBytes() + 1;
for (int i = 0; i < attempts; i++) {
if (equals(needle, needle.readerIndex(),
haystack, haystack.readerIndex() + i,
needle.readableBytes())) {
return haystack.readerIndex() + i;
}
}
return -1;
} | Returns the reader index of needle in haystack, or -1 if needle is not in haystack. |
public static int compare(ByteBuf bufferA, ByteBuf bufferB) {
final int aLen = bufferA.readableBytes();
final int bLen = bufferB.readableBytes();
final int minLength = Math.min(aLen, bLen);
final int uintCount = minLength >>> 2;
final int byteCount = minLength & 3;
int aIndex = bufferA.readerIndex();
int bIndex = bufferB.readerIndex();
if (uintCount > 0) {
boolean bufferAIsBigEndian = bufferA.order() == ByteOrder.BIG_ENDIAN;
final long res;
int uintCountIncrement = uintCount << 2;
if (bufferA.order() == bufferB.order()) {
res = bufferAIsBigEndian ? compareUintBigEndian(bufferA, bufferB, aIndex, bIndex, uintCountIncrement) :
compareUintLittleEndian(bufferA, bufferB, aIndex, bIndex, uintCountIncrement);
} else {
res = bufferAIsBigEndian ? compareUintBigEndianA(bufferA, bufferB, aIndex, bIndex, uintCountIncrement) :
compareUintBigEndianB(bufferA, bufferB, aIndex, bIndex, uintCountIncrement);
}
if (res != 0) {
// Ensure we not overflow when cast
return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, res));
}
aIndex += uintCountIncrement;
bIndex += uintCountIncrement;
}
for (int aEnd = aIndex + byteCount; aIndex < aEnd; ++aIndex, ++bIndex) {
int comp = bufferA.getUnsignedByte(aIndex) - bufferB.getUnsignedByte(bIndex);
if (comp != 0) {
return comp;
}
}
return aLen - bLen;
} | Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}.
This method is useful when implementing a new buffer type. |
public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) {
if (fromIndex <= toIndex) {
return firstIndexOf(buffer, fromIndex, toIndex, value);
} else {
return lastIndexOf(buffer, fromIndex, toIndex, value);
}
} | The default implementation of {@link ByteBuf#indexOf(int, int, byte)}.
This method is useful when implementing a new buffer type. |
@SuppressWarnings("deprecation")
public static ByteBuf writeShortBE(ByteBuf buf, int shortValue) {
return buf.order() == ByteOrder.BIG_ENDIAN? buf.writeShort(shortValue) : buf.writeShortLE(shortValue);
} | Writes a big-endian 16-bit short integer to the buffer. |
@SuppressWarnings("deprecation")
public static ByteBuf setShortBE(ByteBuf buf, int index, int shortValue) {
return buf.order() == ByteOrder.BIG_ENDIAN? buf.setShort(index, shortValue) : buf.setShortLE(index, shortValue);
} | Sets a big-endian 16-bit short integer to the buffer. |
@SuppressWarnings("deprecation")
public static ByteBuf writeMediumBE(ByteBuf buf, int mediumValue) {
return buf.order() == ByteOrder.BIG_ENDIAN? buf.writeMedium(mediumValue) : buf.writeMediumLE(mediumValue);
} | Writes a big-endian 24-bit medium integer to the buffer. |
public static ByteBuf readBytes(ByteBufAllocator alloc, ByteBuf buffer, int length) {
boolean release = true;
ByteBuf dst = alloc.buffer(length);
try {
buffer.readBytes(dst);
release = false;
return dst;
} finally {
if (release) {
dst.release();
}
}
} | Read the given amount of bytes into a new {@link ByteBuf} that is allocated from the {@link ByteBufAllocator}. |
public static ByteBuf writeUtf8(ByteBufAllocator alloc, CharSequence seq) {
// UTF-8 uses max. 3 bytes per char, so calculate the worst case.
ByteBuf buf = alloc.buffer(utf8MaxBytes(seq));
writeUtf8(buf, seq);
return buf;
} | Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write
it to a {@link ByteBuf} allocated with {@code alloc}.
@param alloc The allocator used to allocate a new {@link ByteBuf}.
@param seq The characters to write into a buffer.
@return The {@link ByteBuf} which contains the <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> encoded
result. |
public static int writeUtf8(ByteBuf buf, CharSequence seq) {
return reserveAndWriteUtf8(buf, seq, utf8MaxBytes(seq));
} | Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write
it to a {@link ByteBuf}.
<p>
It behaves like {@link #reserveAndWriteUtf8(ByteBuf, CharSequence, int)} with {@code reserveBytes}
computed by {@link #utf8MaxBytes(CharSequence)}.<br>
This method returns the actual number of bytes written. |
public static int reserveAndWriteUtf8(ByteBuf buf, CharSequence seq, int reserveBytes) {
for (;;) {
if (buf instanceof WrappedCompositeByteBuf) {
// WrappedCompositeByteBuf is a sub-class of AbstractByteBuf so it needs special handling.
buf = buf.unwrap();
} else if (buf instanceof AbstractByteBuf) {
AbstractByteBuf byteBuf = (AbstractByteBuf) buf;
byteBuf.ensureWritable0(reserveBytes);
int written = writeUtf8(byteBuf, byteBuf.writerIndex, seq, seq.length());
byteBuf.writerIndex += written;
return written;
} else if (buf instanceof WrappedByteBuf) {
// Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path.
buf = buf.unwrap();
} else {
byte[] bytes = seq.toString().getBytes(CharsetUtil.UTF_8);
buf.writeBytes(bytes);
return bytes.length;
}
}
} | Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and write
it into {@code reserveBytes} of a {@link ByteBuf}.
<p>
The {@code reserveBytes} must be computed (ie eagerly using {@link #utf8MaxBytes(CharSequence)}
or exactly with {@link #utf8Bytes(CharSequence)}) to ensure this method to not fail: for performance reasons
the index checks will be performed using just {@code reserveBytes}.<br>
This method returns the actual number of bytes written. |
static int writeUtf8(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len) {
int oldWriterIndex = writerIndex;
// We can use the _set methods as these not need to do any index checks and reference checks.
// This is possible as we called ensureWritable(...) before.
for (int i = 0; i < len; i++) {
char c = seq.charAt(i);
if (c < 0x80) {
buffer._setByte(writerIndex++, (byte) c);
} else if (c < 0x800) {
buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6)));
buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f)));
} else if (isSurrogate(c)) {
if (!Character.isHighSurrogate(c)) {
buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN);
continue;
}
final char c2;
try {
// Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid
// duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will
// re-throw a more informative exception describing the problem.
c2 = seq.charAt(++i);
} catch (IndexOutOfBoundsException ignored) {
buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN);
break;
}
// Extra method to allow inlining the rest of writeUtf8 which is the most likely code path.
writerIndex = writeUtf8Surrogate(buffer, writerIndex, c, c2);
} else {
buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12)));
buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f)));
buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f)));
}
}
return writerIndex - oldWriterIndex;
} | Fast-Path implementation |
public static int utf8Bytes(final CharSequence seq) {
if (seq instanceof AsciiString) {
return seq.length();
}
int seqLength = seq.length();
int i = 0;
// ASCII fast path
while (i < seqLength && seq.charAt(i) < 0x80) {
++i;
}
// !ASCII is packed in a separate method to let the ASCII case be smaller
return i < seqLength ? i + utf8Bytes(seq, i, seqLength) : i;
} | Returns the exact bytes length of UTF8 character sequence.
<p>
This method is producing the exact length according to {@link #writeUtf8(ByteBuf, CharSequence)}. |
public static ByteBuf writeAscii(ByteBufAllocator alloc, CharSequence seq) {
// ASCII uses 1 byte per char
ByteBuf buf = alloc.buffer(seq.length());
writeAscii(buf, seq);
return buf;
} | Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> and write
it to a {@link ByteBuf} allocated with {@code alloc}.
@param alloc The allocator used to allocate a new {@link ByteBuf}.
@param seq The characters to write into a buffer.
@return The {@link ByteBuf} which contains the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> encoded
result. |
public static int writeAscii(ByteBuf buf, CharSequence seq) {
// ASCII uses 1 byte per char
final int len = seq.length();
if (seq instanceof AsciiString) {
AsciiString asciiString = (AsciiString) seq;
buf.writeBytes(asciiString.array(), asciiString.arrayOffset(), len);
} else {
for (;;) {
if (buf instanceof WrappedCompositeByteBuf) {
// WrappedCompositeByteBuf is a sub-class of AbstractByteBuf so it needs special handling.
buf = buf.unwrap();
} else if (buf instanceof AbstractByteBuf) {
AbstractByteBuf byteBuf = (AbstractByteBuf) buf;
byteBuf.ensureWritable0(len);
int written = writeAscii(byteBuf, byteBuf.writerIndex, seq, len);
byteBuf.writerIndex += written;
return written;
} else if (buf instanceof WrappedByteBuf) {
// Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path.
buf = buf.unwrap();
} else {
byte[] bytes = seq.toString().getBytes(CharsetUtil.US_ASCII);
buf.writeBytes(bytes);
return bytes.length;
}
}
}
return len;
} | Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> and write it
to a {@link ByteBuf}.
This method returns the actual number of bytes written. |
static int writeAscii(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len) {
// We can use the _set methods as these not need to do any index checks and reference checks.
// This is possible as we called ensureWritable(...) before.
for (int i = 0; i < len; i++) {
buffer._setByte(writerIndex++, AsciiString.c2b(seq.charAt(i)));
}
return len;
} | Fast-Path implementation |
public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset, int extraCapacity) {
return encodeString0(alloc, false, src, charset, extraCapacity);
} | Encode the given {@link CharBuffer} using the given {@link Charset} into a new {@link ByteBuf} which
is allocated via the {@link ByteBufAllocator}.
@param alloc The {@link ByteBufAllocator} to allocate {@link ByteBuf}.
@param src The {@link CharBuffer} to encode.
@param charset The specified {@link Charset}.
@param extraCapacity the extra capacity to alloc except the space for decoding. |
public static ByteBuf threadLocalDirectBuffer() {
if (THREAD_LOCAL_BUFFER_SIZE <= 0) {
return null;
}
if (PlatformDependent.hasUnsafe()) {
return ThreadLocalUnsafeDirectByteBuf.newInstance();
} else {
return ThreadLocalDirectByteBuf.newInstance();
}
} | Returns a cached thread-local direct buffer, if available.
@return a cached thread-local direct buffer, if available. {@code null} otherwise. |
public static byte[] getBytes(ByteBuf buf, int start, int length) {
return getBytes(buf, start, length, true);
} | Create a copy of the underlying storage from {@code buf} into a byte array.
The copy will start at {@code start} and copy {@code length} bytes. |
public static byte[] getBytes(ByteBuf buf, int start, int length, boolean copy) {
int capacity = buf.capacity();
if (isOutOfBounds(start, length, capacity)) {
throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= start + length(" + length
+ ") <= " + "buf.capacity(" + capacity + ')');
}
if (buf.hasArray()) {
if (copy || start != 0 || length != capacity) {
int baseOffset = buf.arrayOffset() + start;
return Arrays.copyOfRange(buf.array(), baseOffset, baseOffset + length);
} else {
return buf.array();
}
}
byte[] v = PlatformDependent.allocateUninitializedArray(length);
buf.getBytes(start, v);
return v;
} | Return an array of the underlying storage from {@code buf} into a byte array.
The copy will start at {@code start} and copy {@code length} bytes.
If {@code copy} is true a copy will be made of the memory.
If {@code copy} is false the underlying storage will be shared, if possible. |
public static void copy(AsciiString src, ByteBuf dst) {
copy(src, 0, dst, src.length());
} | Copies the all content of {@code src} to a {@link ByteBuf} using {@link ByteBuf#writeBytes(byte[], int, int)}.
@param src the source string to copy
@param dst the destination buffer |
public static void copy(AsciiString src, int srcIdx, ByteBuf dst, int dstIdx, int length) {
if (isOutOfBounds(srcIdx, length, src.length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length("
+ length + ") <= srcLen(" + src.length() + ')');
}
checkNotNull(dst, "dst").setBytes(dstIdx, src.array(), srcIdx + src.arrayOffset(), length);
} | Copies the content of {@code src} to a {@link ByteBuf} using {@link ByteBuf#setBytes(int, byte[], int, int)}.
Unlike the {@link #copy(AsciiString, ByteBuf)} and {@link #copy(AsciiString, int, ByteBuf, int)} methods,
this method do not increase a {@code writerIndex} of {@code dst} buffer.
@param src the source string to copy
@param srcIdx the starting offset of characters to copy
@param dst the destination buffer
@param dstIdx the starting offset in the destination buffer
@param length the number of characters to copy |
public static String prettyHexDump(ByteBuf buffer) {
return prettyHexDump(buffer, buffer.readerIndex(), buffer.readableBytes());
} | Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans. |
public static String prettyHexDump(ByteBuf buffer, int offset, int length) {
return HexUtil.prettyHexDump(buffer, offset, length);
} | Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans,
starting at the given {@code offset} using the given {@code length}. |
public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf) {
appendPrettyHexDump(dump, buf, buf.readerIndex(), buf.readableBytes());
} | Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified
{@link StringBuilder} that is easy to read by humans. |
public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length) {
HexUtil.appendPrettyHexDump(dump, buf, offset, length);
} | Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified
{@link StringBuilder} that is easy to read by humans, starting at the given {@code offset} using
the given {@code length}. |
public static boolean isText(ByteBuf buf, Charset charset) {
return isText(buf, buf.readerIndex(), buf.readableBytes(), charset);
} | Returns {@code true} if the given {@link ByteBuf} is valid text using the given {@link Charset},
otherwise return {@code false}.
@param buf The given {@link ByteBuf}.
@param charset The specified {@link Charset}. |
public static boolean isText(ByteBuf buf, int index, int length, Charset charset) {
checkNotNull(buf, "buf");
checkNotNull(charset, "charset");
final int maxIndex = buf.readerIndex() + buf.readableBytes();
if (index < 0 || length < 0 || index > maxIndex - length) {
throw new IndexOutOfBoundsException("index: " + index + " length: " + length);
}
if (charset.equals(CharsetUtil.UTF_8)) {
return isUtf8(buf, index, length);
} else if (charset.equals(CharsetUtil.US_ASCII)) {
return isAscii(buf, index, length);
} else {
CharsetDecoder decoder = CharsetUtil.decoder(charset, CodingErrorAction.REPORT, CodingErrorAction.REPORT);
try {
if (buf.nioBufferCount() == 1) {
decoder.decode(buf.nioBuffer(index, length));
} else {
ByteBuf heapBuffer = buf.alloc().heapBuffer(length);
try {
heapBuffer.writeBytes(buf, index, length);
decoder.decode(heapBuffer.internalNioBuffer(heapBuffer.readerIndex(), length));
} finally {
heapBuffer.release();
}
}
return true;
} catch (CharacterCodingException ignore) {
return false;
}
}
} | Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid
text using the given {@link Charset}, otherwise return {@code false}.
@param buf The given {@link ByteBuf}.
@param index The start index of the specified buffer.
@param length The length of the specified buffer.
@param charset The specified {@link Charset}.
@throws IndexOutOfBoundsException if {@code index} + {@code length} is greater than {@code buf.readableBytes} |
private static boolean isAscii(ByteBuf buf, int index, int length) {
return buf.forEachByte(index, length, FIND_NON_ASCII) == -1;
} | Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid
ASCII text, otherwise return {@code false}.
@param buf The given {@link ByteBuf}.
@param index The start index of the specified buffer.
@param length The length of the specified buffer. |
private static boolean isUtf8(ByteBuf buf, int index, int length) {
final int endIndex = index + length;
while (index < endIndex) {
byte b1 = buf.getByte(index++);
byte b2, b3, b4;
if ((b1 & 0x80) == 0) {
// 1 byte
continue;
}
if ((b1 & 0xE0) == 0xC0) {
// 2 bytes
//
// Bit/Byte pattern
// 110xxxxx 10xxxxxx
// C2..DF 80..BF
if (index >= endIndex) { // no enough bytes
return false;
}
b2 = buf.getByte(index++);
if ((b2 & 0xC0) != 0x80) { // 2nd byte not starts with 10
return false;
}
if ((b1 & 0xFF) < 0xC2) { // out of lower bound
return false;
}
} else if ((b1 & 0xF0) == 0xE0) {
// 3 bytes
//
// Bit/Byte pattern
// 1110xxxx 10xxxxxx 10xxxxxx
// E0 A0..BF 80..BF
// E1..EC 80..BF 80..BF
// ED 80..9F 80..BF
// E1..EF 80..BF 80..BF
if (index > endIndex - 2) { // no enough bytes
return false;
}
b2 = buf.getByte(index++);
b3 = buf.getByte(index++);
if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) { // 2nd or 3rd bytes not start with 10
return false;
}
if ((b1 & 0x0F) == 0x00 && (b2 & 0xFF) < 0xA0) { // out of lower bound
return false;
}
if ((b1 & 0x0F) == 0x0D && (b2 & 0xFF) > 0x9F) { // out of upper bound
return false;
}
} else if ((b1 & 0xF8) == 0xF0) {
// 4 bytes
//
// Bit/Byte pattern
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// F0 90..BF 80..BF 80..BF
// F1..F3 80..BF 80..BF 80..BF
// F4 80..8F 80..BF 80..BF
if (index > endIndex - 3) { // no enough bytes
return false;
}
b2 = buf.getByte(index++);
b3 = buf.getByte(index++);
b4 = buf.getByte(index++);
if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80 || (b4 & 0xC0) != 0x80) {
// 2nd, 3rd or 4th bytes not start with 10
return false;
}
if ((b1 & 0xFF) > 0xF4 // b1 invalid
|| (b1 & 0xFF) == 0xF0 && (b2 & 0xFF) < 0x90 // b2 out of lower bound
|| (b1 & 0xFF) == 0xF4 && (b2 & 0xFF) > 0x8F) { // b2 out of upper bound
return false;
}
} else {
return false;
}
}
return true;
} | Returns {@code true} if the specified {@link ByteBuf} starting at {@code index} with {@code length} is valid
UTF8 text, otherwise return {@code false}.
@param buf The given {@link ByteBuf}.
@param index The start index of the specified buffer.
@param length The length of the specified buffer.
@see
<a href=http://www.ietf.org/rfc/rfc3629.txt>UTF-8 Definition</a>
<pre>
1. Bytes format of UTF-8
The table below summarizes the format of these different octet types.
The letter x indicates bits available for encoding bits of the character number.
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
</pre>
<pre>
2. Syntax of UTF-8 Byte Sequences
UTF8-octets = *( UTF8-char )
UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
UTF8-1 = %x00-7F
UTF8-2 = %xC2-DF UTF8-tail
UTF8-3 = %xE0 %xA0-BF UTF8-tail /
%xE1-EC 2( UTF8-tail ) /
%xED %x80-9F UTF8-tail /
%xEE-EF 2( UTF8-tail )
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) /
%xF1-F3 3( UTF8-tail ) /
%xF4 %x80-8F 2( UTF8-tail )
UTF8-tail = %x80-BF
</pre> |
static void readBytes(ByteBufAllocator allocator, ByteBuffer buffer, int position, int length, OutputStream out)
throws IOException {
if (buffer.hasArray()) {
out.write(buffer.array(), position + buffer.arrayOffset(), length);
} else {
int chunkLen = Math.min(length, WRITE_CHUNK_SIZE);
buffer.clear().position(position);
if (length <= MAX_TL_ARRAY_LEN || !allocator.isDirectBufferPooled()) {
getBytes(buffer, threadLocalTempArray(chunkLen), 0, chunkLen, out, length);
} else {
// if direct buffers are pooled chances are good that heap buffers are pooled as well.
ByteBuf tmpBuf = allocator.heapBuffer(chunkLen);
try {
byte[] tmp = tmpBuf.array();
int offset = tmpBuf.arrayOffset();
getBytes(buffer, tmp, offset, chunkLen, out, length);
} finally {
tmpBuf.release();
}
}
}
} | Read bytes from the given {@link ByteBuffer} into the given {@link OutputStream} using the {@code position} and
{@code length}. The position and limit of the given {@link ByteBuffer} may be adjusted. |
public static void tryCancel(Promise<?> p, InternalLogger logger) {
if (!p.cancel(false) && logger != null) {
Throwable err = p.cause();
if (err == null) {
logger.warn("Failed to cancel promise because it has succeeded already: {}", p);
} else {
logger.warn(
"Failed to cancel promise because it has failed already: {}, unnotified cause:",
p, err);
}
}
} | Try to cancel the {@link Promise} and log if {@code logger} is not {@code null} in case this fails. |
public static <V> void trySuccess(Promise<? super V> p, V result, InternalLogger logger) {
if (!p.trySuccess(result) && logger != null) {
Throwable err = p.cause();
if (err == null) {
logger.warn("Failed to mark a promise as success because it has succeeded already: {}", p);
} else {
logger.warn(
"Failed to mark a promise as success because it has failed already: {}, unnotified cause:",
p, err);
}
}
} | Try to mark the {@link Promise} as success and log if {@code logger} is not {@code null} in case this fails. |
public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) {
if (!p.tryFailure(cause) && logger != null) {
Throwable err = p.cause();
if (err == null) {
logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause);
} else {
logger.warn(
"Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}",
p, ThrowableUtil.stackTraceToString(err), cause);
}
}
} | Try to mark the {@link Promise} as failure and log if {@code logger} is not {@code null} in case this fails. |
@Override
@Deprecated
public int getMaxMessagesPerRead() {
try {
MaxMessagesRecvByteBufAllocator allocator = getRecvByteBufAllocator();
return allocator.maxMessagesPerRead();
} catch (ClassCastException e) {
throw new IllegalStateException("getRecvByteBufAllocator() must return an object of type " +
"MaxMessagesRecvByteBufAllocator", e);
}
} | {@inheritDoc}
<p>
@throws IllegalStateException if {@link #getRecvByteBufAllocator()} does not return an object of type
{@link MaxMessagesRecvByteBufAllocator}. |
@Override
@Deprecated
public ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) {
try {
MaxMessagesRecvByteBufAllocator allocator = getRecvByteBufAllocator();
allocator.maxMessagesPerRead(maxMessagesPerRead);
return this;
} catch (ClassCastException e) {
throw new IllegalStateException("getRecvByteBufAllocator() must return an object of type " +
"MaxMessagesRecvByteBufAllocator", e);
}
} | {@inheritDoc}
<p>
@throws IllegalStateException if {@link #getRecvByteBufAllocator()} does not return an object of type
{@link MaxMessagesRecvByteBufAllocator}. |
private void setRecvByteBufAllocator(RecvByteBufAllocator allocator, ChannelMetadata metadata) {
if (allocator instanceof MaxMessagesRecvByteBufAllocator) {
((MaxMessagesRecvByteBufAllocator) allocator).maxMessagesPerRead(metadata.defaultMaxMessagesPerRead());
} else if (allocator == null) {
throw new NullPointerException("allocator");
}
setRecvByteBufAllocator(allocator);
} | Set the {@link RecvByteBufAllocator} which is used for the channel to allocate receive buffers.
@param allocator the allocator to set.
@param metadata Used to set the {@link ChannelMetadata#defaultMaxMessagesPerRead()} if {@code allocator}
is of type {@link MaxMessagesRecvByteBufAllocator}. |
public static HttpVersion valueOf(String text) {
if (text == null) {
throw new NullPointerException("text");
}
text = text.trim();
if (text.isEmpty()) {
throw new IllegalArgumentException("text is empty (possibly HTTP/0.9)");
}
// Try to match without convert to uppercase first as this is what 99% of all clients
// will send anyway. Also there is a change to the RFC to make it clear that it is
// expected to be case-sensitive
//
// See:
// * http://trac.tools.ietf.org/wg/httpbis/trac/ticket/1
// * http://trac.tools.ietf.org/wg/httpbis/trac/wiki
//
HttpVersion version = version0(text);
if (version == null) {
version = new HttpVersion(text, true);
}
return version;
} | Returns an existing or new {@link HttpVersion} instance which matches to
the specified protocol version string. If the specified {@code text} is
equal to {@code "HTTP/1.0"}, {@link #HTTP_1_0} will be returned. If the
specified {@code text} is equal to {@code "HTTP/1.1"}, {@link #HTTP_1_1}
will be returned. Otherwise, a new {@link HttpVersion} instance will be
returned. |
private void destroy() {
if (queue != null) {
if (!queue.isEmpty()) {
logger.trace("Non-empty queue: {}", queue);
if (releaseMessages) {
Object msg;
while ((msg = queue.poll()) != null) {
ReferenceCountUtil.safeRelease(msg);
}
}
}
queue.recycle();
queue = null;
}
} | Releases all messages and destroys the {@link Queue}. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.