下面列出了io.netty.channel.ChannelId#io.netty.util.internal.ObjectUtil 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a new instance
*
* @param sslCtx an OpenSSL {@code SSL_CTX} object
* @param alloc the {@link ByteBufAllocator} that will be used by this engine
* @param clientMode {@code true} if this is used for clients, {@code false} otherwise
* @param sessionContext the {@link OpenSslSessionContext} this {@link SSLEngine} belongs to.
*/
OpenSslEngine(long sslCtx, ByteBufAllocator alloc, String fallbackApplicationProtocol,
boolean clientMode, OpenSslSessionContext sessionContext, OpenSslEngineMap engineMap) {
OpenSsl.ensureAvailability();
if (sslCtx == 0) {
throw new NullPointerException("sslCtx");
}
this.alloc = ObjectUtil.checkNotNull(alloc, "alloc");
ssl = SSL.newSSL(sslCtx, !clientMode);
networkBIO = SSL.makeNetworkBIO(ssl);
this.fallbackApplicationProtocol = fallbackApplicationProtocol;
this.clientMode = clientMode;
this.sessionContext = sessionContext;
this.engineMap = engineMap;
}
@Override
public void putValue(String name, Object value) {
ObjectUtil.checkNotNull(name, "name");
ObjectUtil.checkNotNull(value, "value");
Map<String, Object> values = this.values;
if (values == null) {
// Use size of 2 to keep the memory overhead small
values = this.values = new HashMap<String, Object>(2);
}
Object old = values.put(name, value);
if (value instanceof SSLSessionBindingListener) {
((SSLSessionBindingListener) value).valueBound(new SSLSessionBindingEvent(this, name));
}
notifyUnbound(old, name);
}
public static String removeSlashesAtBothEnds(String path) {
ObjectUtil.checkNotNull(path, "path");
if (path.isEmpty()) {
return path;
}
int beginIndex = 0;
while (beginIndex < path.length() && path.charAt(beginIndex) == '/') {
beginIndex++;
}
if (beginIndex == path.length()) {
return "";
}
int endIndex = path.length() - 1;
while (endIndex > beginIndex && path.charAt(endIndex) == '/') {
endIndex--;
}
return path.substring(beginIndex, endIndex + 1);
}
/**
* Sets the SSL session ticket keys of this context.设置此上下文的SSL会话票据密钥。
*/
public void setTicketKeys(OpenSslSessionTicketKey... keys) {
ObjectUtil.checkNotNull(keys, "keys");
SessionTicketKey[] ticketKeys = new SessionTicketKey[keys.length];
for (int i = 0; i < ticketKeys.length; i++) {
ticketKeys[i] = keys[i].key;
}
Lock writerLock = context.ctxLock.writeLock();
writerLock.lock();
try {
SSLContext.clearOptions(context.ctx, SSL.SSL_OP_NO_TICKET);
SSLContext.setSessionTicketKeys(context.ctx, ticketKeys);
} finally {
writerLock.unlock();
}
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
ObjectUtil.checkNotNull(command, "command");
ObjectUtil.checkNotNull(unit, "unit");
if (initialDelay < 0) {
throw new IllegalArgumentException(
String.format("initialDelay: %d (expected: >= 0)", initialDelay));
}
if (period <= 0) {
throw new IllegalArgumentException(
String.format("period: %d (expected: > 0)", period));
}
return schedule(new ScheduledFutureTask<Void>(
this, Executors.<Void>callable(command, null),
ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period)));
}
static void invokeExceptionCaught(final AbstractChannelHandlerContext next, final Throwable cause) {
ObjectUtil.checkNotNull(cause, "cause");
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeExceptionCaught(cause);
} else {
try {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeExceptionCaught(cause);
}
});
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to submit an exceptionCaught() event.", t);
logger.warn("The exceptionCaught() event that was failed to submit was:", cause);
}
}
}
}
/**
* Adds a task to be run once at the end of next (or current) {@code eventloop} iteration.
*
* @param task to be added.
* 在下一次(或当前)eventloop迭代结束时添加一个要运行一次的任务。
*/
@UnstableApi
public final void executeAfterEventLoopIteration(Runnable task) {
ObjectUtil.checkNotNull(task, "task");
if (isShutdown()) {
reject();
}
if (!tailTasks.offer(task)) {
reject(task);
}
if (wakesUpForTask(task)) {
wakeup(inEventLoop());
}
}
/**
* Creates a new instance.
*
* @param byteOrder the {@link ByteOrder} of the length field
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
* @param lengthAdjustment the compensation value to add to the value
* of the length field
* @param lengthIncludesLengthFieldLength
* if {@code true}, the length of the prepended
* length field is added to the value of the
* prepended length field.
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(
ByteOrder byteOrder, int lengthFieldLength,
int lengthAdjustment, boolean lengthIncludesLengthFieldLength) {
if (lengthFieldLength != 1 && lengthFieldLength != 2 &&
lengthFieldLength != 3 && lengthFieldLength != 4 &&
lengthFieldLength != 8) {
throw new IllegalArgumentException(
"lengthFieldLength must be either 1, 2, 3, 4, or 8: " +
lengthFieldLength);
}
ObjectUtil.checkNotNull(byteOrder, "byteOrder");
this.byteOrder = byteOrder;
this.lengthFieldLength = lengthFieldLength;
this.lengthIncludesLengthFieldLength = lengthIncludesLengthFieldLength;
this.lengthAdjustment = lengthAdjustment;
}
/**
* Creates a new customizable LZ4 encoder.创建一个新的可定制的LZ4编码器。
*
* @param factory user customizable {@link LZ4Factory} instance
* which may be JNI bindings to the original C implementation, a pure Java implementation
* or a Java implementation that uses the {@link sun.misc.Unsafe}
* @param highCompressor if {@code true} codec will use compressor which requires more memory
* and is slower but compresses more efficiently
* @param blockSize the maximum number of bytes to try to compress at once,
* must be >= 64 and <= 32 M
* @param checksum the {@link Checksum} instance to use to check data for integrity
* @param maxEncodeSize the maximum size for an encode (compressed) buffer
*/
public Lz4FrameEncoder(LZ4Factory factory, boolean highCompressor, int blockSize,
Checksum checksum, int maxEncodeSize) {
if (factory == null) {
throw new NullPointerException("factory");
}
if (checksum == null) {
throw new NullPointerException("checksum");
}
compressor = highCompressor ? factory.highCompressor() : factory.fastCompressor();
this.checksum = ByteBufChecksum.wrapChecksum(checksum);
compressionLevel = compressionLevel(blockSize);
this.blockSize = blockSize;
this.maxEncodeSize = ObjectUtil.checkPositive(maxEncodeSize, "maxEncodeSize");
finished = false;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
ObjectUtil.checkNotNull(command, "command");
ObjectUtil.checkNotNull(unit, "unit");
if (initialDelay < 0) {
throw new IllegalArgumentException(
String.format("initialDelay: %d (expected: >= 0)", initialDelay));
}
if (period <= 0) {
throw new IllegalArgumentException(
String.format("period: %d (expected: > 0)", period));
}
return schedule(new ScheduledFutureTask<Void>(
this, Executors.<Void>callable(command, null),
ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period)));
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
ObjectUtil.checkNotNull(command, "command");
ObjectUtil.checkNotNull(unit, "unit");
if (initialDelay < 0) {
throw new IllegalArgumentException(
String.format("initialDelay: %d (expected: >= 0)", initialDelay));
}
if (delay <= 0) {
throw new IllegalArgumentException(
String.format("delay: %d (expected: > 0)", delay));
}
return schedule(new ScheduledFutureTask<Void>(
this, Executors.<Void>callable(command, null),
ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), -unit.toNanos(delay)));
}
/**
* Tries to backoff when the task can not be added due restrictions for an configured amount of time. This
* is only done if the task was added from outside of the event loop which means
* {@link EventExecutor#inEventLoop()} returns {@code false}.
* 尝试在任务无法被添加时进行回退,这是对已配置的时间的适当限制。这只在从事件循环外部添加任务时完成,这意味着EventExecutor.inEventLoop()返回false。
*/
public static RejectedExecutionHandler backoff(final int retries, long backoffAmount, TimeUnit unit) {
ObjectUtil.checkPositive(retries, "retries");
final long backOffNanos = unit.toNanos(backoffAmount);
return new RejectedExecutionHandler() {
@Override
public void rejected(Runnable task, SingleThreadEventExecutor executor) {
if (!executor.inEventLoop()) {
for (int i = 0; i < retries; i++) {
// Try to wake up the executor so it will empty its task queue.
executor.wakeup(false);
LockSupport.parkNanos(backOffNanos);
if (executor.offerTask(task)) {
return;
}
}
}
// Either we tried to add the task from within the EventLoop or we was not able to add it even with
// backoff.
throw new RejectedExecutionException();
}
};
}
/**
* Creates a new instance.
*
* @param byteOrder the {@link ByteOrder} of the length field
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
* @param lengthAdjustment the compensation value to add to the value
* of the length field
* @param lengthIncludesLengthFieldLength
* if {@code true}, the length of the prepended
* length field is added to the value of the
* prepended length field.
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(
ByteOrder byteOrder, int lengthFieldLength,
int lengthAdjustment, boolean lengthIncludesLengthFieldLength) {
if (lengthFieldLength != 1 && lengthFieldLength != 2 &&
lengthFieldLength != 3 && lengthFieldLength != 4 &&
lengthFieldLength != 8) {
throw new IllegalArgumentException(
"lengthFieldLength must be either 1, 2, 3, 4, or 8: " +
lengthFieldLength);
}
ObjectUtil.checkNotNull(byteOrder, "byteOrder");
this.byteOrder = byteOrder;
this.lengthFieldLength = lengthFieldLength;
this.lengthIncludesLengthFieldLength = lengthIncludesLengthFieldLength;
this.lengthAdjustment = lengthAdjustment;
}
/**
* The maps will be wrapped in Collections.unmodifiableMap.
*/
public RouteResult(String uri, String decodedPath, Map<String, String> pathParams, Map<String, List<String>> queryParams, T target) {
this.uri = ObjectUtil.checkNotNull(uri, "uri");
this.decodedPath = ObjectUtil.checkNotNull(decodedPath, "decodedPath");
this.pathParams = Collections.unmodifiableMap(ObjectUtil.checkNotNull(pathParams, "pathParams"));
this.queryParams = Collections.unmodifiableMap(ObjectUtil.checkNotNull(queryParams, "queryParams"));
this.target = ObjectUtil.checkNotNull(target, "target");
}
@Override
public void setEnabledCipherSuites(String[] cipherSuites) {
ObjectUtil.checkNotNull(cipherSuites, "cipherSuites");
final StringBuilder buf = new StringBuilder();
for (String c: cipherSuites) {
if (c == null) {
break;
}
String converted = CipherSuiteConverter.toOpenSsl(c);
if (converted == null) {
converted = c;
}
if (!OpenSsl.isCipherSuiteAvailable(converted)) {
throw new IllegalArgumentException("unsupported cipher suite: " + c + '(' + converted + ')');
}
buf.append(converted);
buf.append(':');
}
if (buf.length() == 0) {
throw new IllegalArgumentException("empty cipher suites");
}
buf.setLength(buf.length() - 1);
final String cipherSuiteSpec = buf.toString();
try {
SSL.setCipherSuites(ssl, cipherSuiteSpec);
} catch (Exception e) {
throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec, e);
}
}
/**
* The pattern must not contain query, example:
* {@code constant1/constant2?foo=bar}.
*
* <p>The pattern will be stored without slashes at both ends.
*/
public PathPattern(String pattern) {
if (pattern.contains("?")) {
throw new IllegalArgumentException("Path pattern must not contain query");
}
this.pattern = removeSlashesAtBothEnds(ObjectUtil.checkNotNull(pattern, "pattern"));
this.tokens = this.pattern.split("/");
}
/**
* The pattern must not contain query, example:
* {@code constant1/constant2?foo=bar}.
*
* <p>The pattern will be stored without slashes at both ends.
*/
public PathPattern(String pattern) {
if (pattern.contains("?")) {
throw new IllegalArgumentException("Path pattern must not contain query");
}
this.pattern = removeSlashesAtBothEnds(ObjectUtil.checkNotNull(pattern, "pattern"));
this.tokens = this.pattern.split("/");
}
@Override
public void removeValue(String name) {
ObjectUtil.checkNotNull(name, "name");
Map<String, Object> values = this.values;
if (values == null) {
return;
}
Object old = values.remove(name);
notifyUnbound(old, name);
}
/**
* The pattern must not contain query, example:
* {@code constant1/constant2?foo=bar}.
*
* <p>The pattern will be stored without slashes at both ends.
*/
public PathPattern(String pattern) {
if (pattern.contains("?")) {
throw new IllegalArgumentException("Path pattern must not contain query");
}
this.pattern = removeSlashesAtBothEnds(ObjectUtil.checkNotNull(pattern, "pattern"));
this.tokens = this.pattern.split("/");
}
/**
* Adds a parameter with the specified name and value to this encoder.向此编码器添加具有指定名称和值的参数。
*/
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);
}
}
public MqttFixedHeader(
MqttMessageType messageType,
boolean isDup,
MqttQoS qosLevel,
boolean isRetain,
int remainingLength) {
this.messageType = ObjectUtil.checkNotNull(messageType, "messageType");
this.isDup = isDup;
this.qosLevel = ObjectUtil.checkNotNull(qosLevel, "qosLevel");
this.isRetain = isRetain;
this.remainingLength = remainingLength;
}
DnsNameResolverContext(DnsNameResolver parent,
String hostname,
DnsRecord[] additionals,
DnsCache resolveCache,
DnsServerAddressStream nameServerAddrs) {
this.parent = parent;
this.hostname = hostname;
this.additionals = additionals;
this.resolveCache = resolveCache;
this.nameServerAddrs = ObjectUtil.checkNotNull(nameServerAddrs, "nameServerAddrs");
maxAllowedQueries = parent.maxQueriesPerResolve();
resolvedInternetProtocolFamilies = parent.resolvedInternetProtocolFamiliesUnsafe();
allowedQueries = maxAllowedQueries;
}
/**
* Set the specific {@link AttributeKey} with the given value on every child {@link Channel}. If the value is
* {@code null} the {@link AttributeKey} is removed
*/
public <T> UkcpServerBootstrap childAttr(AttributeKey<T> childKey, T value) {
ObjectUtil.checkNotNull(childKey, "childKey");
if (value == null) {
childAttrs.remove(childKey);
} else {
childAttrs.put(childKey, value);
}
return this;
}
public ZstdEncoder(int blockSize, int maxEncodeSize) {
super(true);
compressionLevel = compressionLevel(blockSize);
this.blockSize = blockSize;
this.maxEncodeSize = ObjectUtil.checkPositive(maxEncodeSize, "maxEncodeSize");
finished = false;
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
ObjectUtil.checkNotNull(command, "command");
ObjectUtil.checkNotNull(unit, "unit");
if (delay < 0) {
throw new IllegalArgumentException(
String.format("delay: %d (expected: >= 0)", delay));
}
return schedule(new ScheduledFutureTask<Void>(
this, command, null, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay))));
}
AbstractChannelHandlerContext(DefaultChannelPipeline pipeline, EventExecutor executor, String name,
boolean inbound, boolean outbound) {
this.name = ObjectUtil.checkNotNull(name, "name");
this.pipeline = pipeline;
this.executor = executor;
this.inbound = inbound;
this.outbound = outbound;
// Its ordered if its driven by the EventLoop or the given Executor is an instanceof OrderedEventExecutor.
ordered = executor == null || executor instanceof OrderedEventExecutor;
}
static void invokeUserEventTriggered(final AbstractChannelHandlerContext next, final Object event) {
ObjectUtil.checkNotNull(event, "event");
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeUserEventTriggered(event);
} else {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeUserEventTriggered(event);
}
});
}
}
static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeChannelRead(m);
} else {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeChannelRead(m);
}
});
}
}
protected DefaultChannelPipeline(Channel channel) {
this.channel = ObjectUtil.checkNotNull(channel, "channel");
succeededFuture = new SucceededChannelFuture(channel, null);
voidPromise = new VoidChannelPromise(channel, true);
tail = new TailContext(this);
head = new HeadContext(this);
head.next = tail;
tail.prev = head;
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
ObjectUtil.checkNotNull(callable, "callable");
ObjectUtil.checkNotNull(unit, "unit");
if (delay < 0) {
throw new IllegalArgumentException(
String.format("delay: %d (expected: >= 0)", delay));
}
return schedule(new ScheduledFutureTask<V>(
this, callable, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay))));
}