code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
static int findNonWhitespace(String sb, int offset) {
int result;
for (result = offset; result < sb.length(); result ++) {
if (!Character.isWhitespace(sb.charAt(result))) {
break;
}
}
return result;
} | Find the first non whitespace
@return the rank of the first non whitespace |
static int findEndOfString(String sb) {
int result;
for (result = sb.length(); result > 0; result --) {
if (!Character.isWhitespace(sb.charAt(result - 1))) {
break;
}
}
return result;
} | Find the end of String
@return the rank of the end of string |
public boolean setSessionIdContext(byte[] sidCtx) {
Lock writerLock = context.ctxLock.writeLock();
writerLock.lock();
try {
return SSLContext.setSessionIdContext(context.ctx, sidCtx);
} finally {
writerLock.unlock();
}
} | Set the context within which session be reused (server side only)
See <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_session_id_context.html">
man SSL_CTX_set_session_id_context</a>
@param sidCtx can be any kind of binary data, it is therefore possible to use e.g. the name
of the application and/or the hostname and/or service name
@return {@code true} if success, {@code false} otherwise. |
public static void register(Object object, Runnable cleanupTask) {
AutomaticCleanerReference reference = new AutomaticCleanerReference(object,
ObjectUtil.checkNotNull(cleanupTask, "cleanupTask"));
// Its important to add the reference to the LIVE_SET before we access CLEANER_RUNNING to ensure correct
// behavior in multi-threaded environments.
LIVE_SET.add(reference);
// Check if there is already a cleaner running.
if (CLEANER_RUNNING.compareAndSet(false, true)) {
final Thread cleanupThread = new FastThreadLocalThread(CLEANER_TASK);
cleanupThread.setPriority(Thread.MIN_PRIORITY);
// Set to null to ensure we not create classloader leaks by holding a strong reference to the inherited
// classloader.
// See:
// - https://github.com/netty/netty/issues/7290
// - https://bugs.openjdk.java.net/browse/JDK-7008595
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
cleanupThread.setContextClassLoader(null);
return null;
}
});
cleanupThread.setName(CLEANER_THREAD_NAME);
// Mark this as a daemon thread to ensure that we the JVM can exit if this is the only thread that is
// running.
cleanupThread.setDaemon(true);
cleanupThread.start();
}
} | Register the given {@link Object} for which the {@link Runnable} will be executed once there are no references
to the object anymore.
This should only be used if there are no other ways to execute some cleanup once the Object is not reachable
anymore because it is not a cheap way to handle the cleanup. |
protected final void clearReadPending() {
if (isRegistered()) {
EventLoop eventLoop = eventLoop();
if (eventLoop.inEventLoop()) {
readPending = false;
} else {
eventLoop.execute(clearReadPendingRunnable);
}
} else {
// Best effort if we are not registered yet clear readPending. This happens during channel initialization.
readPending = false;
}
} | Set read pending to {@code false}. |
private static void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
Http2FrameStream stream = data.stream();
if (data.isEndStream()) {
sendResponse(ctx, stream, data.content());
} else {
// We do not send back the response to the remote-peer, so we need to release it.
data.release();
}
// Update the flowcontroller
ctx.write(new DefaultHttp2WindowUpdateFrame(data.initialFlowControlledBytes()).stream(stream));
} | If receive a frame with end-of-stream set, send a pre-canned response. |
public static SpdyStreamStatus valueOf(int code) {
if (code == 0) {
throw new IllegalArgumentException(
"0 is not a valid status code for a RST_STREAM");
}
switch (code) {
case 1:
return PROTOCOL_ERROR;
case 2:
return INVALID_STREAM;
case 3:
return REFUSED_STREAM;
case 4:
return UNSUPPORTED_VERSION;
case 5:
return CANCEL;
case 6:
return INTERNAL_ERROR;
case 7:
return FLOW_CONTROL_ERROR;
case 8:
return STREAM_IN_USE;
case 9:
return STREAM_ALREADY_CLOSED;
case 10:
return INVALID_CREDENTIALS;
case 11:
return FRAME_TOO_LARGE;
}
return new SpdyStreamStatus(code, "UNKNOWN (" + code + ')');
} | Returns the {@link SpdyStreamStatus} represented by the specified code.
If the specified code is a defined SPDY status code, a cached instance
will be returned. Otherwise, a new instance will be returned. |
protected EmbeddedChannel newContentDecompressor(final ChannelHandlerContext ctx, CharSequence contentEncoding)
throws Http2Exception {
if (GZIP.contentEqualsIgnoreCase(contentEncoding) || X_GZIP.contentEqualsIgnoreCase(contentEncoding)) {
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
}
if (DEFLATE.contentEqualsIgnoreCase(contentEncoding) || X_DEFLATE.contentEqualsIgnoreCase(contentEncoding)) {
final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE;
// To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(wrapper));
}
// 'identity' or unsupported
return null;
} | Returns a new {@link EmbeddedChannel} that decodes the HTTP2 message content encoded in the specified
{@code contentEncoding}.
@param contentEncoding the value of the {@code content-encoding} header
@return a new {@link ByteToMessageDecoder} if the specified encoding is supported. {@code null} otherwise
(alternatively, you can throw a {@link Http2Exception} to block unknown encoding).
@throws Http2Exception If the specified encoding is not not supported and warrants an exception |
private void initDecompressor(ChannelHandlerContext ctx, int streamId, Http2Headers headers, boolean endOfStream)
throws Http2Exception {
final Http2Stream stream = connection.stream(streamId);
if (stream == null) {
return;
}
Http2Decompressor decompressor = decompressor(stream);
if (decompressor == null && !endOfStream) {
// Determine the content encoding.
CharSequence contentEncoding = headers.get(CONTENT_ENCODING);
if (contentEncoding == null) {
contentEncoding = IDENTITY;
}
final EmbeddedChannel channel = newContentDecompressor(ctx, contentEncoding);
if (channel != null) {
decompressor = new Http2Decompressor(channel);
stream.setProperty(propertyKey, decompressor);
// Decode the content and remove or replace the existing headers
// so that the message looks like a decoded message.
CharSequence targetContentEncoding = getTargetContentEncoding(contentEncoding);
if (IDENTITY.contentEqualsIgnoreCase(targetContentEncoding)) {
headers.remove(CONTENT_ENCODING);
} else {
headers.set(CONTENT_ENCODING, targetContentEncoding);
}
}
}
if (decompressor != null) {
// The content length will be for the compressed data. Since we will decompress the data
// this content-length will not be correct. Instead of queuing messages or delaying sending
// header frames...just remove the content-length header
headers.remove(CONTENT_LENGTH);
// The first time that we initialize a decompressor, decorate the local flow controller to
// properly convert consumed bytes.
if (!flowControllerInitialized) {
flowControllerInitialized = true;
connection.local().flowController(new ConsumedBytesConverter(connection.local().flowController()));
}
}
} | Checks if a new decompressor object is needed for the stream identified by {@code streamId}.
This method will modify the {@code content-encoding} header contained in {@code headers}.
@param ctx The context
@param streamId The identifier for the headers inside {@code headers}
@param headers Object representing headers which have been read
@param endOfStream Indicates if the stream has ended
@throws Http2Exception If the {@code content-encoding} is not supported |
private static ByteBuf nextReadableBuf(EmbeddedChannel decompressor) {
for (;;) {
final ByteBuf buf = decompressor.readInbound();
if (buf == null) {
return null;
}
if (!buf.isReadable()) {
buf.release();
continue;
}
return buf;
}
} | Read the next decompressed {@link ByteBuf} from the {@link EmbeddedChannel}
or {@code null} if one does not exist.
@param decompressor The channel to read from
@return The next decoded {@link ByteBuf} from the {@link EmbeddedChannel} or {@code null} if one does not exist |
public static HttpResponseStatus valueOf(int code) {
HttpResponseStatus status = valueOf0(code);
return status != null ? status : new HttpResponseStatus(code);
} | Returns the {@link HttpResponseStatus} represented by the specified code.
If the specified code is a standard HTTP status code, a cached instance
will be returned. Otherwise, a new instance will be returned. |
public static HttpResponseStatus valueOf(int code, String reasonPhrase) {
HttpResponseStatus responseStatus = valueOf0(code);
return responseStatus != null && responseStatus.reasonPhrase().contentEquals(reasonPhrase) ? responseStatus :
new HttpResponseStatus(code, reasonPhrase);
} | Returns the {@link HttpResponseStatus} represented by the specified {@code code} and {@code reasonPhrase}.
If the specified code is a standard HTTP status {@code code} and {@code reasonPhrase}, a cached instance
will be returned. Otherwise, a new instance will be returned.
@param code The response code value.
@param reasonPhrase The response code reason phrase.
@return the {@link HttpResponseStatus} represented by the specified {@code code} and {@code reasonPhrase}. |
public static HttpResponseStatus parseLine(CharSequence line) {
return (line instanceof AsciiString) ? parseLine((AsciiString) line) : parseLine(line.toString());
} | Parses the specified HTTP status line into a {@link HttpResponseStatus}. The expected formats of the line are:
<ul>
<li>{@code statusCode} (e.g. 200)</li>
<li>{@code statusCode} {@code reasonPhrase} (e.g. 404 Not Found)</li>
</ul>
@throws IllegalArgumentException if the specified status line is malformed |
public static HttpResponseStatus parseLine(String line) {
try {
int space = line.indexOf(' ');
return space == -1 ? valueOf(parseInt(line)) :
valueOf(parseInt(line.substring(0, space)), line.substring(space + 1));
} catch (Exception e) {
throw new IllegalArgumentException("malformed status line: " + line, e);
}
} | Parses the specified HTTP status line into a {@link HttpResponseStatus}. The expected formats of the line are:
<ul>
<li>{@code statusCode} (e.g. 200)</li>
<li>{@code statusCode} {@code reasonPhrase} (e.g. 404 Not Found)</li>
</ul>
@throws IllegalArgumentException if the specified status line is malformed |
public static HttpResponseStatus parseLine(AsciiString line) {
try {
int space = line.forEachByte(FIND_ASCII_SPACE);
return space == -1 ? valueOf(line.parseInt()) : valueOf(line.parseInt(0, space), line.toString(space + 1));
} catch (Exception e) {
throw new IllegalArgumentException("malformed status line: " + line, e);
}
} | Parses the specified HTTP status line into a {@link HttpResponseStatus}. The expected formats of the line are:
<ul>
<li>{@code statusCode} (e.g. 200)</li>
<li>{@code statusCode} {@code reasonPhrase} (e.g. 404 Not Found)</li>
</ul>
@throws IllegalArgumentException if the specified status line is malformed |
public HttpStatusClass codeClass() {
HttpStatusClass type = this.codeClass;
if (type == null) {
this.codeClass = type = HttpStatusClass.valueOf(code);
}
return type;
} | Returns the class of this {@link HttpResponseStatus} |
private static boolean isSelfDefinedMessageLength(HttpResponse response) {
return isContentLengthSet(response) || isTransferEncodingChunked(response) || isMultipart(response) ||
isInformational(response) || response.status().code() == HttpResponseStatus.NO_CONTENT.code();
} | Keep-alive only works if the client can detect when the message has ended without relying on the connection being
closed.
<p>
<ul>
<li>See <a href="https://tools.ietf.org/html/rfc7230#section-6.3"/></li>
<li>See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.2"/></li>
<li>See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3"/></li>
</ul>
@param response The HttpResponse to check
@return true if the response has a self defined message length. |
public void start() {
switch (WORKER_STATE_UPDATER.get(this)) {
case WORKER_STATE_INIT:
if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) {
workerThread.start();
}
break;
case WORKER_STATE_STARTED:
break;
case WORKER_STATE_SHUTDOWN:
throw new IllegalStateException("cannot be started once stopped");
default:
throw new Error("Invalid WorkerState");
}
// Wait until the startTime is initialized by the worker.
while (startTime == 0) {
try {
startTimeInitialized.await();
} catch (InterruptedException ignore) {
// Ignore - it will be ready very soon.
}
}
} | Starts the background thread explicitly. The background thread will
start automatically on demand even if you did not call this method.
@throws IllegalStateException if this timer has been
{@linkplain #stop() stopped} already |
private static String readString(String fieldName, ByteBuf in) {
int length = in.bytesBefore(MAX_FIELD_LENGTH + 1, (byte) 0);
if (length < 0) {
throw new DecoderException("field '" + fieldName + "' longer than " + MAX_FIELD_LENGTH + " chars");
}
String value = in.readSlice(length).toString(CharsetUtil.US_ASCII);
in.skipBytes(1); // Skip the NUL.
return value;
} | Reads a variable-length NUL-terminated string as defined in SOCKS4. |
@SuppressWarnings("UnusedParameters")
protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
return buffer.retainedSlice(index, length);
} | Override this method if you want to filter the json objects/arrays that get passed through the pipeline. |
long allocate() {
if (elemSize == 0) {
return toHandle(0);
}
if (numAvail == 0 || !doNotDestroy) {
return -1;
}
final int bitmapIdx = getNextAvail();
int q = bitmapIdx >>> 6;
int r = bitmapIdx & 63;
assert (bitmap[q] >>> r & 1) == 0;
bitmap[q] |= 1L << r;
if (-- numAvail == 0) {
removeFromPool();
}
return toHandle(bitmapIdx);
} | Returns the bitmap index of the subpage allocation. |
public static String get(final String key, String def) {
if (key == null) {
throw new NullPointerException("key");
}
if (key.isEmpty()) {
throw new IllegalArgumentException("key must not be empty.");
}
String value = null;
try {
if (System.getSecurityManager() == null) {
value = System.getProperty(key);
} else {
value = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(key);
}
});
}
} catch (SecurityException e) {
logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e);
}
if (value == null) {
return def;
}
return value;
} | Returns the value of the Java system property with the specified
{@code key}, while falling back to the specified default value if
the property access fails.
@return the property value.
{@code def} if there's no such property or if an access to the
specified property is not allowed. |
public static boolean getBoolean(String key, boolean def) {
String value = get(key);
if (value == null) {
return def;
}
value = value.trim().toLowerCase();
if (value.isEmpty()) {
return def;
}
if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
return true;
}
if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
return false;
}
logger.warn(
"Unable to parse the boolean system property '{}':{} - using the default value: {}",
key, value, def
);
return def;
} | Returns the value of the Java system property with the specified
{@code key}, while falling back to the specified default value if
the property access fails.
@return the property value.
{@code def} if there's no such property or if an access to the
specified property is not allowed. |
public static int getInt(String key, int def) {
String value = get(key);
if (value == null) {
return def;
}
value = value.trim();
try {
return Integer.parseInt(value);
} catch (Exception e) {
// Ignore
}
logger.warn(
"Unable to parse the integer system property '{}':{} - using the default value: {}",
key, value, def
);
return def;
} | Returns the value of the Java system property with the specified
{@code key}, while falling back to the specified default value if
the property access fails.
@return the property value.
{@code def} if there's no such property or if an access to the
specified property is not allowed. |
public static long getLong(String key, long def) {
String value = get(key);
if (value == null) {
return def;
}
value = value.trim();
try {
return Long.parseLong(value);
} catch (Exception e) {
// Ignore
}
logger.warn(
"Unable to parse the long integer system property '{}':{} - using the default value: {}",
key, value, def
);
return def;
} | Returns the value of the Java system property with the specified
{@code key}, while falling back to the specified default value if
the property access fails.
@return the property value.
{@code def} if there's no such property or if an access to the
specified property is not allowed. |
@Override
public void channelHandlerContext(ChannelHandlerContext ctx) throws Http2Exception {
this.ctx = checkNotNull(ctx, "ctx");
// Writing the pending bytes will not check writability change and instead a writability change notification
// to be provided by an explicit call.
channelWritabilityChanged();
// Don't worry about cleaning up queued frames here if ctx is null. It is expected that all streams will be
// closed and the queue cleanup will occur when the stream state transitions occur.
// If any frames have been queued up, we should send them now that we have a channel context.
if (isChannelWritable()) {
writePendingBytes();
}
} | {@inheritDoc}
<p>
Any queued {@link FlowControlled} objects will be sent. |
private static int compressionLevel(int blockSize) {
if (blockSize < MIN_BLOCK_SIZE || blockSize > MAX_BLOCK_SIZE) {
throw new IllegalArgumentException(String.format(
"blockSize: %d (expected: %d-%d)", blockSize, MIN_BLOCK_SIZE, MAX_BLOCK_SIZE));
}
int compressionLevel = 32 - Integer.numberOfLeadingZeros(blockSize - 1); // ceil of log2
compressionLevel = Math.max(0, compressionLevel - COMPRESSION_LEVEL_BASE);
return compressionLevel;
} | Calculates compression level on the basis of block size. |
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
if (finished) {
if (!out.isWritable(in.readableBytes())) {
// out should be EMPTY_BUFFER because we should have allocated enough space above in allocateBuffer.
throw ENCODE_FINSHED_EXCEPTION;
}
out.writeBytes(in);
return;
}
final ByteBuf buffer = this.buffer;
int length;
while ((length = in.readableBytes()) > 0) {
final int nextChunkSize = Math.min(length, buffer.writableBytes());
in.readBytes(buffer, nextChunkSize);
if (!buffer.isWritable()) {
flushBufferedData(out);
}
}
} | {@inheritDoc}
Encodes the input buffer into {@link #blockSize} chunks in the output buffer. Data is only compressed and
written once we hit the {@link #blockSize}; else, it is copied into the backing {@link #buffer} to await
more data. |
public ChannelFuture close(final ChannelPromise promise) {
ChannelHandlerContext ctx = ctx();
EventExecutor executor = ctx.executor();
if (executor.inEventLoop()) {
return finishEncode(ctx, promise);
} else {
executor.execute(new Runnable() {
@Override
public void run() {
ChannelFuture f = finishEncode(ctx(), promise);
f.addListener(new ChannelPromiseNotifier(promise));
}
});
return promise;
}
} | Close this {@link Lz4FrameEncoder} and so finish the encoding.
The given {@link ChannelFuture} will be notified once the operation
completes and will also be returned. |
public KQueueDatagramChannelConfig setReusePort(boolean reusePort) {
try {
((KQueueDatagramChannel) 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 KQueueSocketChannel}s to the same port and so accept connections with multiple threads.
Be aware this method needs be called before {@link KQueueDatagramChannel#bind(java.net.SocketAddress)} to have
any affect. |
public static HttpResponseStatus valueOf(int code) {
switch (code) {
case 250: return LOW_STORAGE_SPACE;
case 302: return MOVED_TEMPORARILY;
case 451: return PARAMETER_NOT_UNDERSTOOD;
case 452: return CONFERENCE_NOT_FOUND;
case 453: return NOT_ENOUGH_BANDWIDTH;
case 454: return SESSION_NOT_FOUND;
case 455: return METHOD_NOT_VALID;
case 456: return HEADER_FIELD_NOT_VALID;
case 457: return INVALID_RANGE;
case 458: return PARAMETER_IS_READONLY;
case 459: return AGGREGATE_OPERATION_NOT_ALLOWED;
case 460: return ONLY_AGGREGATE_OPERATION_ALLOWED;
case 461: return UNSUPPORTED_TRANSPORT;
case 462: return DESTINATION_UNREACHABLE;
case 463: return KEY_MANAGEMENT_FAILURE;
case 505: return RTSP_VERSION_NOT_SUPPORTED;
case 551: return OPTION_NOT_SUPPORTED;
default: return HttpResponseStatus.valueOf(code);
}
} | Returns the {@link HttpResponseStatus} represented by the specified code.
If the specified code is a standard RTSP getStatus code, a cached instance
will be returned. Otherwise, a new instance will be returned. |
private void allocateNormal(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
if (q050.allocate(buf, reqCapacity, normCapacity) || q025.allocate(buf, reqCapacity, normCapacity) ||
q000.allocate(buf, reqCapacity, normCapacity) || qInit.allocate(buf, reqCapacity, normCapacity) ||
q075.allocate(buf, reqCapacity, normCapacity)) {
return;
}
// Add a new chunk.
PoolChunk<T> c = newChunk(pageSize, maxOrder, pageShifts, chunkSize);
boolean success = c.allocate(buf, reqCapacity, normCapacity);
assert success;
qInit.add(c);
} | Method must be called inside synchronized(this) { ... } block |
protected void writeTimedOut(ChannelHandlerContext ctx) throws Exception {
if (!closed) {
ctx.fireExceptionCaught(WriteTimeoutException.INSTANCE);
ctx.close();
closed = true;
}
} | Is called when a write timeout was detected |
void realloc(boolean throwIfFail) {
// Double the capacity while it is "sufficiently small", and otherwise increase by 50%.
int newLength = capacity <= 65536 ? capacity << 1 : capacity + capacity >> 1;
try {
ByteBuffer buffer = Buffer.allocateDirectWithNativeOrder(calculateBufferCapacity(newLength));
// Copy over the old content of the memory and reset the position as we always act on the buffer as if
// the position was never increased.
memory.position(0).limit(size);
buffer.put(memory);
buffer.position(0);
Buffer.free(memory);
memory = buffer;
memoryAddress = Buffer.memoryAddress(buffer);
} catch (OutOfMemoryError e) {
if (throwIfFail) {
OutOfMemoryError error = new OutOfMemoryError(
"unable to allocate " + newLength + " new bytes! Existing capacity is: " + capacity);
error.initCause(e);
throw error;
}
}
} | Increase the storage of this {@link KQueueEventArray}. |
protected final ByteBuf newDirectBuffer(Object holder, ByteBuf buf) {
final int readableBytes = buf.readableBytes();
if (readableBytes == 0) {
ReferenceCountUtil.release(holder);
return Unpooled.EMPTY_BUFFER;
}
final ByteBufAllocator alloc = alloc();
if (alloc.isDirectBufferPooled()) {
return newDirectBuffer0(holder, buf, alloc, readableBytes);
}
final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer();
if (directBuf == null) {
return newDirectBuffer0(holder, buf, alloc, readableBytes);
}
directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
ReferenceCountUtil.safeRelease(holder);
return directBuf;
} | Returns an off-heap copy of the specified {@link ByteBuf}, and releases the specified holder.
The caller must ensure that the holder releases the original {@link ByteBuf} when the holder is released by
this method. |
protected final int doReadBytes(ByteBuf byteBuf) throws Exception {
int writerIndex = byteBuf.writerIndex();
int localReadAmount;
unsafe().recvBufAllocHandle().attemptedBytesRead(byteBuf.writableBytes());
if (byteBuf.hasMemoryAddress()) {
localReadAmount = socket.readAddress(byteBuf.memoryAddress(), writerIndex, byteBuf.capacity());
} else {
ByteBuffer buf = byteBuf.internalNioBuffer(writerIndex, byteBuf.writableBytes());
localReadAmount = socket.read(buf, buf.position(), buf.limit());
}
if (localReadAmount > 0) {
byteBuf.writerIndex(writerIndex + localReadAmount);
}
return localReadAmount;
} | Read bytes into the given {@link ByteBuf} and return the amount. |
protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
if (localAddress instanceof InetSocketAddress) {
checkResolvable((InetSocketAddress) localAddress);
}
InetSocketAddress remoteSocketAddr = remoteAddress instanceof InetSocketAddress
? (InetSocketAddress) remoteAddress : null;
if (remoteSocketAddr != null) {
checkResolvable(remoteSocketAddr);
}
if (remote != null) {
// Check if already connected before trying to connect. This is needed as connect(...) will not return -1
// and set errno to EISCONN if a previous connect(...) attempt was setting errno to EINPROGRESS and finished
// later.
throw new AlreadyConnectedException();
}
if (localAddress != null) {
socket.bind(localAddress);
}
boolean connected = doConnect0(remoteAddress);
if (connected) {
remote = remoteSocketAddr == null?
remoteAddress : computeRemoteAddr(remoteSocketAddr, socket.remoteAddress());
}
// We always need to set the localAddress even if not connected yet as the bind already took place.
//
// See https://github.com/netty/netty/issues/3463
local = socket.localAddress();
return connected;
} | Connect to the remote peer |
static String base64(byte[] data) {
ByteBuf encodedData = Unpooled.wrappedBuffer(data);
ByteBuf encoded = Base64.encode(encodedData);
String encodedString = encoded.toString(CharsetUtil.UTF_8);
encoded.release();
return encodedString;
} | Performs base64 encoding on the specified data
@param data The data to encode
@return An encoded string containing the data |
static int randomNumber(int minimum, int maximum) {
assert minimum < maximum;
double fraction = PlatformDependent.threadLocalRandom().nextDouble();
// the idea here is that nextDouble gives us a random value
//
// 0 <= fraction <= 1
//
// the distance from min to max declared as
//
// dist = max - min
//
// satisfies the following
//
// min + dist = max
//
// taking into account
//
// 0 <= fraction * dist <= dist
//
// we've got
//
// min <= min + fraction * dist <= max
return (int) (minimum + fraction * (maximum - minimum));
} | Generates a pseudo-random number
@param minimum The minimum allowable value
@param maximum The maximum allowable value
@return A pseudo-random number |
public final Http2FrameStream newStream() {
Http2FrameCodec codec = frameCodec;
if (codec == null) {
throw new IllegalStateException(StringUtil.simpleClassName(Http2FrameCodec.class) + " not found." +
" Has the handler been added to a pipeline?");
}
return codec.newStream();
} | Creates a new {@link Http2FrameStream} object.
<p>This method is <em>thread-safe</em>. |
@Override
protected Future<SslContext> lookup(ChannelHandlerContext ctx, String hostname) throws Exception {
return mapping.map(hostname, ctx.executor().<SslContext>newPromise());
} | The default implementation will simply call {@link AsyncMapping#map(Object, Promise)} but
users can override this method to implement custom behavior.
@see AsyncMapping#map(Object, Promise) |
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception {
SslHandler sslHandler = null;
try {
sslHandler = newSslHandler(sslContext, ctx.alloc());
ctx.pipeline().replace(this, SslHandler.class.getName(), sslHandler);
sslHandler = null;
} finally {
// Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
// transferred to the SslHandler.
// See https://github.com/netty/netty/issues/5678
if (sslHandler != null) {
ReferenceCountUtil.safeRelease(sslHandler.engine());
}
}
} | The default implementation of this method will simply replace {@code this} {@link SniHandler}
instance with a {@link SslHandler}. Users may override this method to implement custom behavior.
Please be aware that this method may get called after a client has already disconnected and
custom implementations must take it into consideration when overriding this method.
It's also possible for the hostname argument to be {@code null}. |
public static CharsetEncoder encoder(Charset charset, CodingErrorAction malformedInputAction,
CodingErrorAction unmappableCharacterAction) {
checkNotNull(charset, "charset");
CharsetEncoder e = charset.newEncoder();
e.onMalformedInput(malformedInputAction).onUnmappableCharacter(unmappableCharacterAction);
return e;
} | Returns a new {@link CharsetEncoder} for the {@link Charset} with specified error actions.
@param charset The specified charset
@param malformedInputAction The encoder's action for malformed-input errors
@param unmappableCharacterAction The encoder's action for unmappable-character errors
@return The encoder for the specified {@code charset} |
public static CharsetEncoder encoder(Charset charset, CodingErrorAction codingErrorAction) {
return encoder(charset, codingErrorAction, codingErrorAction);
} | Returns a new {@link CharsetEncoder} for the {@link Charset} with the specified error action.
@param charset The specified charset
@param codingErrorAction The encoder's action for malformed-input and unmappable-character errors
@return The encoder for the specified {@code charset} |
public static CharsetEncoder encoder(Charset charset) {
checkNotNull(charset, "charset");
Map<Charset, CharsetEncoder> map = InternalThreadLocalMap.get().charsetEncoderCache();
CharsetEncoder e = map.get(charset);
if (e != null) {
e.reset().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);
return e;
}
e = encoder(charset, CodingErrorAction.REPLACE, CodingErrorAction.REPLACE);
map.put(charset, e);
return e;
} | Returns a cached thread-local {@link CharsetEncoder} for the specified {@link Charset}.
@param charset The specified charset
@return The encoder for the specified {@code charset} |
public static CharsetDecoder decoder(Charset charset, CodingErrorAction malformedInputAction,
CodingErrorAction unmappableCharacterAction) {
checkNotNull(charset, "charset");
CharsetDecoder d = charset.newDecoder();
d.onMalformedInput(malformedInputAction).onUnmappableCharacter(unmappableCharacterAction);
return d;
} | Returns a new {@link CharsetDecoder} for the {@link Charset} with specified error actions.
@param charset The specified charset
@param malformedInputAction The decoder's action for malformed-input errors
@param unmappableCharacterAction The decoder's action for unmappable-character errors
@return The decoder for the specified {@code charset} |
public static CharsetDecoder decoder(Charset charset, CodingErrorAction codingErrorAction) {
return decoder(charset, codingErrorAction, codingErrorAction);
} | Returns a new {@link CharsetDecoder} for the {@link Charset} with the specified error action.
@param charset The specified charset
@param codingErrorAction The decoder's action for malformed-input and unmappable-character errors
@return The decoder for the specified {@code charset} |
public static CharsetDecoder decoder(Charset charset) {
checkNotNull(charset, "charset");
Map<Charset, CharsetDecoder> map = InternalThreadLocalMap.get().charsetDecoderCache();
CharsetDecoder d = map.get(charset);
if (d != null) {
d.reset().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);
return d;
}
d = decoder(charset, CodingErrorAction.REPLACE, CodingErrorAction.REPLACE);
map.put(charset, d);
return d;
} | Returns a cached thread-local {@link CharsetDecoder} for the specified {@link Charset}.
@param charset The specified charset
@return The decoder for the specified {@code charset} |
public void addParam(String name, String value) {
ObjectUtil.checkNotNull(name, "name");
if (hasParams) {
uriBuilder.append('&');
} else {
uriBuilder.append('?');
hasParams = true;
}
appendComponent(name, charsetName, uriBuilder);
if (value != null) {
uriBuilder.append('=');
appendComponent(value, charsetName, uriBuilder);
}
} | Adds a parameter with the specified name and value to this encoder. |
public static void watch(Thread thread, Runnable task) {
if (thread == null) {
throw new NullPointerException("thread");
}
if (task == null) {
throw new NullPointerException("task");
}
if (!thread.isAlive()) {
throw new IllegalArgumentException("thread must be alive.");
}
schedule(thread, task, true);
} | Schedules the specified {@code task} to run when the specified {@code thread} dies.
@param thread the {@link Thread} to watch
@param task the {@link Runnable} to run when the {@code thread} dies
@throws IllegalArgumentException if the specified {@code thread} is not alive |
public static void unwatch(Thread thread, Runnable task) {
if (thread == null) {
throw new NullPointerException("thread");
}
if (task == null) {
throw new NullPointerException("task");
}
schedule(thread, task, false);
} | Cancels the task scheduled via {@link #watch(Thread, Runnable)}. |
public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException {
if (unit == null) {
throw new NullPointerException("unit");
}
Thread watcherThread = ThreadDeathWatcher.watcherThread;
if (watcherThread != null) {
watcherThread.join(unit.toMillis(timeout));
return !watcherThread.isAlive();
} else {
return true;
}
} | Waits until the thread of this watcher has no threads to watch and terminates itself.
Because a new watcher thread will be started again on {@link #watch(Thread, Runnable)},
this operation is only useful when you want to ensure that the watcher thread is terminated
<strong>after</strong> your application is shut down and there's no chance of calling
{@link #watch(Thread, Runnable)} afterwards.
@return {@code true} if and only if the watcher thread has been terminated |
protected final void removeMessage(Http2Stream stream, boolean release) {
FullHttpMessage msg = stream.removeProperty(messageKey);
if (release && msg != null) {
msg.release();
}
} | The stream is out of scope for the HTTP message flow and will no longer be tracked
@param stream The stream to remove associated state with
@param release {@code true} to call release on the value if it is present. {@code false} to not call release. |
protected final void putMessage(Http2Stream stream, FullHttpMessage message) {
FullHttpMessage previous = stream.setProperty(messageKey, message);
if (previous != message && previous != null) {
previous.release();
}
} | Make {@code message} be the state associated with {@code stream}.
@param stream The stream which {@code message} is associated with.
@param message The message which contains the HTTP semantics. |
protected void fireChannelRead(ChannelHandlerContext ctx, FullHttpMessage msg, boolean release,
Http2Stream stream) {
removeMessage(stream, release);
HttpUtil.setContentLength(msg, msg.content().readableBytes());
ctx.fireChannelRead(msg);
} | Set final headers and fire a channel read event
@param ctx The context to fire the event on
@param msg The message to send
@param release {@code true} to call release on the value if it is present. {@code false} to not call release.
@param stream the stream of the message which is being fired |
protected FullHttpMessage newMessage(Http2Stream stream, Http2Headers headers, boolean validateHttpHeaders,
ByteBufAllocator alloc)
throws Http2Exception {
return connection.isServer() ? HttpConversionUtil.toFullHttpRequest(stream.id(), headers, alloc,
validateHttpHeaders) : HttpConversionUtil.toFullHttpResponse(stream.id(), headers, alloc,
validateHttpHeaders);
} | Create a new {@link FullHttpMessage} based upon the current connection parameters
@param stream The stream to create a message for
@param headers The headers associated with {@code stream}
@param validateHttpHeaders
<ul>
<li>{@code true} to validate HTTP headers in the http-codec</li>
<li>{@code false} not to validate HTTP headers in the http-codec</li>
</ul>
@param alloc The {@link ByteBufAllocator} to use to generate the content of the message
@throws Http2Exception |
protected FullHttpMessage processHeadersBegin(ChannelHandlerContext ctx, Http2Stream stream, Http2Headers headers,
boolean endOfStream, boolean allowAppend, boolean appendToTrailer) throws Http2Exception {
FullHttpMessage msg = getMessage(stream);
boolean release = true;
if (msg == null) {
msg = newMessage(stream, headers, validateHttpHeaders, ctx.alloc());
} else if (allowAppend) {
release = false;
HttpConversionUtil.addHttp2ToHttpHeaders(stream.id(), headers, msg, appendToTrailer);
} else {
release = false;
msg = null;
}
if (sendDetector.mustSendImmediately(msg)) {
// Copy the message (if necessary) before sending. The content is not expected to be copied (or used) in
// this operation but just in case it is used do the copy before sending and the resource may be released
final FullHttpMessage copy = endOfStream ? null : sendDetector.copyIfNeeded(msg);
fireChannelRead(ctx, msg, release, stream);
return copy;
}
return msg;
} | Provides translation between HTTP/2 and HTTP header objects while ensuring the stream
is in a valid state for additional headers.
@param ctx The context for which this message has been received.
Used to send informational header if detected.
@param stream The stream the {@code headers} apply to
@param headers The headers to process
@param endOfStream {@code true} if the {@code stream} has received the end of stream flag
@param allowAppend
<ul>
<li>{@code true} if headers will be appended if the stream already exists.</li>
<li>if {@code false} and the stream already exists this method returns {@code null}.</li>
</ul>
@param appendToTrailer
<ul>
<li>{@code true} if a message {@code stream} already exists then the headers
should be added to the trailing headers.</li>
<li>{@code false} then appends will be done to the initial headers.</li>
</ul>
@return The object used to track the stream corresponding to {@code stream}. {@code null} if
{@code allowAppend} is {@code false} and the stream already exists.
@throws Http2Exception If the stream id is not in the correct state to process the headers request |
private void processHeadersEnd(ChannelHandlerContext ctx, Http2Stream stream, FullHttpMessage msg,
boolean endOfStream) {
if (endOfStream) {
// Release if the msg from the map is different from the object being forwarded up the pipeline.
fireChannelRead(ctx, msg, getMessage(stream) != msg, stream);
} else {
putMessage(stream, msg);
}
} | After HTTP/2 headers have been processed by {@link #processHeadersBegin} this method either
sends the result up the pipeline or retains the message for future processing.
@param ctx The context for which this message has been received
@param stream The stream the {@code objAccumulator} corresponds to
@param msg The object which represents all headers/data for corresponding to {@code stream}
@param endOfStream {@code true} if this is the last event for the stream |
static List<HpackHeader> headers(HpackHeadersSize size, boolean limitToAscii) {
return headersMap.get(new HeadersKey(size, limitToAscii));
} | Gets headers for the given size and whether the key/values should be limited to ASCII. |
@SuppressWarnings("unchecked")
public static <T> ChannelOption<T> valueOf(String name) {
return (ChannelOption<T>) pool.valueOf(name);
} | Returns the {@link ChannelOption} of the specified name. |
@SuppressWarnings("unchecked")
public static <T> ChannelOption<T> valueOf(Class<?> firstNameComponent, String secondNameComponent) {
return (ChannelOption<T>) pool.valueOf(firstNameComponent, secondNameComponent);
} | Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}. |
@Deprecated
@SuppressWarnings("unchecked")
public static <T> ChannelOption<T> newInstance(String name) {
return (ChannelOption<T>) pool.newInstance(name);
} | Creates a new {@link ChannelOption} for the given {@code name} or fail with an
{@link IllegalArgumentException} if a {@link ChannelOption} for the given {@code name} exists.
@deprecated use {@link #valueOf(String)}. |
OpenSslKeyMaterial chooseKeyMaterial(ByteBufAllocator allocator, String alias) throws Exception {
X509Certificate[] certificates = keyManager.getCertificateChain(alias);
if (certificates == null || certificates.length == 0) {
return null;
}
PrivateKey key = keyManager.getPrivateKey(alias);
PemEncoded encoded = PemX509Certificate.toPEM(allocator, true, certificates);
long chainBio = 0;
long pkeyBio = 0;
long chain = 0;
long pkey = 0;
try {
chainBio = toBIO(allocator, encoded.retain());
chain = SSL.parseX509Chain(chainBio);
OpenSslKeyMaterial keyMaterial;
if (key instanceof OpenSslPrivateKey) {
keyMaterial = ((OpenSslPrivateKey) key).newKeyMaterial(chain, certificates);
} else {
pkeyBio = toBIO(allocator, key);
pkey = key == null ? 0 : SSL.parsePrivateKey(pkeyBio, password);
keyMaterial = new DefaultOpenSslKeyMaterial(chain, pkey, certificates);
}
// See the chain and pkey to 0 so we will not release it as the ownership was
// transferred to OpenSslKeyMaterial.
chain = 0;
pkey = 0;
return keyMaterial;
} finally {
SSL.freeBIO(chainBio);
SSL.freeBIO(pkeyBio);
if (chain != 0) {
SSL.freeX509Chain(chain);
}
if (pkey != 0) {
SSL.freePrivateKey(pkey);
}
encoded.release();
}
} | Returns the {@link OpenSslKeyMaterial} or {@code null} (if none) that should be used during the handshake by
OpenSSL. |
protected final int doWrite0(ChannelOutboundBuffer in) throws Exception {
Object msg = in.current();
if (msg == null) {
// Directly return here so incompleteWrite(...) is not called.
return 0;
}
return doWriteInternal(in, in.current());
} | Write objects to the OS.
@param in the collection which contains objects to write.
@return The value that should be decremented from the write quantum which starts at
{@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
<ul>
<li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
is encountered</li>
<li>1 - if a single call to write data was made to the OS</li>
<li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but no
data was accepted</li>
</ul>
@throws Exception if an I/O exception occurs during write. |
public static ResolvedAddressTypes computeResolvedAddressTypes(InternetProtocolFamily... internetProtocolFamilies) {
if (internetProtocolFamilies == null || internetProtocolFamilies.length == 0) {
return DnsNameResolver.DEFAULT_RESOLVE_ADDRESS_TYPES;
}
if (internetProtocolFamilies.length > 2) {
throw new IllegalArgumentException("No more than 2 InternetProtocolFamilies");
}
switch(internetProtocolFamilies[0]) {
case IPv4:
return (internetProtocolFamilies.length >= 2
&& internetProtocolFamilies[1] == InternetProtocolFamily.IPv6) ?
ResolvedAddressTypes.IPV4_PREFERRED: ResolvedAddressTypes.IPV4_ONLY;
case IPv6:
return (internetProtocolFamilies.length >= 2
&& internetProtocolFamilies[1] == InternetProtocolFamily.IPv4) ?
ResolvedAddressTypes.IPV6_PREFERRED: ResolvedAddressTypes.IPV6_ONLY;
default:
throw new IllegalArgumentException(
"Couldn't resolve ResolvedAddressTypes from InternetProtocolFamily array");
}
} | Compute a {@link ResolvedAddressTypes} from some {@link InternetProtocolFamily}s.
An empty input will return the default value, based on "java.net" System properties.
Valid inputs are (), (IPv4), (IPv6), (Ipv4, IPv6) and (IPv6, IPv4).
@param internetProtocolFamilies a valid sequence of {@link InternetProtocolFamily}s
@return a {@link ResolvedAddressTypes} |
public DnsNameResolverBuilder searchDomains(Iterable<String> searchDomains) {
checkNotNull(searchDomains, "searchDomains");
final List<String> list = new ArrayList<String>(4);
for (String f : searchDomains) {
if (f == null) {
break;
}
// Avoid duplicate entries.
if (list.contains(f)) {
continue;
}
list.add(f);
}
this.searchDomains = list.toArray(new String[0]);
return this;
} | Set the list of search domains of the resolver.
@param searchDomains the search domains
@return {@code this} |
public DnsNameResolver build() {
if (eventLoop == null) {
throw new IllegalStateException("eventLoop should be specified to build a DnsNameResolver.");
}
if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
throw new IllegalStateException("resolveCache and TTLs are mutually exclusive");
}
if (authoritativeDnsServerCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
throw new IllegalStateException("authoritativeDnsServerCache and TTLs are mutually exclusive");
}
DnsCache resolveCache = this.resolveCache != null ? this.resolveCache : newCache();
DnsCnameCache cnameCache = this.cnameCache != null ? this.cnameCache : newCnameCache();
AuthoritativeDnsServerCache authoritativeDnsServerCache = this.authoritativeDnsServerCache != null ?
this.authoritativeDnsServerCache : newAuthoritativeDnsServerCache();
return new DnsNameResolver(
eventLoop,
channelFactory,
resolveCache,
cnameCache,
authoritativeDnsServerCache,
dnsQueryLifecycleObserverFactory,
queryTimeoutMillis,
resolvedAddressTypes,
recursionDesired,
maxQueriesPerResolve,
traceEnabled,
maxPayloadSize,
optResourceEnabled,
hostsFileEntriesResolver,
dnsServerAddressStreamProvider,
searchDomains,
ndots,
decodeIdn);
} | Returns a new {@link DnsNameResolver} instance.
@return a {@link DnsNameResolver} |
public DnsNameResolverBuilder copy() {
DnsNameResolverBuilder copiedBuilder = new DnsNameResolverBuilder();
if (eventLoop != null) {
copiedBuilder.eventLoop(eventLoop);
}
if (channelFactory != null) {
copiedBuilder.channelFactory(channelFactory);
}
if (resolveCache != null) {
copiedBuilder.resolveCache(resolveCache);
}
if (cnameCache != null) {
copiedBuilder.cnameCache(cnameCache);
}
if (maxTtl != null && minTtl != null) {
copiedBuilder.ttl(minTtl, maxTtl);
}
if (negativeTtl != null) {
copiedBuilder.negativeTtl(negativeTtl);
}
if (authoritativeDnsServerCache != null) {
copiedBuilder.authoritativeDnsServerCache(authoritativeDnsServerCache);
}
if (dnsQueryLifecycleObserverFactory != null) {
copiedBuilder.dnsQueryLifecycleObserverFactory(dnsQueryLifecycleObserverFactory);
}
copiedBuilder.queryTimeoutMillis(queryTimeoutMillis);
copiedBuilder.resolvedAddressTypes(resolvedAddressTypes);
copiedBuilder.recursionDesired(recursionDesired);
copiedBuilder.maxQueriesPerResolve(maxQueriesPerResolve);
copiedBuilder.traceEnabled(traceEnabled);
copiedBuilder.maxPayloadSize(maxPayloadSize);
copiedBuilder.optResourceEnabled(optResourceEnabled);
copiedBuilder.hostsFileEntriesResolver(hostsFileEntriesResolver);
if (dnsServerAddressStreamProvider != null) {
copiedBuilder.nameServerProvider(dnsServerAddressStreamProvider);
}
if (searchDomains != null) {
copiedBuilder.searchDomains(Arrays.asList(searchDomains));
}
copiedBuilder.ndots(ndots);
copiedBuilder.decodeIdn(decodeIdn);
return copiedBuilder;
} | Creates a copy of this {@link DnsNameResolverBuilder}
@return {@link DnsNameResolverBuilder} |
@Override
public ChannelFuture block(
InetAddress multicastAddress, NetworkInterface networkInterface,
InetAddress sourceToBlock, ChannelPromise promise) {
checkJavaVersion();
if (multicastAddress == null) {
throw new NullPointerException("multicastAddress");
}
if (sourceToBlock == null) {
throw new NullPointerException("sourceToBlock");
}
if (networkInterface == null) {
throw new NullPointerException("networkInterface");
}
synchronized (this) {
if (memberships != null) {
List<MembershipKey> keys = memberships.get(multicastAddress);
for (MembershipKey key: keys) {
if (networkInterface.equals(key.networkInterface())) {
try {
key.block(sourceToBlock);
} catch (IOException e) {
promise.setFailure(e);
}
}
}
}
}
promise.setSuccess();
return promise;
} | Block the given sourceToBlock address for the given multicastAddress on the given networkInterface |
public static HttpMethod valueOf(String name) {
HttpMethod result = methodMap.get(name);
return result != null ? result : new HttpMethod(name);
} | Returns the {@link HttpMethod} represented by the specified name.
If the specified name is a standard HTTP method name, a cached instance
will be returned. Otherwise, a new instance will be returned. |
protected T build() {
final T instance;
try {
instance = build(connection(), maxContentLength(),
isValidateHttpHeaders(), isPropagateSettings());
} catch (Throwable t) {
throw new IllegalStateException("failed to create a new InboundHttp2ToHttpAdapter", t);
}
connection.addListener(instance);
return instance;
} | Builds/creates a new {@link InboundHttp2ToHttpAdapter} instance using this builder's current settings. |
@Override
protected void encode(ChannelHandlerContext ctx, HttpObject obj, List<Object> out) throws Exception {
// 100-continue is typically a FullHttpResponse, but the decoded
// Http2HeadersFrame should not be marked as endStream=true
if (obj instanceof HttpResponse) {
final HttpResponse res = (HttpResponse) obj;
if (res.status().equals(HttpResponseStatus.CONTINUE)) {
if (res instanceof FullHttpResponse) {
final Http2Headers headers = toHttp2Headers(ctx, res);
out.add(new DefaultHttp2HeadersFrame(headers, false));
return;
} else {
throw new EncoderException(
HttpResponseStatus.CONTINUE.toString() + " must be a FullHttpResponse");
}
}
}
if (obj instanceof HttpMessage) {
Http2Headers headers = toHttp2Headers(ctx, (HttpMessage) obj);
boolean noMoreFrames = false;
if (obj instanceof FullHttpMessage) {
FullHttpMessage full = (FullHttpMessage) obj;
noMoreFrames = !full.content().isReadable() && full.trailingHeaders().isEmpty();
}
out.add(new DefaultHttp2HeadersFrame(headers, noMoreFrames));
}
if (obj instanceof LastHttpContent) {
LastHttpContent last = (LastHttpContent) obj;
encodeLastContent(last, out);
} else if (obj instanceof HttpContent) {
HttpContent cont = (HttpContent) obj;
out.add(new DefaultHttp2DataFrame(cont.content().retain(), false));
}
} | Encode from an {@link HttpObject} to an {@link Http2StreamFrame}. This method will
be called for each written message that can be handled by this encoder.
NOTE: 100-Continue responses that are NOT {@link FullHttpResponse} will be rejected.
@param ctx the {@link ChannelHandlerContext} which this handler belongs to
@param obj the {@link HttpObject} message to encode
@param out the {@link List} into which the encoded msg should be added
needs to do some kind of aggregation
@throws Exception is thrown if an error occurs |
static InternalLogger wrapLogger(Logger logger) {
return logger instanceof LocationAwareLogger ?
new LocationAwareSlf4JLogger((LocationAwareLogger) logger) : new Slf4JLogger(logger);
} | package-private for testing. |
@Override
public Http2FrameCodec build() {
Http2FrameWriter frameWriter = this.frameWriter;
if (frameWriter != null) {
// This is to support our tests and will never be executed by the user as frameWriter(...)
// is package-private.
DefaultHttp2Connection connection = new DefaultHttp2Connection(isServer(), maxReservedStreams());
Long maxHeaderListSize = initialSettings().maxHeaderListSize();
Http2FrameReader frameReader = new DefaultHttp2FrameReader(maxHeaderListSize == null ?
new DefaultHttp2HeadersDecoder(true) :
new DefaultHttp2HeadersDecoder(true, maxHeaderListSize));
if (frameLogger() != null) {
frameWriter = new Http2OutboundFrameLogger(frameWriter, frameLogger());
frameReader = new Http2InboundFrameLogger(frameReader, frameLogger());
}
Http2ConnectionEncoder encoder = new DefaultHttp2ConnectionEncoder(connection, frameWriter);
if (encoderEnforceMaxConcurrentStreams()) {
encoder = new StreamBufferingEncoder(encoder);
}
Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder, frameReader,
promisedRequestVerifier(), isAutoAckSettingsFrame());
return build(decoder, encoder, initialSettings());
}
return super.build();
} | Build a {@link Http2FrameCodec} object. |
private Future<Channel> acquireHealthyFromPoolOrNew(final Promise<Channel> promise) {
try {
final Channel ch = pollChannel();
if (ch == null) {
// No Channel left in the pool bootstrap a new Channel
Bootstrap bs = bootstrap.clone();
bs.attr(POOL_KEY, this);
ChannelFuture f = connectChannel(bs);
if (f.isDone()) {
notifyConnect(f, promise);
} else {
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
notifyConnect(future, promise);
}
});
}
return promise;
}
EventLoop loop = ch.eventLoop();
if (loop.inEventLoop()) {
doHealthCheck(ch, promise);
} else {
loop.execute(new Runnable() {
@Override
public void run() {
doHealthCheck(ch, promise);
}
});
}
} catch (Throwable cause) {
promise.tryFailure(cause);
}
return promise;
} | Tries to retrieve healthy channel from the pool if any or creates a new channel otherwise.
@param promise the promise to provide acquire result.
@return future for acquiring a channel. |
private void releaseAndOfferIfHealthy(Channel channel, Promise<Void> promise, Future<Boolean> future)
throws Exception {
if (future.getNow()) { //channel turns out to be healthy, offering and releasing it.
releaseAndOffer(channel, promise);
} else { //channel not healthy, just releasing it.
handler.channelReleased(channel);
promise.setSuccess(null);
}
} | Adds the channel back to the pool only if the channel is healthy.
@param channel the channel to put back to the pool
@param promise offer operation promise.
@param future the future that contains information fif channel is healthy or not.
@throws Exception in case when failed to notify handler about release operation. |
public int forEachByte(int index, int length, ByteProcessor visitor) throws Exception {
if (isOutOfBounds(index, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= index(" + index + ") <= start + length(" + length
+ ") <= " + "length(" + length() + ')');
}
return forEachByte0(index, length, visitor);
} | Iterates over the specified area of this buffer with the specified {@code processor} in ascending order.
(i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}).
@return {@code -1} if the processor iterated to or beyond the end of the specified area.
The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. |
public int forEachByteDesc(int index, int length, ByteProcessor visitor) throws Exception {
if (isOutOfBounds(index, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= index(" + index + ") <= start + length(" + length
+ ") <= " + "length(" + length() + ')');
}
return forEachByteDesc0(index, length, visitor);
} | Iterates over the specified area of this buffer with the specified {@code processor} in descending order.
(i.e. {@code (index + length - 1)}, {@code (index + length - 2)}, ... {@code index}).
@return {@code -1} if the processor iterated to or beyond the beginning of the specified area.
The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}. |
public byte[] toByteArray(int start, int end) {
return Arrays.copyOfRange(value, start + offset, end + offset);
} | Converts a subset of this string to a byte array.
The subset is defined by the range [{@code start}, {@code end}). |
public void copy(int srcIdx, byte[] dst, int dstIdx, int length) {
if (isOutOfBounds(srcIdx, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length("
+ length + ") <= srcLen(" + length() + ')');
}
System.arraycopy(value, srcIdx + offset, checkNotNull(dst, "dst"), dstIdx, length);
} | Copies the content of this string to a byte array.
@param srcIdx the starting offset of characters to copy.
@param dst the destination byte array.
@param dstIdx the starting offset in the destination byte array.
@param length the number of characters to copy. |
@Override
public int compareTo(CharSequence string) {
if (this == string) {
return 0;
}
int result;
int length1 = length();
int length2 = string.length();
int minLength = Math.min(length1, length2);
for (int i = 0, j = arrayOffset(); i < minLength; i++, j++) {
result = b2c(value[j]) - string.charAt(i);
if (result != 0) {
return result;
}
}
return length1 - length2;
} | Compares the specified string to this string using the ASCII values of the characters. Returns 0 if the strings
contain the same characters in the same order. Returns a negative integer if the first non-equal character in
this string has an ASCII value which is less than the ASCII value of the character at the same position in the
specified string, or if this string is a prefix of the specified string. Returns a positive integer if the first
non-equal character in this string has a ASCII value which is greater than the ASCII value of the character at
the same position in the specified string, or if the specified string is a prefix of this string.
@param string the string to compare.
@return 0 if the strings are equal, a negative integer if this string is before the specified string, or a
positive integer if this string is after the specified string.
@throws NullPointerException if {@code string} is {@code null}. |
public AsciiString concat(CharSequence string) {
int thisLen = length();
int thatLen = string.length();
if (thatLen == 0) {
return this;
}
if (string.getClass() == AsciiString.class) {
AsciiString that = (AsciiString) string;
if (isEmpty()) {
return that;
}
byte[] newValue = PlatformDependent.allocateUninitializedArray(thisLen + thatLen);
System.arraycopy(value, arrayOffset(), newValue, 0, thisLen);
System.arraycopy(that.value, that.arrayOffset(), newValue, thisLen, thatLen);
return new AsciiString(newValue, false);
}
if (isEmpty()) {
return new AsciiString(string);
}
byte[] newValue = PlatformDependent.allocateUninitializedArray(thisLen + thatLen);
System.arraycopy(value, arrayOffset(), newValue, 0, thisLen);
for (int i = thisLen, j = 0; i < newValue.length; i++, j++) {
newValue[i] = c2b(string.charAt(j));
}
return new AsciiString(newValue, false);
} | Concatenates this string and the specified string.
@param string the string to concatenate
@return a new string which is the concatenation of this string and the specified string. |
public boolean endsWith(CharSequence suffix) {
int suffixLen = suffix.length();
return regionMatches(length() - suffixLen, suffix, 0, suffixLen);
} | Compares the specified string to this string to determine if the specified string is a suffix.
@param suffix the suffix to look for.
@return {@code true} if the specified string is a suffix of this string, {@code false} otherwise.
@throws NullPointerException if {@code suffix} is {@code null}. |
public boolean contentEqualsIgnoreCase(CharSequence string) {
if (string == null || string.length() != length()) {
return false;
}
if (string.getClass() == AsciiString.class) {
AsciiString rhs = (AsciiString) string;
for (int i = arrayOffset(), j = rhs.arrayOffset(); i < length(); ++i, ++j) {
if (!equalsIgnoreCase(value[i], rhs.value[j])) {
return false;
}
}
return true;
}
for (int i = arrayOffset(), j = 0; i < length(); ++i, ++j) {
if (!equalsIgnoreCase(b2c(value[i]), string.charAt(j))) {
return false;
}
}
return true;
} | Compares the specified string to this string ignoring the case of the characters and returns true if they are
equal.
@param string the string to compare.
@return {@code true} if the specified string is equal to this string, {@code false} otherwise. |
public char[] toCharArray(int start, int end) {
int length = end - start;
if (length == 0) {
return EmptyArrays.EMPTY_CHARS;
}
if (isOutOfBounds(start, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= start(" + start + ") <= srcIdx + length("
+ length + ") <= srcLen(" + length() + ')');
}
final char[] buffer = new char[length];
for (int i = 0, j = start + arrayOffset(); i < length; i++, j++) {
buffer[i] = b2c(value[j]);
}
return buffer;
} | Copies the characters in this string to a character array.
@return a character array containing the characters of this string. |
public void copy(int srcIdx, char[] dst, int dstIdx, int length) {
if (dst == null) {
throw new NullPointerException("dst");
}
if (isOutOfBounds(srcIdx, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length("
+ length + ") <= srcLen(" + length() + ')');
}
final int dstEnd = dstIdx + length;
for (int i = dstIdx, j = srcIdx + arrayOffset(); i < dstEnd; i++, j++) {
dst[i] = b2c(value[j]);
}
} | Copied the content of this string to a character array.
@param srcIdx the starting offset of characters to copy.
@param dst the destination character array.
@param dstIdx the starting offset in the destination byte array.
@param length the number of characters to copy. |
public AsciiString subSequence(int start, int end, boolean copy) {
if (isOutOfBounds(start, end - start, length())) {
throw new IndexOutOfBoundsException("expected: 0 <= start(" + start + ") <= end (" + end + ") <= length("
+ length() + ')');
}
if (start == 0 && end == length()) {
return this;
}
if (end == start) {
return EMPTY_STRING;
}
return new AsciiString(value, start + offset, end - start, copy);
} | Either copy or share a subset of underlying sub-sequence of bytes.
@param start the offset of the first character (inclusive).
@param end The index to stop at (exclusive).
@param copy If {@code true} then a copy of the underlying storage will be made.
If {@code false} then the underlying storage will be shared.
@return a new string containing the characters from start to the end of the string.
@throws IndexOutOfBoundsException if {@code start < 0} or {@code start > length()}. |
public int indexOf(CharSequence subString, int start) {
final int subCount = subString.length();
if (start < 0) {
start = 0;
}
if (subCount <= 0) {
return start < length ? start : length;
}
if (subCount > length - start) {
return INDEX_NOT_FOUND;
}
final char firstChar = subString.charAt(0);
if (firstChar > MAX_CHAR_VALUE) {
return INDEX_NOT_FOUND;
}
final byte firstCharAsByte = c2b0(firstChar);
final int len = offset + length - subCount;
for (int i = start + offset; i <= len; ++i) {
if (value[i] == firstCharAsByte) {
int o1 = i, o2 = 0;
while (++o2 < subCount && b2c(value[++o1]) == subString.charAt(o2)) {
// Intentionally empty
}
if (o2 == subCount) {
return i - offset;
}
}
}
return INDEX_NOT_FOUND;
} | Searches in this string for the index of the specified string. The search for the string starts at the specified
offset and moves towards the end of this string.
@param subString the string to find.
@param start the starting offset.
@return the index of the first character of the specified string in this string, -1 if the specified string is
not a substring.
@throws NullPointerException if {@code subString} is {@code null}. |
public int indexOf(char ch, int start) {
if (ch > MAX_CHAR_VALUE) {
return INDEX_NOT_FOUND;
}
if (start < 0) {
start = 0;
}
final byte chAsByte = c2b0(ch);
final int len = offset + length;
for (int i = start + offset; i < len; ++i) {
if (value[i] == chAsByte) {
return i - offset;
}
}
return INDEX_NOT_FOUND;
} | Searches in this string for the index of the specified char {@code ch}.
The search for the char starts at the specified offset {@code start} and moves towards the end of this string.
@param ch the char to find.
@param start the starting offset.
@return the index of the first occurrence of the specified char {@code ch} in this string,
-1 if found no occurrence. |
public boolean regionMatches(int thisStart, CharSequence string, int start, int length) {
if (string == null) {
throw new NullPointerException("string");
}
if (start < 0 || string.length() - start < length) {
return false;
}
final int thisLen = length();
if (thisStart < 0 || thisLen - thisStart < length) {
return false;
}
if (length <= 0) {
return true;
}
final int thatEnd = start + length;
for (int i = start, j = thisStart + arrayOffset(); i < thatEnd; i++, j++) {
if (b2c(value[j]) != string.charAt(i)) {
return false;
}
}
return true;
} | Compares the specified string to this string and compares the specified range of characters to determine if they
are the same.
@param thisStart the starting offset in this string.
@param string the string to compare.
@param start the starting offset in the specified string.
@param length the number of characters to compare.
@return {@code true} if the ranges of characters are equal, {@code false} otherwise
@throws NullPointerException if {@code string} is {@code null}. |
public boolean regionMatches(boolean ignoreCase, int thisStart, CharSequence string, int start, int length) {
if (!ignoreCase) {
return regionMatches(thisStart, string, start, length);
}
if (string == null) {
throw new NullPointerException("string");
}
final int thisLen = length();
if (thisStart < 0 || length > thisLen - thisStart) {
return false;
}
if (start < 0 || length > string.length() - start) {
return false;
}
thisStart += arrayOffset();
final int thisEnd = thisStart + length;
while (thisStart < thisEnd) {
if (!equalsIgnoreCase(b2c(value[thisStart++]), string.charAt(start++))) {
return false;
}
}
return true;
} | Compares the specified string to this string and compares the specified range of characters to determine if they
are the same. When ignoreCase is true, the case of the characters is ignored during the comparison.
@param ignoreCase specifies if case should be ignored.
@param thisStart the starting offset in this string.
@param string the string to compare.
@param start the starting offset in the specified string.
@param length the number of characters to compare.
@return {@code true} if the ranges of characters are equal, {@code false} otherwise.
@throws NullPointerException if {@code string} is {@code null}. |
public AsciiString replace(char oldChar, char newChar) {
if (oldChar > MAX_CHAR_VALUE) {
return this;
}
final byte oldCharAsByte = c2b0(oldChar);
final byte newCharAsByte = c2b(newChar);
final int len = offset + length;
for (int i = offset; i < len; ++i) {
if (value[i] == oldCharAsByte) {
byte[] buffer = PlatformDependent.allocateUninitializedArray(length());
System.arraycopy(value, offset, buffer, 0, i - offset);
buffer[i - offset] = newCharAsByte;
++i;
for (; i < len; ++i) {
byte oldValue = value[i];
buffer[i - offset] = oldValue != oldCharAsByte ? oldValue : newCharAsByte;
}
return new AsciiString(buffer, false);
}
}
return this;
} | Copies this string replacing occurrences of the specified character with another character.
@param oldChar the character to replace.
@param newChar the replacement character.
@return a new string with occurrences of oldChar replaced by newChar. |
public AsciiString toLowerCase() {
boolean lowercased = true;
int i, j;
final int len = length() + arrayOffset();
for (i = arrayOffset(); i < len; ++i) {
byte b = value[i];
if (b >= 'A' && b <= 'Z') {
lowercased = false;
break;
}
}
// Check if this string does not contain any uppercase characters.
if (lowercased) {
return this;
}
final byte[] newValue = PlatformDependent.allocateUninitializedArray(length());
for (i = 0, j = arrayOffset(); i < newValue.length; ++i, ++j) {
newValue[i] = toLowerCase(value[j]);
}
return new AsciiString(newValue, false);
} | Converts the characters in this string to lowercase, using the default Locale.
@return a new string containing the lowercase characters equivalent to the characters in this string. |
public AsciiString toUpperCase() {
boolean uppercased = true;
int i, j;
final int len = length() + arrayOffset();
for (i = arrayOffset(); i < len; ++i) {
byte b = value[i];
if (b >= 'a' && b <= 'z') {
uppercased = false;
break;
}
}
// Check if this string does not contain any lowercase characters.
if (uppercased) {
return this;
}
final byte[] newValue = PlatformDependent.allocateUninitializedArray(length());
for (i = 0, j = arrayOffset(); i < newValue.length; ++i, ++j) {
newValue[i] = toUpperCase(value[j]);
}
return new AsciiString(newValue, false);
} | Converts the characters in this string to uppercase, using the default Locale.
@return a new string containing the uppercase characters equivalent to the characters in this string. |
public static CharSequence trim(CharSequence c) {
if (c.getClass() == AsciiString.class) {
return ((AsciiString) c).trim();
}
if (c instanceof String) {
return ((String) c).trim();
}
int start = 0, last = c.length() - 1;
int end = last;
while (start <= end && c.charAt(start) <= ' ') {
start++;
}
while (end >= start && c.charAt(end) <= ' ') {
end--;
}
if (start == 0 && end == last) {
return c;
}
return c.subSequence(start, end);
} | Copies this string removing white space characters from the beginning and end of the string, and tries not to
copy if possible.
@param c The {@link CharSequence} to trim.
@return a new string with characters {@code <= \\u0020} removed from the beginning and the end. |
public AsciiString trim() {
int start = arrayOffset(), last = arrayOffset() + length() - 1;
int end = last;
while (start <= end && value[start] <= ' ') {
start++;
}
while (end >= start && value[end] <= ' ') {
end--;
}
if (start == 0 && end == last) {
return this;
}
return new AsciiString(value, start, end - start + 1, false);
} | Duplicates this string removing white space characters from the beginning and end of the
string, without copying.
@return a new string with characters {@code <= \\u0020} removed from the beginning and the end. |
public boolean contentEquals(CharSequence a) {
if (a == null || a.length() != length()) {
return false;
}
if (a.getClass() == AsciiString.class) {
return equals(a);
}
for (int i = arrayOffset(), j = 0; j < a.length(); ++i, ++j) {
if (b2c(value[i]) != a.charAt(j)) {
return false;
}
}
return true;
} | Compares a {@code CharSequence} to this {@code String} to determine if their contents are equal.
@param a the character sequence to compare to.
@return {@code true} if equal, otherwise {@code false} |
public AsciiString[] split(String expr, int max) {
return toAsciiStringArray(Pattern.compile(expr).split(this, max));
} | Splits this string using the supplied regular expression {@code expr}. The parameter {@code max} controls the
behavior how many times the pattern is applied to the string.
@param expr the regular expression used to divide the string.
@param max the number of entries in the resulting array.
@return an array of Strings created by separating the string along matches of the regular expression.
@throws NullPointerException if {@code expr} is {@code null}.
@throws PatternSyntaxException if the syntax of the supplied regular expression is not valid.
@see Pattern#split(CharSequence, int) |
public AsciiString[] split(char delim) {
final List<AsciiString> res = InternalThreadLocalMap.get().arrayList();
int start = 0;
final int length = length();
for (int i = start; i < length; i++) {
if (charAt(i) == delim) {
if (start == i) {
res.add(EMPTY_STRING);
} else {
res.add(new AsciiString(value, start + arrayOffset(), i - start, false));
}
start = i + 1;
}
}
if (start == 0) { // If no delimiter was found in the value
res.add(this);
} else {
if (start != length) {
// Add the last element if it's not empty.
res.add(new AsciiString(value, start + arrayOffset(), length - start, false));
} else {
// Truncate trailing empty elements.
for (int i = res.size() - 1; i >= 0; i--) {
if (res.get(i).isEmpty()) {
res.remove(i);
} else {
break;
}
}
}
}
return res.toArray(new AsciiString[0]);
} | Splits the specified {@link String} with the specified delimiter.. |
public static AsciiString of(CharSequence string) {
return string.getClass() == AsciiString.class ? (AsciiString) string : new AsciiString(string);
} | Returns an {@link AsciiString} containing the given character sequence. If the given string is already a
{@link AsciiString}, just returns the same instance. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.