Utilize i.n.u.internal.ObjectUtil to assert Preconditions (handler) (#11170) (#11180)

Motivation:

NullChecks resulting in a NullPointerException or IllegalArgumentException, numeric ranges (>0, >=0) checks, not empty strings/arrays checks must never be anonymous but with the parameter or variable name which is checked. They must be specific and should not be done with an "OR-Logic" (if a == null || b == null) throw new NullPointerEx.

Modifications:

* import static relevant checks
* Replace manual checks with ObjectUtil methods

Result:

All checks needed are done with ObjectUtil, some exception texts are improved.

Fixes #11170
This commit is contained in:
Boris Unckel 2021-04-22 12:51:23 +02:00 committed by Norman Maurer
parent 8c12ad4cee
commit 83297ed2ba
16 changed files with 69 additions and 132 deletions

View File

@ -21,6 +21,7 @@ import java.util.List;
import javax.net.ssl.SSLEngine;
import static io.netty.handler.ssl.ApplicationProtocolUtil.toList;
import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
import static java.util.Objects.requireNonNull;
/**
@ -81,9 +82,7 @@ public final class ApplicationProtocolConfig {
if (protocol == Protocol.NONE) {
throw new IllegalArgumentException("protocol (" + Protocol.NONE + ") must not be " + Protocol.NONE + '.');
}
if (supportedProtocols.isEmpty()) {
throw new IllegalArgumentException("supportedProtocols must be not empty");
}
checkNonEmpty(supportedProtocols, "supportedProtocols");
}
/**

View File

@ -15,6 +15,8 @@
*/
package io.netty.handler.ssl;
import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
import java.util.ArrayList;
import java.util.List;
@ -38,17 +40,10 @@ final class ApplicationProtocolUtil {
List<String> result = new ArrayList<>(initialListSize);
for (String p : protocols) {
if (p == null || p.isEmpty()) {
throw new IllegalArgumentException("protocol cannot be null or empty");
}
result.add(p);
result.add(checkNonEmpty(p, "p"));
}
if (result.isEmpty()) {
throw new IllegalArgumentException("protocols cannot empty");
}
return result;
return checkNonEmpty(result, "result");
}
static List<String> toList(String... protocols) {
@ -62,16 +57,9 @@ final class ApplicationProtocolUtil {
List<String> result = new ArrayList<>(initialListSize);
for (String p : protocols) {
if (p == null || p.isEmpty()) {
throw new IllegalArgumentException("protocol cannot be null or empty");
}
result.add(p);
result.add(checkNonEmpty(p, "p"));
}
if (result.isEmpty()) {
throw new IllegalArgumentException("protocols cannot empty");
}
return result;
return checkNonEmpty(result, "result");
}
}

View File

@ -16,6 +16,7 @@
package io.netty.handler.ssl;
import static java.util.Objects.requireNonNull;
import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
@ -205,9 +206,7 @@ public final class OpenSslX509KeyManagerFactory extends KeyManagerFactory {
destroy();
}
}
if (materialMap.isEmpty()) {
throw new IllegalArgumentException("aliases must be non-empty");
}
checkNonEmpty(materialMap, "materialMap");
}
@Override

View File

@ -16,6 +16,7 @@
package io.netty.handler.ssl;
import static java.util.Objects.requireNonNull;
import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
import java.math.BigInteger;
import java.security.Principal;
@ -56,9 +57,7 @@ public final class PemX509Certificate extends X509Certificate implements PemEnco
static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect,
X509Certificate... chain) throws CertificateEncodingException {
if (chain == null || chain.length == 0) {
throw new IllegalArgumentException("X.509 certificate chain can't be null or empty");
}
checkNonEmpty(chain, "chain");
// We can take a shortcut if there is only one certificate and
// it already happens to be a PemEncoded instance. This is the

View File

@ -15,6 +15,8 @@
*/
package io.netty.handler.ssl;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import io.netty.util.internal.EmptyArrays;
import javax.crypto.Mac;
@ -59,9 +61,7 @@ final class PseudoRandomFunction {
* @throws IllegalArgumentException if the algo could not be found.
*/
static byte[] hash(byte[] secret, byte[] label, byte[] seed, int length, String algo) {
if (length < 0) {
throw new IllegalArgumentException("You must provide a length greater than zero.");
}
checkPositiveOrZero(length, "length");
try {
Mac hmac = Mac.getInstance(algo);
hmac.init(new SecretKeySpec(secret, algo));

View File

@ -45,7 +45,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.Lock;
@ -64,6 +63,7 @@ import javax.net.ssl.X509TrustManager;
import static io.netty.handler.ssl.OpenSsl.DEFAULT_CIPHERS;
import static io.netty.handler.ssl.OpenSsl.availableJavaCipherSuites;
import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import static java.util.Objects.requireNonNull;
@ -530,7 +530,7 @@ public abstract class ReferenceCountedOpenSslContext extends SslContext implemen
@Deprecated
@UnstableApi
public final void setPrivateKeyMethod(OpenSslPrivateKeyMethod method) {
Objects.requireNonNull(method, "method");
requireNonNull(method, "method");
Lock writerLock = ctxLock.writeLock();
writerLock.lock();
try {
@ -848,9 +848,7 @@ public abstract class ReferenceCountedOpenSslContext extends SslContext implemen
return 0;
}
if (certChain.length == 0) {
throw new IllegalArgumentException("certChain can't be empty");
}
checkNonEmpty(certChain, "certChain");
PemEncoded pem = PemX509Certificate.toPEM(allocator, true, certChain);
try {

View File

@ -70,6 +70,8 @@ import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1_1;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1_2;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_TLS_V1_3;
import static io.netty.handler.ssl.SslUtils.SSL_RECORD_HEADER_LENGTH;
import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
import static io.netty.util.internal.ObjectUtil.checkNotNullArrayParam;
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Math.min;
import static java.util.Objects.requireNonNull;
@ -707,12 +709,8 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
public final SSLEngineResult wrap(
final ByteBuffer[] srcs, int offset, final int length, final ByteBuffer dst) throws SSLException {
// Throw required runtime exceptions
if (srcs == null) {
throw new IllegalArgumentException("srcs is null");
}
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
checkNotNullWithIAE(srcs, "srcs");
checkNotNullWithIAE(dst, "dst");
if (offset >= srcs.length || offset + length > srcs.length) {
throw new IndexOutOfBoundsException(
@ -1080,16 +1078,14 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
final ByteBuffer[] dsts, int dstsOffset, final int dstsLength) throws SSLException {
// Throw required runtime exceptions
requireNonNull(srcs, "srcs");
checkNotNullWithIAE(srcs, "srcs");
if (srcsOffset >= srcs.length
|| srcsOffset + srcsLength > srcs.length) {
throw new IndexOutOfBoundsException(
"offset: " + srcsOffset + ", length: " + srcsLength +
" (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
}
if (dsts == null) {
throw new IllegalArgumentException("dsts is null");
}
checkNotNullWithIAE(dsts, "dsts");
if (dstsOffset >= dsts.length || dstsOffset + dstsLength > dsts.length) {
throw new IndexOutOfBoundsException(
"offset: " + dstsOffset + ", length: " + dstsLength +
@ -1098,10 +1094,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
long capacity = 0;
final int dstsEndOffset = dstsOffset + dstsLength;
for (int i = dstsOffset; i < dstsEndOffset; i ++) {
ByteBuffer dst = dsts[i];
if (dst == null) {
throw new IllegalArgumentException("dsts[" + i + "] is null");
}
ByteBuffer dst = checkNotNullArrayParam(dsts[i], i, "dsts");
if (dst.isReadOnly()) {
throw new ReadOnlyBufferException();
}
@ -1111,10 +1104,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
final int srcsEndOffset = srcsOffset + srcsLength;
long len = 0;
for (int i = srcsOffset; i < srcsEndOffset; i++) {
ByteBuffer src = srcs[i];
if (src == null) {
throw new IllegalArgumentException("srcs[" + i + "] is null");
}
ByteBuffer src = checkNotNullArrayParam(srcs[i], i, "srcs");
len += src.remaining();
}
@ -1693,10 +1683,8 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
}
private void setEnabledProtocols0(String[] protocols, boolean cache) {
if (protocols == null) {
// This is correct from the API docs
throw new IllegalArgumentException();
}
// This is correct from the API docs
checkNotNullWithIAE(protocols, "protocols");
int minProtocolIndex = OPENSSL_OP_NO_PROTOCOLS.length;
int maxProtocolIndex = 0;
for (String p: protocols) {
@ -2343,6 +2331,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
public void putValue(String name, Object value) {
requireNonNull(name, "name");
requireNonNull(value, "value");
final Object old;
synchronized (this) {
Map<String, Object> values = this.values;

View File

@ -39,6 +39,8 @@ import java.util.Map;
import static io.netty.util.internal.EmptyArrays.EMPTY_STRINGS;
import static io.netty.util.internal.EmptyArrays.EMPTY_X509_CERTIFICATES;
import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
import static java.util.Objects.requireNonNull;
/**
@ -427,19 +429,14 @@ public final class SslContextBuilder {
*/
public SslContextBuilder keyManager(PrivateKey key, String keyPassword, X509Certificate... keyCertChain) {
if (forServer) {
requireNonNull(keyCertChain, "keyCertChain required for servers");
if (keyCertChain.length == 0) { // lgtm[java/dereferenced-value-may-be-null]
throw new IllegalArgumentException("keyCertChain must be non-empty");
}
checkNonEmpty(keyCertChain, "keyCertChain"); // lgtm[java/dereferenced-value-may-be-null]
requireNonNull(key, "key required for servers");
}
if (keyCertChain == null || keyCertChain.length == 0) {
this.keyCertChain = null;
} else {
for (X509Certificate cert: keyCertChain) {
if (cert == null) {
throw new IllegalArgumentException("keyCertChain contains null entry");
}
checkNotNullWithIAE(cert, "cert");
}
this.keyCertChain = keyCertChain.clone();
}

View File

@ -73,6 +73,7 @@ import java.util.regex.Pattern;
import static io.netty.buffer.ByteBufUtil.ensureWritableSuccess;
import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import static java.util.Objects.requireNonNull;
/**
@ -460,16 +461,11 @@ public class SslHandler extends ByteToMessageDecoder {
public void setHandshakeTimeout(long handshakeTimeout, TimeUnit unit) {
requireNonNull(unit, "unit");
setHandshakeTimeoutMillis(unit.toMillis(handshakeTimeout));
}
public void setHandshakeTimeoutMillis(long handshakeTimeoutMillis) {
if (handshakeTimeoutMillis < 0) {
throw new IllegalArgumentException(
"handshakeTimeoutMillis: " + handshakeTimeoutMillis + " (expected: >= 0)");
}
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
this.handshakeTimeoutMillis = checkPositiveOrZero(handshakeTimeoutMillis, "handshakeTimeoutMillis");
}
/**
@ -543,11 +539,8 @@ public class SslHandler extends ByteToMessageDecoder {
* See {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}.
*/
public final void setCloseNotifyFlushTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
if (closeNotifyFlushTimeoutMillis < 0) {
throw new IllegalArgumentException(
"closeNotifyFlushTimeoutMillis: " + closeNotifyFlushTimeoutMillis + " (expected: >= 0)");
}
this.closeNotifyFlushTimeoutMillis = closeNotifyFlushTimeoutMillis;
this.closeNotifyFlushTimeoutMillis = checkPositiveOrZero(closeNotifyFlushTimeoutMillis,
"closeNotifyFlushTimeoutMillis");
}
/**
@ -572,11 +565,8 @@ public class SslHandler extends ByteToMessageDecoder {
* See {@link #setCloseNotifyReadTimeout(long, TimeUnit)}.
*/
public final void setCloseNotifyReadTimeoutMillis(long closeNotifyReadTimeoutMillis) {
if (closeNotifyReadTimeoutMillis < 0) {
throw new IllegalArgumentException(
"closeNotifyReadTimeoutMillis: " + closeNotifyReadTimeoutMillis + " (expected: >= 0)");
}
this.closeNotifyReadTimeoutMillis = closeNotifyReadTimeoutMillis;
this.closeNotifyReadTimeoutMillis = checkPositiveOrZero(closeNotifyReadTimeoutMillis,
"closeNotifyReadTimeoutMillis");
}
/**

View File

@ -16,7 +16,8 @@
package io.netty.handler.ssl.util;
import io.netty.util.internal.ObjectUtil;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
import java.util.ArrayList;
import java.util.Arrays;
@ -43,7 +44,7 @@ public final class FingerprintTrustManagerFactoryBuilder {
* @param algorithm a hash algorithm
*/
FingerprintTrustManagerFactoryBuilder(String algorithm) {
this.algorithm = ObjectUtil.checkNotNull(algorithm, "algorithm");
this.algorithm = checkNotNull(algorithm, "algorithm");
}
/**
@ -53,8 +54,7 @@ public final class FingerprintTrustManagerFactoryBuilder {
* @return the same builder
*/
public FingerprintTrustManagerFactoryBuilder fingerprints(CharSequence... fingerprints) {
ObjectUtil.checkNotNull(fingerprints, "fingerprints");
return fingerprints(Arrays.asList(fingerprints));
return fingerprints(Arrays.asList(checkNotNull(fingerprints, "fingerprints")));
}
/**
@ -64,11 +64,9 @@ public final class FingerprintTrustManagerFactoryBuilder {
* @return the same builder
*/
public FingerprintTrustManagerFactoryBuilder fingerprints(Iterable<? extends CharSequence> fingerprints) {
ObjectUtil.checkNotNull(fingerprints, "fingerprints");
checkNotNull(fingerprints, "fingerprints");
for (CharSequence fingerprint : fingerprints) {
if (fingerprint == null) {
throw new IllegalArgumentException("One of the fingerprints is null");
}
checkNotNullWithIAE(fingerprint, "fingerprint");
this.fingerprints.add(fingerprint.toString());
}
return this;

View File

@ -15,6 +15,7 @@
*/
package io.netty.handler.stream;
import static io.netty.util.internal.ObjectUtil.checkPositive;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBuf;
@ -55,13 +56,8 @@ public class ChunkedNioStream implements ChunkedInput<ByteBuf> {
* {@link #readChunk(ChannelHandlerContext)} call
*/
public ChunkedNioStream(ReadableByteChannel in, int chunkSize) {
requireNonNull(in, "in");
if (chunkSize <= 0) {
throw new IllegalArgumentException("chunkSize: " + chunkSize +
" (expected: a positive integer)");
}
this.in = in;
this.chunkSize = chunkSize;
this.in = requireNonNull(in, "in");
this.chunkSize = checkPositive(chunkSize, "chunkSize");
byteBuffer = ByteBuffer.allocate(chunkSize);
}

View File

@ -15,6 +15,8 @@
*/
package io.netty.handler.stream;
import static io.netty.util.internal.ObjectUtil.checkPositive;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
@ -80,10 +82,7 @@ public class ChunkedWriteHandler implements ChannelHandler {
*/
@Deprecated
public ChunkedWriteHandler(int maxPendingWrites) {
if (maxPendingWrites <= 0) {
throw new IllegalArgumentException(
"maxPendingWrites: " + maxPendingWrites + " (expected: > 0)");
}
checkPositive(maxPendingWrites, "maxPendingWrites");
}
@Override

View File

@ -15,6 +15,8 @@
*/
package io.netty.handler.traffic;
import static io.netty.util.internal.ObjectUtil.checkPositive;
import io.netty.buffer.ByteBufConvertible;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
@ -165,15 +167,12 @@ public abstract class AbstractTrafficShapingHandler implements ChannelHandler {
* Must be positive.
*/
protected AbstractTrafficShapingHandler(long writeLimit, long readLimit, long checkInterval, long maxTime) {
if (maxTime <= 0) {
throw new IllegalArgumentException("maxTime must be positive");
}
this.maxTime = checkPositive(maxTime, "maxTime");
userDefinedWritabilityIndex = userDefinedWritabilityIndex();
this.writeLimit = writeLimit;
this.readLimit = readLimit;
this.checkInterval = checkInterval;
this.maxTime = maxTime;
}
/**
@ -347,10 +346,7 @@ public abstract class AbstractTrafficShapingHandler implements ChannelHandler {
* Must be positive.
*/
public void setMaxTimeWait(long maxTime) {
if (maxTime <= 0) {
throw new IllegalArgumentException("maxTime must be positive");
}
this.maxTime = maxTime;
this.maxTime = checkPositive(maxTime, "maxTime");
}
/**
@ -378,10 +374,7 @@ public abstract class AbstractTrafficShapingHandler implements ChannelHandler {
* Must be positive.
*/
public void setMaxWriteDelay(long maxWriteDelay) {
if (maxWriteDelay <= 0) {
throw new IllegalArgumentException("maxWriteDelay must be positive");
}
this.maxWriteDelay = maxWriteDelay;
this.maxWriteDelay = checkPositive(maxWriteDelay, "maxWriteDelay");
}
/**

View File

@ -15,6 +15,8 @@
*/
package io.netty.handler.traffic;
import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
import io.netty.handler.traffic.GlobalChannelTrafficShapingHandler.PerChannel;
import java.util.concurrent.ScheduledExecutorService;
@ -36,9 +38,7 @@ public class GlobalChannelTrafficCounter extends TrafficCounter {
public GlobalChannelTrafficCounter(GlobalChannelTrafficShapingHandler trafficShapingHandler,
ScheduledExecutorService executor, String name, long checkInterval) {
super(trafficShapingHandler, executor, name, checkInterval);
if (executor == null) {
throw new IllegalArgumentException("Executor must not be null");
}
checkNotNullWithIAE(executor, "executor");
}
/**

View File

@ -15,6 +15,10 @@
*/
package io.netty.handler.traffic;
import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
import static io.netty.util.internal.ObjectUtil.checkPositive;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import io.netty.buffer.ByteBufConvertible;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
@ -147,9 +151,7 @@ public class GlobalChannelTrafficShapingHandler extends AbstractTrafficShapingHa
void createGlobalTrafficCounter(ScheduledExecutorService executor) {
// Default
setMaxDeviation(DEFAULT_DEVIATION, DEFAULT_SLOWDOWN, DEFAULT_ACCELERATION);
if (executor == null) {
throw new IllegalArgumentException("Executor must not be null");
}
checkNotNullWithIAE(executor, "executor");
TrafficCounter tc = new GlobalChannelTrafficCounter(this, executor, "GlobalChannelTC", checkInterval);
setTrafficCounter(tc);
tc.start();
@ -299,9 +301,7 @@ public class GlobalChannelTrafficShapingHandler extends AbstractTrafficShapingHa
if (maxDeviation > MAX_DEVIATION) {
throw new IllegalArgumentException("maxDeviation must be <= " + MAX_DEVIATION);
}
if (slowDownFactor < 0) {
throw new IllegalArgumentException("slowDownFactor must be >= 0");
}
checkPositiveOrZero(slowDownFactor, "slowDownFactor");
if (accelerationFactor > 0) {
throw new IllegalArgumentException("accelerationFactor must be <= 0");
}
@ -385,10 +385,7 @@ public class GlobalChannelTrafficShapingHandler extends AbstractTrafficShapingHa
* globally for all channels before write suspended is set.
*/
public void setMaxGlobalWriteSize(long maxGlobalWriteSize) {
if (maxGlobalWriteSize <= 0) {
throw new IllegalArgumentException("maxGlobalWriteSize must be positive");
}
this.maxGlobalWriteSize = maxGlobalWriteSize;
this.maxGlobalWriteSize = checkPositive(maxGlobalWriteSize, "maxGlobalWriteSize");
}
/**

View File

@ -15,6 +15,7 @@
*/
package io.netty.handler.traffic;
import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
import static java.util.Objects.requireNonNull;
import io.netty.util.internal.logging.InternalLogger;
@ -278,15 +279,9 @@ public class TrafficCounter {
public TrafficCounter(
AbstractTrafficShapingHandler trafficShapingHandler, ScheduledExecutorService executor,
String name, long checkInterval) {
if (trafficShapingHandler == null) {
throw new IllegalArgumentException("trafficShapingHandler");
}
requireNonNull(name, "name");
this.trafficShapingHandler = trafficShapingHandler;
this.name = requireNonNull(name, "name");
this.trafficShapingHandler = checkNotNullWithIAE(trafficShapingHandler, "trafficShapingHandler");
this.executor = executor;
this.name = name;
init(checkInterval);
}