code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private static Class<?> tryToLoadClass(final ClassLoader loader, final Class<?> helper)
throws ClassNotFoundException {
try {
return Class.forName(helper.getName(), false, loader);
} catch (ClassNotFoundException e1) {
if (loader == null) {
// cannot defineClass inside bootstrap class loader
throw e1;
}
try {
// The helper class is NOT found in target ClassLoader, we have to define the helper class.
final byte[] classBinary = classToByteArray(helper);
return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
// Define the helper class in the target ClassLoader,
// then we can call the helper to load the native library.
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class);
defineClass.setAccessible(true);
return (Class<?>) defineClass.invoke(loader, helper.getName(), classBinary, 0,
classBinary.length);
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
}
});
} catch (ClassNotFoundException e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
} catch (RuntimeException e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
} catch (Error e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
}
}
} | Try to load the helper {@link Class} into specified {@link ClassLoader}.
@param loader - The {@link ClassLoader} where to load the helper {@link Class}
@param helper - The helper {@link Class}
@return A new helper Class defined in the specified ClassLoader.
@throws ClassNotFoundException Helper class not found or loading failed |
private static byte[] classToByteArray(Class<?> clazz) throws ClassNotFoundException {
String fileName = clazz.getName();
int lastDot = fileName.lastIndexOf('.');
if (lastDot > 0) {
fileName = fileName.substring(lastDot + 1);
}
URL classUrl = clazz.getResource(fileName + ".class");
if (classUrl == null) {
throw new ClassNotFoundException(clazz.getName());
}
byte[] buf = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
InputStream in = null;
try {
in = classUrl.openStream();
for (int r; (r = in.read(buf)) != -1;) {
out.write(buf, 0, r);
}
return out.toByteArray();
} catch (IOException ex) {
throw new ClassNotFoundException(clazz.getName(), ex);
} finally {
closeQuietly(in);
closeQuietly(out);
}
} | Load the helper {@link Class} as a byte array, to be redefined in specified {@link ClassLoader}.
@param clazz - The helper {@link Class} provided by this bundle
@return The binary content of helper {@link Class}.
@throws ClassNotFoundException Helper class not found or loading failed |
public static ByteBuffer allocateDirectWithNativeOrder(int capacity) {
return ByteBuffer.allocateDirect(capacity).order(
PlatformDependent.BIG_ENDIAN_NATIVE_ORDER ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
} | Returns a new {@link ByteBuffer} which has the same {@link ByteOrder} as the native order of the machine. |
public static long memoryAddress(ByteBuffer buffer) {
assert buffer.isDirect();
if (PlatformDependent.hasUnsafe()) {
return PlatformDependent.directBufferAddress(buffer);
}
return memoryAddress0(buffer);
} | Returns the memory address of the given direct {@link ByteBuffer}. |
private M invalidMessage(Exception cause) {
state = State.BAD_MESSAGE;
M message = buildInvalidMessage();
message.setDecoderResult(DecoderResult.failure(cause));
return message;
} | Helper method to create a message indicating a invalid decoding result.
@param cause the cause of the decoding failure.
@return a valid message indicating failure. |
private MemcacheContent invalidChunk(Exception cause) {
state = State.BAD_MESSAGE;
MemcacheContent chunk = new DefaultLastMemcacheContent(Unpooled.EMPTY_BUFFER);
chunk.setDecoderResult(DecoderResult.failure(cause));
return chunk;
} | Helper method to create a content chunk indicating a invalid decoding result.
@param cause the cause of the decoding failure.
@return a valid content chunk indicating failure. |
private Set<Cookie> doDecode(String header) {
List<String> names = new ArrayList<String>(8);
List<String> values = new ArrayList<String>(8);
extractKeyValuePairs(header, names, values);
if (names.isEmpty()) {
return Collections.emptySet();
}
int i;
int version = 0;
// $Version is the only attribute that can appear before the actual
// cookie name-value pair.
if (names.get(0).equalsIgnoreCase(VERSION)) {
try {
version = Integer.parseInt(values.get(0));
} catch (NumberFormatException e) {
// Ignore.
}
i = 1;
} else {
i = 0;
}
if (names.size() <= i) {
// There's a version attribute, but nothing more.
return Collections.emptySet();
}
Set<Cookie> cookies = new TreeSet<Cookie>();
for (; i < names.size(); i ++) {
String name = names.get(i);
String value = values.get(i);
if (value == null) {
value = "";
}
Cookie c = initCookie(name, value);
if (c == null) {
break;
}
boolean discard = false;
boolean secure = false;
boolean httpOnly = false;
String comment = null;
String commentURL = null;
String domain = null;
String path = null;
long maxAge = Long.MIN_VALUE;
List<Integer> ports = new ArrayList<Integer>(2);
for (int j = i + 1; j < names.size(); j++, i++) {
name = names.get(j);
value = values.get(j);
if (DISCARD.equalsIgnoreCase(name)) {
discard = true;
} else if (CookieHeaderNames.SECURE.equalsIgnoreCase(name)) {
secure = true;
} else if (CookieHeaderNames.HTTPONLY.equalsIgnoreCase(name)) {
httpOnly = true;
} else if (COMMENT.equalsIgnoreCase(name)) {
comment = value;
} else if (COMMENTURL.equalsIgnoreCase(name)) {
commentURL = value;
} else if (CookieHeaderNames.DOMAIN.equalsIgnoreCase(name)) {
domain = value;
} else if (CookieHeaderNames.PATH.equalsIgnoreCase(name)) {
path = value;
} else if (CookieHeaderNames.EXPIRES.equalsIgnoreCase(name)) {
Date date = DateFormatter.parseHttpDate(value);
if (date != null) {
long maxAgeMillis = date.getTime() - System.currentTimeMillis();
maxAge = maxAgeMillis / 1000 + (maxAgeMillis % 1000 != 0? 1 : 0);
}
} else if (CookieHeaderNames.MAX_AGE.equalsIgnoreCase(name)) {
maxAge = Integer.parseInt(value);
} else if (VERSION.equalsIgnoreCase(name)) {
version = Integer.parseInt(value);
} else if (PORT.equalsIgnoreCase(name)) {
String[] portList = value.split(",");
for (String s1: portList) {
try {
ports.add(Integer.valueOf(s1));
} catch (NumberFormatException e) {
// Ignore.
}
}
} else {
break;
}
}
c.setVersion(version);
c.setMaxAge(maxAge);
c.setPath(path);
c.setDomain(domain);
c.setSecure(secure);
c.setHttpOnly(httpOnly);
if (version > 0) {
c.setComment(comment);
}
if (version > 1) {
c.setCommentUrl(commentURL);
c.setPorts(ports);
c.setDiscard(discard);
}
cookies.add(c);
}
return cookies;
} | Decodes the specified HTTP header value into {@link Cookie}s.
@return the decoded {@link Cookie}s |
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
HttpServerUpgradeHandler.UpgradeEvent upgradeEvent =
(HttpServerUpgradeHandler.UpgradeEvent) evt;
onHeadersRead(ctx, 1, http1HeadersToHttp2Headers(upgradeEvent.upgradeRequest()), 0 , true);
}
super.userEventTriggered(ctx, evt);
} | Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2
on stream 1 (the stream specifically reserved for cleartext HTTP upgrade). |
private void sendResponse(ChannelHandlerContext ctx, int streamId, ByteBuf payload) {
// Send a frame for the response status
Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
encoder().writeData(ctx, streamId, payload, 0, true, ctx.newPromise());
// no need to call flush as channelReadComplete(...) will take care of it.
} | Sends a "Hello World" DATA frame to the client. |
public static Date parseHttpDate(CharSequence txt, int start, int end) {
int length = end - start;
if (length == 0) {
return null;
} else if (length < 0) {
throw new IllegalArgumentException("Can't have end < start");
} else if (length > 64) {
throw new IllegalArgumentException("Can't parse more than 64 chars," +
"looks like a user error or a malformed header");
}
return formatter().parse0(checkNotNull(txt, "txt"), start, end);
} | Parse some text into a {@link Date}, according to RFC6265
@param txt text to parse
@param start the start index inside {@code txt}
@param end the end index inside {@code txt}
@return a {@link Date}, or null if text couldn't be parsed |
public static StringBuilder append(Date date, StringBuilder sb) {
return formatter().append0(checkNotNull(date, "date"), checkNotNull(sb, "sb"));
} | Append a {@link Date} to a {@link StringBuilder} into RFC1123 format
@param date the date to format
@param sb the StringBuilder
@return the same StringBuilder |
private T retain0(T instance, final int increment, final int rawIncrement) {
int oldRef = updater().getAndAdd(instance, rawIncrement);
if (oldRef != 2 && oldRef != 4 && (oldRef & 1) != 0) {
throw new IllegalReferenceCountException(0, increment);
}
// don't pass 0!
if ((oldRef <= 0 && oldRef + rawIncrement >= 0)
|| (oldRef >= 0 && oldRef + rawIncrement < oldRef)) {
// overflow case
updater().getAndAdd(instance, -rawIncrement);
throw new IllegalReferenceCountException(realRefCnt(oldRef), increment);
}
return instance;
} | rawIncrement == increment << 1 |
@Override
public final void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
try {
onChannelReadComplete(ctx);
} finally {
parentReadInProgress = false;
tail = head = null;
// We always flush as this is what Http2ConnectionHandler does for now.
flush0(ctx);
}
channelReadComplete0(ctx);
} | Notifies any child streams of the read completion. |
public static byte[] bestAvailableMac() {
// Find the best MAC address available.
byte[] bestMacAddr = EMPTY_BYTES;
InetAddress bestInetAddr = NetUtil.LOCALHOST4;
// Retrieve the list of available network interfaces.
Map<NetworkInterface, InetAddress> ifaces = new LinkedHashMap<NetworkInterface, InetAddress>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// Use the interface with proper INET addresses only.
Enumeration<InetAddress> addrs = SocketUtils.addressesFromNetworkInterface(iface);
if (addrs.hasMoreElements()) {
InetAddress a = addrs.nextElement();
if (!a.isLoopbackAddress()) {
ifaces.put(iface, a);
}
}
}
}
} catch (SocketException e) {
logger.warn("Failed to retrieve the list of available network interfaces", e);
}
for (Entry<NetworkInterface, InetAddress> entry: ifaces.entrySet()) {
NetworkInterface iface = entry.getKey();
InetAddress inetAddr = entry.getValue();
if (iface.isVirtual()) {
continue;
}
byte[] macAddr;
try {
macAddr = SocketUtils.hardwareAddressFromNetworkInterface(iface);
} catch (SocketException e) {
logger.debug("Failed to get the hardware address of a network interface: {}", iface, e);
continue;
}
boolean replace = false;
int res = compareAddresses(bestMacAddr, macAddr);
if (res < 0) {
// Found a better MAC address.
replace = true;
} else if (res == 0) {
// Two MAC addresses are of pretty much same quality.
res = compareAddresses(bestInetAddr, inetAddr);
if (res < 0) {
// Found a MAC address with better INET address.
replace = true;
} else if (res == 0) {
// Cannot tell the difference. Choose the longer one.
if (bestMacAddr.length < macAddr.length) {
replace = true;
}
}
}
if (replace) {
bestMacAddr = macAddr;
bestInetAddr = inetAddr;
}
}
if (bestMacAddr == EMPTY_BYTES) {
return null;
}
switch (bestMacAddr.length) {
case EUI48_MAC_ADDRESS_LENGTH: // EUI-48 - convert to EUI-64
byte[] newAddr = new byte[EUI64_MAC_ADDRESS_LENGTH];
System.arraycopy(bestMacAddr, 0, newAddr, 0, 3);
newAddr[3] = (byte) 0xFF;
newAddr[4] = (byte) 0xFE;
System.arraycopy(bestMacAddr, 3, newAddr, 5, 3);
bestMacAddr = newAddr;
break;
default: // Unknown
bestMacAddr = Arrays.copyOf(bestMacAddr, EUI64_MAC_ADDRESS_LENGTH);
}
return bestMacAddr;
} | Obtains the best MAC address found on local network interfaces.
Generally speaking, an active network interface used on public
networks is better than a local network interface.
@return byte array containing a MAC. null if no MAC can be found. |
public static byte[] defaultMachineId() {
byte[] bestMacAddr = bestAvailableMac();
if (bestMacAddr == null) {
bestMacAddr = new byte[EUI64_MAC_ADDRESS_LENGTH];
PlatformDependent.threadLocalRandom().nextBytes(bestMacAddr);
logger.warn(
"Failed to find a usable hardware address from the network interfaces; using random bytes: {}",
formatAddress(bestMacAddr));
}
return bestMacAddr;
} | Returns the result of {@link #bestAvailableMac()} if non-{@code null} otherwise returns a random EUI-64 MAC
address. |
public static byte[] parseMAC(String value) {
final byte[] machineId;
final char separator;
switch (value.length()) {
case 17:
separator = value.charAt(2);
validateMacSeparator(separator);
machineId = new byte[EUI48_MAC_ADDRESS_LENGTH];
break;
case 23:
separator = value.charAt(2);
validateMacSeparator(separator);
machineId = new byte[EUI64_MAC_ADDRESS_LENGTH];
break;
default:
throw new IllegalArgumentException("value is not supported [MAC-48, EUI-48, EUI-64]");
}
final int end = machineId.length - 1;
int j = 0;
for (int i = 0; i < end; ++i, j += 3) {
final int sIndex = j + 2;
machineId[i] = StringUtil.decodeHexByte(value, j);
if (value.charAt(sIndex) != separator) {
throw new IllegalArgumentException("expected separator '" + separator + " but got '" +
value.charAt(sIndex) + "' at index: " + sIndex);
}
}
machineId[end] = StringUtil.decodeHexByte(value, j);
return machineId;
} | Parse a EUI-48, MAC-48, or EUI-64 MAC address from a {@link String} and return it as a {@code byte[]}.
@param value The string representation of the MAC address.
@return The byte representation of the MAC address. |
static int compareAddresses(byte[] current, byte[] candidate) {
if (candidate == null || candidate.length < EUI48_MAC_ADDRESS_LENGTH) {
return 1;
}
// Must not be filled with only 0 and 1.
boolean onlyZeroAndOne = true;
for (byte b: candidate) {
if (b != 0 && b != 1) {
onlyZeroAndOne = false;
break;
}
}
if (onlyZeroAndOne) {
return 1;
}
// Must not be a multicast address
if ((candidate[0] & 1) != 0) {
return 1;
}
// Prefer globally unique address.
if ((candidate[0] & 2) == 0) {
if (current.length != 0 && (current[0] & 2) == 0) {
// Both current and candidate are globally unique addresses.
return 0;
} else {
// Only candidate is globally unique.
return -1;
}
} else {
if (current.length != 0 && (current[0] & 2) == 0) {
// Only current is globally unique.
return 1;
} else {
// Both current and candidate are non-unique.
return 0;
}
}
} | visible for testing |
protected B server(boolean isServer) {
enforceConstraint("server", "connection", connection);
enforceConstraint("server", "codec", decoder);
enforceConstraint("server", "codec", encoder);
this.isServer = isServer;
return self();
} | Sets if {@link #build()} will to create a {@link Http2Connection} in server mode ({@code true})
or client mode ({@code false}). |
protected B maxReservedStreams(int maxReservedStreams) {
enforceConstraint("server", "connection", connection);
enforceConstraint("server", "codec", decoder);
enforceConstraint("server", "codec", encoder);
this.maxReservedStreams = checkPositiveOrZero(maxReservedStreams, "maxReservedStreams");
return self();
} | Set the maximum number of streams which can be in the reserved state at any given time. |
protected B connection(Http2Connection connection) {
enforceConstraint("connection", "maxReservedStreams", maxReservedStreams);
enforceConstraint("connection", "server", isServer);
enforceConstraint("connection", "codec", decoder);
enforceConstraint("connection", "codec", encoder);
this.connection = checkNotNull(connection, "connection");
return self();
} | Sets the {@link Http2Connection} to use. |
protected B codec(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder) {
enforceConstraint("codec", "server", isServer);
enforceConstraint("codec", "maxReservedStreams", maxReservedStreams);
enforceConstraint("codec", "connection", connection);
enforceConstraint("codec", "frameLogger", frameLogger);
enforceConstraint("codec", "validateHeaders", validateHeaders);
enforceConstraint("codec", "headerSensitivityDetector", headerSensitivityDetector);
enforceConstraint("codec", "encoderEnforceMaxConcurrentStreams", encoderEnforceMaxConcurrentStreams);
checkNotNull(decoder, "decoder");
checkNotNull(encoder, "encoder");
if (decoder.connection() != encoder.connection()) {
throw new IllegalArgumentException("The specified encoder and decoder have different connections.");
}
this.decoder = decoder;
this.encoder = encoder;
return self();
} | Sets the {@link Http2ConnectionDecoder} and {@link Http2ConnectionEncoder} to use. |
protected T build() {
if (encoder != null) {
assert decoder != null;
return buildFromCodec(decoder, encoder);
}
Http2Connection connection = this.connection;
if (connection == null) {
connection = new DefaultHttp2Connection(isServer(), maxReservedStreams());
}
return buildFromConnection(connection);
} | Create a new {@link Http2ConnectionHandler}. |
final void forEachActiveStream(final Http2FrameStreamVisitor streamVisitor) throws Http2Exception {
assert ctx.executor().inEventLoop();
connection().forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) {
try {
return streamVisitor.visit((Http2FrameStream) stream.getProperty(streamKey));
} catch (Throwable cause) {
onError(ctx, false, cause);
return false;
}
}
});
} | Iterates over all active HTTP/2 streams.
<p>This method must not be called outside of the event loop. |
@Override
public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) {
// The user event implies that we are on the client.
tryExpandConnectionFlowControlWindow(connection());
} else if (evt instanceof UpgradeEvent) {
UpgradeEvent upgrade = (UpgradeEvent) evt;
try {
onUpgradeEvent(ctx, upgrade.retain());
Http2Stream stream = connection().stream(HTTP_UPGRADE_STREAM_ID);
if (stream.getProperty(streamKey) == null) {
// TODO: improve handler/stream lifecycle so that stream isn't active before handler added.
// The stream was already made active, but ctx may have been null so it wasn't initialized.
// https://github.com/netty/netty/issues/4942
onStreamActive0(stream);
}
upgrade.upgradeRequest().headers().setInt(
HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), HTTP_UPGRADE_STREAM_ID);
stream.setProperty(upgradeKey, true);
InboundHttpToHttp2Adapter.handle(
ctx, connection(), decoder().frameListener(), upgrade.upgradeRequest().retain());
} finally {
upgrade.release();
}
return;
}
super.userEventTriggered(ctx, evt);
} | Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via
HTTP/2 on stream 1 (the stream specifically reserved for cleartext HTTP upgrade). |
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (msg instanceof Http2DataFrame) {
Http2DataFrame dataFrame = (Http2DataFrame) msg;
encoder().writeData(ctx, dataFrame.stream().id(), dataFrame.content(),
dataFrame.padding(), dataFrame.isEndStream(), promise);
} else if (msg instanceof Http2HeadersFrame) {
writeHeadersFrame(ctx, (Http2HeadersFrame) msg, promise);
} else if (msg instanceof Http2WindowUpdateFrame) {
Http2WindowUpdateFrame frame = (Http2WindowUpdateFrame) msg;
Http2FrameStream frameStream = frame.stream();
// It is legit to send a WINDOW_UPDATE frame for the connection stream. The parent channel doesn't attempt
// to set the Http2FrameStream so we assume if it is null the WINDOW_UPDATE is for the connection stream.
try {
if (frameStream == null) {
increaseInitialConnectionWindow(frame.windowSizeIncrement());
} else {
consumeBytes(frameStream.id(), frame.windowSizeIncrement());
}
promise.setSuccess();
} catch (Throwable t) {
promise.setFailure(t);
}
} else if (msg instanceof Http2ResetFrame) {
Http2ResetFrame rstFrame = (Http2ResetFrame) msg;
encoder().writeRstStream(ctx, rstFrame.stream().id(), rstFrame.errorCode(), promise);
} else if (msg instanceof Http2PingFrame) {
Http2PingFrame frame = (Http2PingFrame) msg;
encoder().writePing(ctx, frame.ack(), frame.content(), promise);
} else if (msg instanceof Http2SettingsFrame) {
encoder().writeSettings(ctx, ((Http2SettingsFrame) msg).settings(), promise);
} else if (msg instanceof Http2SettingsAckFrame) {
// In the event of manual SETTINGS ACK is is assumed the encoder will apply the earliest received but not
// yet ACKed settings.
encoder().writeSettingsAck(ctx, promise);
} else if (msg instanceof Http2GoAwayFrame) {
writeGoAwayFrame(ctx, (Http2GoAwayFrame) msg, promise);
} else if (msg instanceof Http2UnknownFrame) {
Http2UnknownFrame unknownFrame = (Http2UnknownFrame) msg;
encoder().writeFrame(ctx, unknownFrame.frameType(), unknownFrame.stream().id(),
unknownFrame.flags(), unknownFrame.content(), promise);
} else if (!(msg instanceof Http2Frame)) {
ctx.write(msg, promise);
} else {
ReferenceCountUtil.release(msg);
throw new UnsupportedMessageTypeException(msg);
}
} | Processes all {@link Http2Frame}s. {@link Http2StreamFrame}s may only originate in child
streams. |
@Override
protected final void onStreamError(ChannelHandlerContext ctx, boolean outbound, Throwable cause,
Http2Exception.StreamException streamException) {
int streamId = streamException.streamId();
Http2Stream connectionStream = connection().stream(streamId);
if (connectionStream == null) {
onHttp2UnknownStreamError(ctx, cause, streamException);
// Write a RST_STREAM
super.onStreamError(ctx, outbound, cause, streamException);
return;
}
Http2FrameStream stream = connectionStream.getProperty(streamKey);
if (stream == null) {
LOG.warn("Stream exception thrown without stream object attached.", cause);
// Write a RST_STREAM
super.onStreamError(ctx, outbound, cause, streamException);
return;
}
if (!outbound) {
// We only forward non outbound errors as outbound errors will already be reflected by failing the promise.
onHttp2FrameStreamException(ctx, new Http2FrameStreamException(stream, streamException.error(), cause));
}
} | Exceptions for unknown streams, that is streams that have no {@link Http2FrameStream} object attached
are simply logged and replied to by sending a RST_STREAM frame. |
private static boolean isUpgradeRequest(HttpObject msg) {
return msg instanceof HttpRequest && ((HttpRequest) msg).headers().get(HttpHeaderNames.UPGRADE) != null;
} | Determines whether or not the message is an HTTP upgrade request. |
private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) {
// Select the best protocol based on those requested in the UPGRADE header.
final List<CharSequence> requestedProtocols = splitHeader(request.headers().get(HttpHeaderNames.UPGRADE));
final int numRequestedProtocols = requestedProtocols.size();
UpgradeCodec upgradeCodec = null;
CharSequence upgradeProtocol = null;
for (int i = 0; i < numRequestedProtocols; i ++) {
final CharSequence p = requestedProtocols.get(i);
final UpgradeCodec c = upgradeCodecFactory.newUpgradeCodec(p);
if (c != null) {
upgradeProtocol = p;
upgradeCodec = c;
break;
}
}
if (upgradeCodec == null) {
// None of the requested protocols are supported, don't upgrade.
return false;
}
// Make sure the CONNECTION header is present.
List<String> connectionHeaderValues = request.headers().getAll(HttpHeaderNames.CONNECTION);
if (connectionHeaderValues == null) {
return false;
}
final StringBuilder concatenatedConnectionValue = new StringBuilder(connectionHeaderValues.size() * 10);
for (CharSequence connectionHeaderValue : connectionHeaderValues) {
concatenatedConnectionValue.append(connectionHeaderValue).append(COMMA);
}
concatenatedConnectionValue.setLength(concatenatedConnectionValue.length() - 1);
// Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers.
Collection<CharSequence> requiredHeaders = upgradeCodec.requiredUpgradeHeaders();
List<CharSequence> values = splitHeader(concatenatedConnectionValue);
if (!containsContentEqualsIgnoreCase(values, HttpHeaderNames.UPGRADE) ||
!containsAllContentEqualsIgnoreCase(values, requiredHeaders)) {
return false;
}
// Ensure that all required protocol-specific headers are found in the request.
for (CharSequence requiredHeader : requiredHeaders) {
if (!request.headers().contains(requiredHeader)) {
return false;
}
}
// Prepare and send the upgrade response. Wait for this write to complete before upgrading,
// since we need the old codec in-place to properly encode the response.
final FullHttpResponse upgradeResponse = createUpgradeResponse(upgradeProtocol);
if (!upgradeCodec.prepareUpgradeResponse(ctx, request, upgradeResponse.headers())) {
return false;
}
// Create the user event to be fired once the upgrade completes.
final UpgradeEvent event = new UpgradeEvent(upgradeProtocol, request);
// After writing the upgrade response we immediately prepare the
// pipeline for the next protocol to avoid a race between completion
// of the write future and receiving data before the pipeline is
// restructured.
try {
final ChannelFuture writeComplete = ctx.writeAndFlush(upgradeResponse);
// Perform the upgrade to the new protocol.
sourceCodec.upgradeFrom(ctx);
upgradeCodec.upgradeTo(ctx, request);
// Remove this handler from the pipeline.
ctx.pipeline().remove(HttpServerUpgradeHandler.this);
// Notify that the upgrade has occurred. Retain the event to offset
// the release() in the finally block.
ctx.fireUserEventTriggered(event.retain());
// Add the listener last to avoid firing upgrade logic after
// the channel is already closed since the listener may fire
// immediately if the write failed eagerly.
writeComplete.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} finally {
// Release the event if the upgrade event wasn't fired.
event.release();
}
return true;
} | Attempts to upgrade to the protocol(s) identified by the {@link HttpHeaderNames#UPGRADE} header (if provided
in the request).
@param ctx the context for this handler.
@param request the HTTP request.
@return {@code true} if the upgrade occurred, otherwise {@code false}. |
private static FullHttpResponse createUpgradeResponse(CharSequence upgradeProtocol) {
DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS,
Unpooled.EMPTY_BUFFER, false);
res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
res.headers().add(HttpHeaderNames.UPGRADE, upgradeProtocol);
return res;
} | Creates the 101 Switching Protocols response message. |
private static List<CharSequence> splitHeader(CharSequence header) {
final StringBuilder builder = new StringBuilder(header.length());
final List<CharSequence> protocols = new ArrayList<CharSequence>(4);
for (int i = 0; i < header.length(); ++i) {
char c = header.charAt(i);
if (Character.isWhitespace(c)) {
// Don't include any whitespace.
continue;
}
if (c == ',') {
// Add the string and reset the builder for the next protocol.
protocols.add(builder.toString());
builder.setLength(0);
} else {
builder.append(c);
}
}
// Add the last protocol
if (builder.length() > 0) {
protocols.add(builder.toString());
}
return protocols;
} | Splits a comma-separated header value. The returned set is case-insensitive and contains each
part with whitespace removed. |
public static Http2Exception connectionError(Http2Error error, String fmt, Object... args) {
return new Http2Exception(error, String.format(fmt, args));
} | Use if an error has occurred which can not be isolated to a single stream, but instead applies
to the entire connection.
@param error The type of error as defined by the HTTP/2 specification.
@param fmt String with the content and format for the additional debug data.
@param args Objects which fit into the format defined by {@code fmt}.
@return An exception which can be translated into a HTTP/2 error. |
public static Http2Exception closedStreamError(Http2Error error, String fmt, Object... args) {
return new ClosedStreamCreationException(error, String.format(fmt, args));
} | Use if an error has occurred which can not be isolated to a single stream, but instead applies
to the entire connection.
@param error The type of error as defined by the HTTP/2 specification.
@param fmt String with the content and format for the additional debug data.
@param args Objects which fit into the format defined by {@code fmt}.
@return An exception which can be translated into a HTTP/2 error. |
public static Http2Exception streamError(int id, Http2Error error, Throwable cause,
String fmt, Object... args) {
return CONNECTION_STREAM_ID == id ?
Http2Exception.connectionError(error, cause, fmt, args) :
new StreamException(id, error, String.format(fmt, args), cause);
} | Use if an error which can be isolated to a single stream has occurred. If the {@code id} is not
{@link Http2CodecUtil#CONNECTION_STREAM_ID} then a {@link Http2Exception.StreamException} will be returned.
Otherwise the error is considered a connection error and a {@link Http2Exception} is returned.
@param id The stream id for which the error is isolated to.
@param error The type of error as defined by the HTTP/2 specification.
@param cause The object which caused the error.
@param fmt String with the content and format for the additional debug data.
@param args Objects which fit into the format defined by {@code fmt}.
@return If the {@code id} is not
{@link Http2CodecUtil#CONNECTION_STREAM_ID} then a {@link Http2Exception.StreamException} will be returned.
Otherwise the error is considered a connection error and a {@link Http2Exception} is returned. |
public static Http2Exception headerListSizeError(int id, Http2Error error, boolean onDecode,
String fmt, Object... args) {
return CONNECTION_STREAM_ID == id ?
Http2Exception.connectionError(error, fmt, args) :
new HeaderListSizeException(id, error, String.format(fmt, args), onDecode);
} | A specific stream error resulting from failing to decode headers that exceeds the max header size list.
If the {@code id} is not {@link Http2CodecUtil#CONNECTION_STREAM_ID} then a
{@link Http2Exception.StreamException} will be returned. Otherwise the error is considered a
connection error and a {@link Http2Exception} is returned.
@param id The stream id for which the error is isolated to.
@param error The type of error as defined by the HTTP/2 specification.
@param onDecode Whether this error was caught while decoding headers
@param fmt String with the content and format for the additional debug data.
@param args Objects which fit into the format defined by {@code fmt}.
@return If the {@code id} is not
{@link Http2CodecUtil#CONNECTION_STREAM_ID} then a {@link HeaderListSizeException}
will be returned. Otherwise the error is considered a connection error and a {@link Http2Exception} is
returned. |
void add(AbstractEpollChannel ch) throws IOException {
assert inEventLoop();
int fd = ch.socket.intValue();
Native.epollCtlAdd(epollFd.intValue(), fd, ch.flags);
channels.put(fd, ch);
} | Register the given epoll with this {@link EventLoop}. |
void modify(AbstractEpollChannel ch) throws IOException {
assert inEventLoop();
Native.epollCtlMod(epollFd.intValue(), ch.socket.intValue(), ch.flags);
} | The flags of the given epoll was modified so update the registration |
void remove(AbstractEpollChannel ch) throws IOException {
assert inEventLoop();
if (ch.isOpen()) {
int fd = ch.socket.intValue();
if (channels.remove(fd) != null) {
// Remove the epoll. This is only needed if it's still open as otherwise it will be automatically
// removed once the file-descriptor is closed.
Native.epollCtlDel(epollFd.intValue(), ch.fd().intValue());
}
}
} | Deregister the given epoll from this {@link EventLoop}. |
void handleLoopException(Throwable t) {
logger.warn("Unexpected exception in the selector loop.", t);
// Prevent possible consecutive immediate failures that lead to
// excessive CPU consumption.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore.
}
} | Visible only for testing! |
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isRegistered()) {
// This should always be true with our current DefaultChannelPipeline implementation.
// The good thing about calling initChannel(...) in handlerAdded(...) is that there will be no ordering
// surprises if a ChannelInitializer will add another ChannelInitializer. This is as all handlers
// will be added in the expected order.
if (initChannel(ctx)) {
// We are done with init the Channel, removing the initializer now.
removeState(ctx);
}
}
} | {@inheritDoc} If override this method ensure you call super! |
public static <T> T checkNotNull(T arg, String text) {
if (arg == null) {
throw new NullPointerException(text);
}
return arg;
} | Checks that the given argument is not null. If it is, throws {@link NullPointerException}.
Otherwise, returns the argument. |
public static <T> T[] checkNonEmpty(T[] array, String name) {
checkNotNull(array, name);
checkPositive(array.length, name + ".length");
return array;
} | Checks that the given argument is neither null nor empty.
If it is, throws {@link NullPointerException} or {@link IllegalArgumentException}.
Otherwise, returns the argument. |
public static <T extends Collection<?>> T checkNonEmpty(T collection, String name) {
checkNotNull(collection, name);
checkPositive(collection.size(), name + ".size");
return collection;
} | Checks that the given argument is neither null nor empty.
If it is, throws {@link NullPointerException} or {@link IllegalArgumentException}.
Otherwise, returns the argument. |
protected boolean isSwitchingToNonHttp1Protocol(HttpResponse msg) {
if (msg.status().code() != HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
return false;
}
String newProtocol = msg.headers().get(HttpHeaderNames.UPGRADE);
return newProtocol == null ||
!newProtocol.contains(HttpVersion.HTTP_1_0.text()) &&
!newProtocol.contains(HttpVersion.HTTP_1_1.text());
} | Returns true if the server switched to a different protocol than HTTP/1.0 or HTTP/1.1, e.g. HTTP/2 or Websocket.
Returns false if the upgrade happened in a different layer, e.g. upgrade from HTTP/1.1 to HTTP/1.1 over TLS. |
public static SpdySessionStatus valueOf(int code) {
switch (code) {
case 0:
return OK;
case 1:
return PROTOCOL_ERROR;
case 2:
return INTERNAL_ERROR;
}
return new SpdySessionStatus(code, "UNKNOWN (" + code + ')');
} | Returns the {@link SpdySessionStatus} 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. |
static int mask(Class<? extends ChannelHandler> clazz) {
// Try to obtain the mask from the cache first. If this fails calculate it and put it in the cache for fast
// lookup in the future.
Map<Class<? extends ChannelHandler>, Integer> cache = MASKS.get();
Integer mask = cache.get(clazz);
if (mask == null) {
mask = mask0(clazz);
cache.put(clazz, mask);
}
return mask;
} | Return the {@code executionMask}. |
private static int mask0(Class<? extends ChannelHandler> handlerType) {
int mask = MASK_EXCEPTION_CAUGHT;
try {
if (ChannelInboundHandler.class.isAssignableFrom(handlerType)) {
mask |= MASK_ALL_INBOUND;
if (isSkippable(handlerType, "channelRegistered", ChannelHandlerContext.class)) {
mask &= ~MASK_CHANNEL_REGISTERED;
}
if (isSkippable(handlerType, "channelUnregistered", ChannelHandlerContext.class)) {
mask &= ~MASK_CHANNEL_UNREGISTERED;
}
if (isSkippable(handlerType, "channelActive", ChannelHandlerContext.class)) {
mask &= ~MASK_CHANNEL_ACTIVE;
}
if (isSkippable(handlerType, "channelInactive", ChannelHandlerContext.class)) {
mask &= ~MASK_CHANNEL_INACTIVE;
}
if (isSkippable(handlerType, "channelRead", ChannelHandlerContext.class, Object.class)) {
mask &= ~MASK_CHANNEL_READ;
}
if (isSkippable(handlerType, "channelReadComplete", ChannelHandlerContext.class)) {
mask &= ~MASK_CHANNEL_READ_COMPLETE;
}
if (isSkippable(handlerType, "channelWritabilityChanged", ChannelHandlerContext.class)) {
mask &= ~MASK_CHANNEL_WRITABILITY_CHANGED;
}
if (isSkippable(handlerType, "userEventTriggered", ChannelHandlerContext.class, Object.class)) {
mask &= ~MASK_USER_EVENT_TRIGGERED;
}
}
if (ChannelOutboundHandler.class.isAssignableFrom(handlerType)) {
mask |= MASK_ALL_OUTBOUND;
if (isSkippable(handlerType, "bind", ChannelHandlerContext.class,
SocketAddress.class, ChannelPromise.class)) {
mask &= ~MASK_BIND;
}
if (isSkippable(handlerType, "connect", ChannelHandlerContext.class, SocketAddress.class,
SocketAddress.class, ChannelPromise.class)) {
mask &= ~MASK_CONNECT;
}
if (isSkippable(handlerType, "disconnect", ChannelHandlerContext.class, ChannelPromise.class)) {
mask &= ~MASK_DISCONNECT;
}
if (isSkippable(handlerType, "close", ChannelHandlerContext.class, ChannelPromise.class)) {
mask &= ~MASK_CLOSE;
}
if (isSkippable(handlerType, "deregister", ChannelHandlerContext.class, ChannelPromise.class)) {
mask &= ~MASK_DEREGISTER;
}
if (isSkippable(handlerType, "read", ChannelHandlerContext.class)) {
mask &= ~MASK_READ;
}
if (isSkippable(handlerType, "write", ChannelHandlerContext.class,
Object.class, ChannelPromise.class)) {
mask &= ~MASK_WRITE;
}
if (isSkippable(handlerType, "flush", ChannelHandlerContext.class)) {
mask &= ~MASK_FLUSH;
}
}
if (isSkippable(handlerType, "exceptionCaught", ChannelHandlerContext.class, Throwable.class)) {
mask &= ~MASK_EXCEPTION_CAUGHT;
}
} catch (Exception e) {
// Should never reach here.
PlatformDependent.throwException(e);
}
return mask;
} | Calculate the {@code executionMask}. |
public static ByteBuf toByteBuf(InputStream input) throws IOException {
ByteBuf buf = Unpooled.buffer();
int n = 0;
do {
n = buf.writeBytes(input, BLOCK_SIZE);
} while (n > 0);
return buf;
} | Reads an InputStream into a byte array.
@param input the InputStream.
@return a byte array representation of the InputStream.
@throws IOException if an I/O exception of some sort happens while reading the InputStream. |
protected DnsRecord decodeRecord(
String name, DnsRecordType type, int dnsClass, long timeToLive,
ByteBuf in, int offset, int length) throws Exception {
// DNS message compression means that domain names may contain "pointers" to other positions in the packet
// to build a full message. This means the indexes are meaningful and we need the ability to reference the
// indexes un-obstructed, and thus we cannot use a slice here.
// See https://www.ietf.org/rfc/rfc1035 [4.1.4. Message compression]
if (type == DnsRecordType.PTR) {
return new DefaultDnsPtrRecord(
name, dnsClass, timeToLive, decodeName0(in.duplicate().setIndex(offset, offset + length)));
}
return new DefaultDnsRawRecord(
name, type, dnsClass, timeToLive, in.retainedDuplicate().setIndex(offset, offset + length));
} | Decodes a record from the information decoded so far by {@link #decodeRecord(ByteBuf)}.
@param name the domain name of the record
@param type the type of the record
@param dnsClass the class of the record
@param timeToLive the TTL of the record
@param in the {@link ByteBuf} that contains the RDATA
@param offset the start offset of the RDATA in {@code in}
@param length the length of the RDATA
@return a {@link DnsRawRecord}. Override this method to decode RDATA and return other record implementation. |
public static String decodeName(ByteBuf in) {
int position = -1;
int checked = 0;
final int end = in.writerIndex();
final int readable = in.readableBytes();
// Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
// some servers do not respect this for empty names. So just workaround this and return an empty name in this
// case.
//
// See:
// - https://github.com/netty/netty/issues/5014
// - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
if (readable == 0) {
return ROOT;
}
final StringBuilder name = new StringBuilder(readable << 1);
while (in.isReadable()) {
final int len = in.readUnsignedByte();
final boolean pointer = (len & 0xc0) == 0xc0;
if (pointer) {
if (position == -1) {
position = in.readerIndex() + 1;
}
if (!in.isReadable()) {
throw new CorruptedFrameException("truncated pointer in a name");
}
final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
if (next >= end) {
throw new CorruptedFrameException("name has an out-of-range pointer");
}
in.readerIndex(next);
// check for loops
checked += 2;
if (checked >= end) {
throw new CorruptedFrameException("name contains a loop.");
}
} else if (len != 0) {
if (!in.isReadable(len)) {
throw new CorruptedFrameException("truncated label in a name");
}
name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
in.skipBytes(len);
} else { // len == 0
break;
}
}
if (position != -1) {
in.readerIndex(position);
}
if (name.length() == 0) {
return ROOT;
}
if (name.charAt(name.length() - 1) != '.') {
name.append('.');
}
return name.toString();
} | Retrieves a domain name given a buffer containing a DNS packet. If the
name contains a pointer, the position of the buffer will be set to
directly after the pointer's index after the name has been read.
@param in the byte buffer containing the DNS packet
@return the domain name for an entry |
public static Throwable trySetAccessible(AccessibleObject object, boolean checkAccessible) {
if (checkAccessible && !PlatformDependent0.isExplicitTryReflectionSetAccessible()) {
return new UnsupportedOperationException("Reflective setAccessible(true) disabled");
}
try {
object.setAccessible(true);
return null;
} catch (SecurityException e) {
return e;
} catch (RuntimeException e) {
return handleInaccessibleObjectException(e);
}
} | Try to call {@link AccessibleObject#setAccessible(boolean)} but will catch any {@link SecurityException} and
{@link java.lang.reflect.InaccessibleObjectException} and return it.
The caller must check if it returns {@code null} and if not handle the returned exception. |
static byte[] shortToBytes(short value) {
byte[] bytes = new byte[2];
if (PlatformDependent.BIG_ENDIAN_NATIVE_ORDER) {
bytes[1] = (byte) ((value >> 8) & 0xff);
bytes[0] = (byte) (value & 0xff);
} else {
bytes[0] = (byte) ((value >> 8) & 0xff);
bytes[1] = (byte) (value & 0xff);
}
return bytes;
} | Returns a {@code byte[]} of {@code short} value. This is opposite of {@code makeShort()}. |
protected final ByteBuf newDirectBuffer(ByteBuf buf) {
final int readableBytes = buf.readableBytes();
if (readableBytes == 0) {
ReferenceCountUtil.safeRelease(buf);
return Unpooled.EMPTY_BUFFER;
}
final ByteBufAllocator alloc = alloc();
if (alloc.isDirectBufferPooled()) {
ByteBuf directBuf = alloc.directBuffer(readableBytes);
directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
ReferenceCountUtil.safeRelease(buf);
return directBuf;
}
final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer();
if (directBuf != null) {
directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
ReferenceCountUtil.safeRelease(buf);
return directBuf;
}
// Allocating and deallocating an unpooled direct buffer is very expensive; give up.
return buf;
} | Returns an off-heap copy of the specified {@link ByteBuf}, and releases the original one.
Note that this method does not create an off-heap copy if the allocation / deallocation cost is too high,
but just returns the original {@link ByteBuf}.. |
public static <K, V> List<String> getAllAsString(Headers<K, V, ?> headers, K name) {
final List<V> allNames = headers.getAll(name);
return new AbstractList<String>() {
@Override
public String get(int index) {
V value = allNames.get(index);
return value != null ? value.toString() : null;
}
@Override
public int size() {
return allNames.size();
}
};
} | {@link Headers#get(Object)} and convert each element of {@link List} to a {@link String}.
@param name the name of the header to retrieve
@return a {@link List} of header values or an empty {@link List} if no values are found. |
public static <K, V> String getAsString(Headers<K, V, ?> headers, K name) {
V orig = headers.get(name);
return orig != null ? orig.toString() : null;
} | {@link Headers#get(Object)} and convert the result to a {@link String}.
@param headers the headers to get the {@code name} from
@param name the name of the header to retrieve
@return the first header value if the header is found. {@code null} if there's no such entry. |
public static Iterator<Entry<String, String>> iteratorAsString(
Iterable<Entry<CharSequence, CharSequence>> headers) {
return new StringEntryIterator(headers.iterator());
} | {@link Headers#iterator()} which converts each {@link Entry}'s key and value to a {@link String}. |
public static Set<String> namesAsString(Headers<CharSequence, CharSequence, ?> headers) {
return new CharSequenceDelegatingStringSet(headers.names());
} | {@link Headers#names()} and convert each element of {@link Set} to a {@link String}.
@param headers the headers to get the names from
@return a {@link Set} of header values or an empty {@link Set} if no values are found. |
public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException {
if (unit == null) {
throw new NullPointerException("unit");
}
final Thread thread = this.thread;
if (thread == null) {
throw new IllegalStateException("thread was not started");
}
thread.join(unit.toMillis(timeout));
return !thread.isAlive();
} | Waits until the worker thread of this executor has no tasks left in its task queue and terminates itself.
Because a new worker thread will be started again when a new task is submitted, this operation is only useful
when you want to ensure that the worker thread is terminated <strong>after</strong> your application is shut
down and there's no chance of submitting a new task afterwards.
@return {@code true} if and only if the worker thread has been terminated |
@SuppressWarnings({ "unchecked", "rawtypes" })
public void add(Future future) {
checkAddAllowed();
checkInEventLoop();
++expectedCount;
future.addListener(listener);
} | Adds a new future to be combined. New futures may be added until an aggregate promise is added via the
{@link PromiseCombiner#finish(Promise)} method.
@param future the future to add to this promise combiner |
public void finish(Promise<Void> aggregatePromise) {
ObjectUtil.checkNotNull(aggregatePromise, "aggregatePromise");
checkInEventLoop();
if (this.aggregatePromise != null) {
throw new IllegalStateException("Already finished");
}
this.aggregatePromise = aggregatePromise;
if (doneCount == expectedCount) {
tryPromise();
}
} | <p>Sets the promise to be notified when all combined futures have finished. If all combined futures succeed,
then the aggregate promise will succeed. If one or more combined futures fails, then the aggregate promise will
fail with the cause of one of the failed futures. If more than one combined future fails, then exactly which
failure will be assigned to the aggregate promise is undefined.</p>
<p>After this method is called, no more futures may be added via the {@link PromiseCombiner#add(Future)} or
{@link PromiseCombiner#addAll(Future[])} methods.</p>
@param aggregatePromise the promise to notify when all combined futures have finished |
public static File getFile(Class resourceClass, String fileName) {
try {
return new File(URLDecoder.decode(resourceClass.getResource(fileName).getFile(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
return new File(resourceClass.getResource(fileName).getFile());
}
} | Returns a {@link File} named {@code fileName} associated with {@link Class} {@code resourceClass} .
@param resourceClass The associated class
@param fileName The file name
@return The file named {@code fileName} associated with {@link Class} {@code resourceClass} . |
void createGlobalTrafficCounter(ScheduledExecutorService executor) {
if (executor == null) {
throw new NullPointerException("executor");
}
TrafficCounter tc = new TrafficCounter(this, executor, "GlobalTC", checkInterval);
setTrafficCounter(tc);
tc.start();
} | Create the global TrafficCounter. |
public ChannelFuture handshake(Channel channel) {
if (channel == null) {
throw new NullPointerException("channel");
}
return handshake(channel, channel.newPromise());
} | Begins the opening handshake
@param channel
Channel |
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
FullHttpRequest request = newHandshakeRequest();
HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
if (decoder == null) {
HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
if (codec == null) {
promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
"a HttpResponseDecoder or HttpClientCodec"));
return promise;
}
}
channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
ChannelPipeline p = future.channel().pipeline();
ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
}
if (ctx == null) {
promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
"a HttpRequestEncoder or HttpClientCodec"));
return;
}
p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
}
});
return promise;
} | Begins the opening handshake
@param channel
Channel
@param promise
the {@link ChannelPromise} to be notified when the opening handshake is sent |
public final void finishHandshake(Channel channel, FullHttpResponse response) {
verify(response);
// Verify the subprotocol that we received from the server.
// This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol
String receivedProtocol = response.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null;
String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : "";
boolean protocolValid = false;
if (expectedProtocol.isEmpty() && receivedProtocol == null) {
// No subprotocol required and none received
protocolValid = true;
setActualSubprotocol(expectedSubprotocol); // null or "" - we echo what the user requested
} else if (!expectedProtocol.isEmpty() && receivedProtocol != null && !receivedProtocol.isEmpty()) {
// We require a subprotocol and received one -> verify it
for (String protocol : expectedProtocol.split(",")) {
if (protocol.trim().equals(receivedProtocol)) {
protocolValid = true;
setActualSubprotocol(receivedProtocol);
break;
}
}
} // else mixed cases - which are all errors
if (!protocolValid) {
throw new WebSocketHandshakeException(String.format(
"Invalid subprotocol. Actual: %s. Expected one of: %s",
receivedProtocol, expectedSubprotocol));
}
setHandshakeComplete();
final ChannelPipeline p = channel.pipeline();
// Remove decompressor from pipeline if its in use
HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
if (decompressor != null) {
p.remove(decompressor);
}
// Remove aggregator if present before
HttpObjectAggregator aggregator = p.get(HttpObjectAggregator.class);
if (aggregator != null) {
p.remove(aggregator);
}
ChannelHandlerContext ctx = p.context(HttpResponseDecoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
if (ctx == null) {
throw new IllegalStateException("ChannelPipeline does not contain " +
"a HttpRequestEncoder or HttpClientCodec");
}
final HttpClientCodec codec = (HttpClientCodec) ctx.handler();
// Remove the encoder part of the codec as the user may start writing frames after this method returns.
codec.removeOutboundHandler();
p.addAfter(ctx.name(), "ws-decoder", newWebsocketDecoder());
// Delay the removal of the decoder so the user can setup the pipeline if needed to handle
// WebSocketFrame messages.
// See https://github.com/netty/netty/issues/4533
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
p.remove(codec);
}
});
} else {
if (p.get(HttpRequestEncoder.class) != null) {
// Remove the encoder part of the codec as the user may start writing frames after this method returns.
p.remove(HttpRequestEncoder.class);
}
final ChannelHandlerContext context = ctx;
p.addAfter(context.name(), "ws-decoder", newWebsocketDecoder());
// Delay the removal of the decoder so the user can setup the pipeline if needed to handle
// WebSocketFrame messages.
// See https://github.com/netty/netty/issues/4533
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
p.remove(context.handler());
}
});
}
} | Validates and finishes the opening handshake initiated by {@link #handshake}}.
@param channel
Channel
@param response
HTTP response containing the closing handshake details |
public final ChannelFuture processHandshake(final Channel channel, HttpResponse response) {
return processHandshake(channel, response, channel.newPromise());
} | Process the opening handshake initiated by {@link #handshake}}.
@param channel
Channel
@param response
HTTP response containing the closing handshake details
@return future
the {@link ChannelFuture} which is notified once the handshake completes. |
public final ChannelFuture processHandshake(final Channel channel, HttpResponse response,
final ChannelPromise promise) {
if (response instanceof FullHttpResponse) {
try {
finishHandshake(channel, (FullHttpResponse) response);
promise.setSuccess();
} catch (Throwable cause) {
promise.setFailure(cause);
}
} else {
ChannelPipeline p = channel.pipeline();
ChannelHandlerContext ctx = p.context(HttpResponseDecoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
if (ctx == null) {
return promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
"a HttpResponseDecoder or HttpClientCodec"));
}
}
// Add aggregator and ensure we feed the HttpResponse so it is aggregated. A limit of 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<FullHttpResponse>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
// Remove ourself and do the actual handshake
ctx.pipeline().remove(this);
try {
finishHandshake(channel, msg);
promise.setSuccess();
} catch (Throwable cause) {
promise.setFailure(cause);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// Remove ourself and fail the handshake promise.
ctx.pipeline().remove(this);
promise.setFailure(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(response));
} catch (Throwable cause) {
promise.setFailure(cause);
}
}
return promise;
} | Process the opening handshake initiated by {@link #handshake}}.
@param channel
Channel
@param response
HTTP response containing the closing handshake details
@param promise
the {@link ChannelPromise} to notify once the handshake completes.
@return future
the {@link ChannelFuture} which is notified once the handshake completes. |
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame) {
if (channel == null) {
throw new NullPointerException("channel");
}
return close(channel, frame, channel.newPromise());
} | Performs the closing handshake
@param channel
Channel
@param frame
Closing Frame that was received |
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) {
if (channel == null) {
throw new NullPointerException("channel");
}
channel.writeAndFlush(frame, promise);
applyForceCloseTimeout(channel, promise);
return promise;
} | 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 |
static String rawPath(URI wsURL) {
String path = wsURL.getRawPath();
String query = wsURL.getRawQuery();
if (query != null && !query.isEmpty()) {
path = path + '?' + query;
}
return path == null || path.isEmpty() ? "/" : path;
} | Return the constructed raw path for the give {@link URI}. |
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
String command = (String) msg;
if (command.startsWith("get ")) {
String keyString = command.substring("get ".length());
ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8));
BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest(key);
req.setOpcode(BinaryMemcacheOpcodes.GET);
ctx.write(req, promise);
} else if (command.startsWith("set ")) {
String[] parts = command.split(" ", 3);
if (parts.length < 3) {
throw new IllegalArgumentException("Malformed Command: " + command);
}
String keyString = parts[1];
String value = parts[2];
ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8));
ByteBuf content = Unpooled.wrappedBuffer(value.getBytes(CharsetUtil.UTF_8));
ByteBuf extras = ctx.alloc().buffer(8);
extras.writeZero(8);
BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest(key, extras, content);
req.setOpcode(BinaryMemcacheOpcodes.SET);
ctx.write(req, promise);
} else {
throw new IllegalStateException("Unknown Message: " + msg);
}
} | Transforms basic string requests to binary memcache requests |
@Deprecated
public static String getHeader(HttpMessage message, CharSequence name, String defaultValue) {
return message.headers().get(name, defaultValue);
} | @deprecated Use {@link #get(CharSequence, String)} instead.
Returns the header value with the specified header name. If there are
more than one header value for the specified header name, the first
value is returned.
@return the header value or the {@code defaultValue} if there is no such
header |
@Deprecated
public static void setHeader(HttpMessage message, String name, Object value) {
message.headers().set(name, value);
} | @deprecated Use {@link #set(CharSequence, Object)} instead.
@see #setHeader(HttpMessage, CharSequence, Object) |
@Deprecated
public static void setHeader(HttpMessage message, String name, Iterable<?> values) {
message.headers().set(name, values);
} | @deprecated Use {@link #set(CharSequence, Iterable)} instead.
@see #setHeader(HttpMessage, CharSequence, Iterable) |
@Deprecated
public static void addHeader(HttpMessage message, String name, Object value) {
message.headers().add(name, value);
} | @deprecated Use {@link #add(CharSequence, Object)} instead.
@see #addHeader(HttpMessage, CharSequence, Object) |
@Deprecated
public static void removeHeader(HttpMessage message, String name) {
message.headers().remove(name);
} | @deprecated Use {@link #remove(CharSequence)} instead.
@see #removeHeader(HttpMessage, CharSequence) |
@Deprecated
public static void removeHeader(HttpMessage message, CharSequence name) {
message.headers().remove(name);
} | @deprecated Use {@link #remove(CharSequence)} instead.
Removes the header with the specified name. |
@Deprecated
public static int getIntHeader(HttpMessage message, String name) {
return getIntHeader(message, (CharSequence) name);
} | @deprecated Use {@link #getInt(CharSequence)} instead.
@see #getIntHeader(HttpMessage, CharSequence) |
@Deprecated
public static int getIntHeader(HttpMessage message, CharSequence name) {
String value = message.headers().get(name);
if (value == null) {
throw new NumberFormatException("header not found: " + name);
}
return Integer.parseInt(value);
} | @deprecated Use {@link #getInt(CharSequence)} instead.
Returns the integer header value with the specified header name. If
there are more than one header value for the specified header name, the
first value is returned.
@return the header value
@throws NumberFormatException
if there is no such header or the header value is not a number |
@Deprecated
public static int getIntHeader(HttpMessage message, String name, int defaultValue) {
return message.headers().getInt(name, defaultValue);
} | @deprecated Use {@link #getInt(CharSequence, int)} instead.
@see #getIntHeader(HttpMessage, CharSequence, int) |
@Deprecated
public static void setIntHeader(HttpMessage message, String name, int value) {
message.headers().setInt(name, value);
} | @deprecated Use {@link #setInt(CharSequence, int)} instead.
@see #setIntHeader(HttpMessage, CharSequence, int) |
@Deprecated
public static void setIntHeader(HttpMessage message, String name, Iterable<Integer> values) {
message.headers().set(name, values);
} | @deprecated Use {@link #set(CharSequence, Iterable)} instead.
@see #setIntHeader(HttpMessage, CharSequence, Iterable) |
@Deprecated
public static void addIntHeader(HttpMessage message, String name, int value) {
message.headers().add(name, value);
} | @deprecated Use {@link #add(CharSequence, Iterable)} instead.
@see #addIntHeader(HttpMessage, CharSequence, int) |
@Deprecated
public static void addIntHeader(HttpMessage message, CharSequence name, int value) {
message.headers().addInt(name, value);
} | @deprecated Use {@link #addInt(CharSequence, int)} instead.
Adds a new integer header with the specified name and value. |
@Deprecated
public static Date getDateHeader(HttpMessage message, String name) throws ParseException {
return getDateHeader(message, (CharSequence) name);
} | @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
@see #getDateHeader(HttpMessage, CharSequence) |
@Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name) throws ParseException {
String value = message.headers().get(name);
if (value == null) {
throw new ParseException("header not found: " + name, 0);
}
Date date = DateFormatter.parseHttpDate(value);
if (date == null) {
throw new ParseException("header can't be parsed into a Date: " + value, 0);
}
return date;
} | @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
Returns the date header value with the specified header name. If
there are more than one header value for the specified header name, the
first value is returned.
@return the header value
@throws ParseException
if there is no such header or the header value is not a formatted date |
@Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name, Date defaultValue) {
final String value = getHeader(message, name);
Date date = DateFormatter.parseHttpDate(value);
return date != null ? date : defaultValue;
} | @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
Returns the date header value with the specified header name. If
there are more than one header value for the specified header name, the
first value is returned.
@return the header value or the {@code defaultValue} if there is no such
header or the header value is not a formatted date |
@Deprecated
public static void setDateHeader(HttpMessage message, String name, Date value) {
setDateHeader(message, (CharSequence) name, value);
} | @deprecated Use {@link #set(CharSequence, Object)} instead.
@see #setDateHeader(HttpMessage, CharSequence, Date) |
@Deprecated
public static void setDateHeader(HttpMessage message, CharSequence name, Date value) {
if (value != null) {
message.headers().set(name, DateFormatter.format(value));
} else {
message.headers().set(name, null);
}
} | @deprecated Use {@link #set(CharSequence, Object)} instead.
Sets a new date header with the specified name and value. If there
is an existing header with the same name, the existing header is removed.
The specified value is formatted as defined in
<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a> |
@Deprecated
public static void setDateHeader(HttpMessage message, String name, Iterable<Date> values) {
message.headers().set(name, values);
} | @deprecated Use {@link #set(CharSequence, Iterable)} instead.
@see #setDateHeader(HttpMessage, CharSequence, Iterable) |
@Deprecated
public static void addDateHeader(HttpMessage message, String name, Date value) {
message.headers().add(name, value);
} | @deprecated Use {@link #add(CharSequence, Object)} instead.
@see #addDateHeader(HttpMessage, CharSequence, Date) |
@Deprecated
public static String getHost(HttpMessage message) {
return message.headers().get(HttpHeaderNames.HOST);
} | @deprecated Use {@link #get(CharSequence)} instead.
Returns the value of the {@code "Host"} header. |
@Deprecated
public static void setHost(HttpMessage message, String value) {
message.headers().set(HttpHeaderNames.HOST, value);
} | @deprecated Use {@link #set(CharSequence, Object)} instead.
@see #setHost(HttpMessage, CharSequence) |
@Deprecated
public static Date getDate(HttpMessage message) throws ParseException {
return getDateHeader(message, HttpHeaderNames.DATE);
} | @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
Returns the value of the {@code "Date"} header.
@throws ParseException
if there is no such header or the header value is not a formatted date |
@Deprecated
public static Date getDate(HttpMessage message, Date defaultValue) {
return getDateHeader(message, HttpHeaderNames.DATE, defaultValue);
} | @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
Returns the value of the {@code "Date"} header. If there is no such
header or the header is not a formatted date, the {@code defaultValue}
is returned. |
@Deprecated
public static void setDate(HttpMessage message, Date value) {
message.headers().set(HttpHeaderNames.DATE, value);
} | @deprecated Use {@link #set(CharSequence, Object)} instead.
Sets the {@code "Date"} header. |
public String get(CharSequence name, String defaultValue) {
String value = get(name);
if (value == null) {
return defaultValue;
}
return value;
} | Returns the value of a header with the specified name. If there are
more than one values for the specified name, the first value is returned.
@param name The name of the header to search
@return The first header value or {@code defaultValue} if there is no such header |
public HttpHeaders add(CharSequence name, Object value) {
return add(name.toString(), value);
} | Adds a new header with the specified name and value.
If the specified value is not a {@link String}, it is converted
into a {@link String} by {@link Object#toString()}, except in the cases
of {@link Date} and {@link Calendar}, which are formatted to the date
format defined in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>.
@param name The name of the header being added
@param value The value of the header being added
@return {@code this} |
public HttpHeaders add(CharSequence name, Iterable<?> values) {
return add(name.toString(), values);
} | Adds a new header with the specified name and values.
This getMethod can be represented approximately as the following code:
<pre>
for (Object v: values) {
if (v == null) {
break;
}
headers.add(name, v);
}
</pre>
@param name The name of the headers being set
@param values The values of the headers being set
@return {@code this} |
public HttpHeaders add(HttpHeaders headers) {
if (headers == null) {
throw new NullPointerException("headers");
}
for (Map.Entry<String, String> e: headers) {
add(e.getKey(), e.getValue());
}
return this;
} | Adds all header entries of the specified {@code headers}.
@return {@code this} |
public HttpHeaders set(CharSequence name, Object value) {
return set(name.toString(), value);
} | Sets a header with the specified name and value.
If there is an existing header with the same name, it is removed.
If the specified value is not a {@link String}, it is converted into a
{@link String} by {@link Object#toString()}, except for {@link Date}
and {@link Calendar}, which are formatted to the date format defined in
<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>.
@param name The name of the header being set
@param value The value of the header being set
@return {@code this} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.