8265426: Update java.security to use instanceof pattern variable

Reviewed-by: rriggs, weijun, dfuchs
This commit is contained in:
Patrick Concannon 2021-05-07 13:42:40 +00:00
parent 3fcdc50e44
commit 86b8dc9f5b
23 changed files with 85 additions and 165 deletions

View file

@ -750,18 +750,9 @@ public final class AccessControlContext {
if (obj == this) if (obj == this)
return true; return true;
if (! (obj instanceof AccessControlContext)) return obj instanceof AccessControlContext that
return false; && equalContext(that)
&& equalLimitedContext(that);
AccessControlContext that = (AccessControlContext) obj;
if (!equalContext(that))
return false;
if (!equalLimitedContext(that))
return false;
return true;
} }
/* /*

View file

@ -364,27 +364,25 @@ final class BasicPermissionCollection
*/ */
@Override @Override
public void add(Permission permission) { public void add(Permission permission) {
if (! (permission instanceof BasicPermission)) if (!(permission instanceof BasicPermission basicPermission))
throw new IllegalArgumentException("invalid permission: "+ throw new IllegalArgumentException("invalid permission: "+
permission); permission);
if (isReadOnly()) if (isReadOnly())
throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection"); throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
BasicPermission bp = (BasicPermission) permission;
// make sure we only add new BasicPermissions of the same class // make sure we only add new BasicPermissions of the same class
// Also check null for compatibility with deserialized form from // Also check null for compatibility with deserialized form from
// previous versions. // previous versions.
if (permClass == null) { if (permClass == null) {
// adding first permission // adding first permission
permClass = bp.getClass(); permClass = basicPermission.getClass();
} else { } else {
if (bp.getClass() != permClass) if (basicPermission.getClass() != permClass)
throw new IllegalArgumentException("invalid permission: " + throw new IllegalArgumentException("invalid permission: " +
permission); permission);
} }
String canonName = bp.getCanonicalName(); String canonName = basicPermission.getCanonicalName();
perms.put(canonName, permission); perms.put(canonName, permission);
// No sync on all_allowed; staleness OK // No sync on all_allowed; staleness OK
@ -405,13 +403,11 @@ final class BasicPermissionCollection
*/ */
@Override @Override
public boolean implies(Permission permission) { public boolean implies(Permission permission) {
if (! (permission instanceof BasicPermission)) if (!(permission instanceof BasicPermission basicPermission))
return false; return false;
BasicPermission bp = (BasicPermission) permission;
// random subclasses of BasicPermission do not imply each other // random subclasses of BasicPermission do not imply each other
if (bp.getClass() != permClass) if (basicPermission.getClass() != permClass)
return false; return false;
// short circuit if the "*" Permission was added // short circuit if the "*" Permission was added
@ -422,7 +418,7 @@ final class BasicPermissionCollection
// Check for full match first. Then work our way up the // Check for full match first. Then work our way up the
// path looking for matches on a.b..* // path looking for matches on a.b..*
String path = bp.getCanonicalName(); String path = basicPermission.getCanonicalName();
//System.out.println("check "+path); //System.out.println("check "+path);
Permission x = perms.get(path); Permission x = perms.get(path);

View file

@ -126,10 +126,9 @@ public final class CodeSigner implements Serializable {
* @return true if the objects are considered equal, false otherwise. * @return true if the objects are considered equal, false otherwise.
*/ */
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null || (!(obj instanceof CodeSigner))) { if (obj == null || (!(obj instanceof CodeSigner that))) {
return false; return false;
} }
CodeSigner that = (CodeSigner)obj;
if (this == that) { if (this == that) {
return true; return true;

View file

@ -34,6 +34,8 @@ import java.util.Hashtable;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.security.cert.*; import java.security.cert.*;
import java.util.Objects;
import sun.net.util.URLUtil; import sun.net.util.URLUtil;
import sun.security.util.IOUtils; import sun.security.util.IOUtils;
@ -157,22 +159,9 @@ public class CodeSource implements java.io.Serializable {
return true; return true;
// objects types must be equal // objects types must be equal
if (!(obj instanceof CodeSource)) return (obj instanceof CodeSource other)
return false; && Objects.equals(location, other.location)
&& matchCerts(other, true);
CodeSource cs = (CodeSource) obj;
// URLs must match
if (location == null) {
// if location is null, then cs.location must be null as well
if (cs.location != null) return false;
} else {
// if location is not null, then it must equal cs.location
if (!location.equals(cs.location)) return false;
}
// certs must match
return matchCerts(cs, true);
} }
/** /**

View file

@ -334,20 +334,12 @@ public abstract class Identity implements Principal, Serializable {
* @see #identityEquals * @see #identityEquals
*/ */
public final boolean equals(Object identity) { public final boolean equals(Object identity) {
if (identity == this) { if (identity == this) {
return true; return true;
} }
if (identity instanceof Identity) { return identity instanceof Identity other
Identity i = (Identity)identity; && (this.fullName().equals(other.fullName()) || identityEquals(other));
if (this.fullName().equals(i.fullName())) {
return true;
} else {
return identityEquals(i);
}
}
return false;
} }
/** /**

View file

@ -313,10 +313,9 @@ public class KeyFactory {
Service s = serviceIterator.next(); Service s = serviceIterator.next();
try { try {
Object obj = s.newInstance(null); Object obj = s.newInstance(null);
if (obj instanceof KeyFactorySpi == false) { if (!(obj instanceof KeyFactorySpi spi)) {
continue; continue;
} }
KeyFactorySpi spi = (KeyFactorySpi)obj;
provider = s.getProvider(); provider = s.getProvider();
this.spi = spi; this.spi = spi;
return spi; return spi;

View file

@ -623,13 +623,12 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi {
try { try {
Object inst = s.newInstance(null); Object inst = s.newInstance(null);
// ignore non-spis // ignore non-spis
if (inst instanceof KeyPairGeneratorSpi == false) { if (!(inst instanceof KeyPairGeneratorSpi spi)) {
continue; continue;
} }
if (inst instanceof KeyPairGenerator) { if (inst instanceof KeyPairGenerator) {
continue; continue;
} }
KeyPairGeneratorSpi spi = (KeyPairGeneratorSpi)inst;
if (reinit) { if (reinit) {
if (initType == I_SIZE) { if (initType == I_SIZE) {
spi.initialize(initKeySize, initRandom); spi.initialize(initKeySize, initRandom);

View file

@ -1961,13 +1961,13 @@ public class KeyStore {
if ((type == null) || (file == null) || (protection == null)) { if ((type == null) || (file == null) || (protection == null)) {
throw new NullPointerException(); throw new NullPointerException();
} }
if ((protection instanceof PasswordProtection == false) && if (!(protection instanceof PasswordProtection) &&
(protection instanceof CallbackHandlerProtection == false)) { !(protection instanceof CallbackHandlerProtection)) {
throw new IllegalArgumentException throw new IllegalArgumentException
("Protection must be PasswordProtection or " + ("Protection must be PasswordProtection or " +
"CallbackHandlerProtection"); "CallbackHandlerProtection");
} }
if (file.isFile() == false) { if (!file.isFile()) {
throw new IllegalArgumentException throw new IllegalArgumentException
("File does not exist or it does not refer " + ("File does not exist or it does not refer " +
"to a normal file: " + file); "to a normal file: " + file);
@ -2056,7 +2056,7 @@ public class KeyStore {
PrivilegedExceptionAction<KeyStore> action = PrivilegedExceptionAction<KeyStore> action =
new PrivilegedExceptionAction<KeyStore>() { new PrivilegedExceptionAction<KeyStore>() {
public KeyStore run() throws Exception { public KeyStore run() throws Exception {
if (protection instanceof CallbackHandlerProtection == false) { if (!(protection instanceof CallbackHandlerProtection)) {
return run0(); return run0();
} }
// when using a CallbackHandler, // when using a CallbackHandler,
@ -2190,7 +2190,7 @@ public class KeyStore {
ks = KeyStore.getInstance(type, provider); ks = KeyStore.getInstance(type, provider);
} }
LoadStoreParameter param = new SimpleLoadStoreParameter(protection); LoadStoreParameter param = new SimpleLoadStoreParameter(protection);
if (protection instanceof CallbackHandlerProtection == false) { if (!(protection instanceof CallbackHandlerProtection)) {
ks.load(param); ks.load(param);
} else { } else {
// when using a CallbackHandler, // when using a CallbackHandler,

View file

@ -298,8 +298,7 @@ public abstract class MessageDigest extends MessageDigestSpi {
if (provider == null) if (provider == null)
throw new IllegalArgumentException("missing provider"); throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
if (objs[0] instanceof MessageDigest) { if (objs[0] instanceof MessageDigest md) {
MessageDigest md = (MessageDigest)objs[0];
md.provider = (Provider)objs[1]; md.provider = (Provider)objs[1];
return md; return md;
} else { } else {

View file

@ -1077,10 +1077,8 @@ public abstract class Provider extends Properties {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (!(obj instanceof ServiceKey other)) { return obj instanceof ServiceKey other
return false; && this.type.equals(other.type)
}
return this.type.equals(other.type)
&& this.algorithm.equals(other.algorithm); && this.algorithm.equals(other.algorithm);
} }
boolean matches(String type, String algorithm) { boolean matches(String type, String algorithm) {
@ -1500,11 +1498,8 @@ public abstract class Provider extends Properties {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj instanceof UString == false) { return obj instanceof UString other
return false; && lowerString.equals(other.lowerString);
}
UString other = (UString)obj;
return lowerString.equals(other.lowerString);
} }
public String toString() { public String toString() {
@ -2005,16 +2000,16 @@ public abstract class Provider extends Properties {
// unknown engine type, return true by default // unknown engine type, return true by default
return true; return true;
} }
if (cap.supportsParameter == false) { if (!cap.supportsParameter) {
throw new InvalidParameterException("supportsParameter() not " throw new InvalidParameterException("supportsParameter() not "
+ "used with " + type + " engines"); + "used with " + type + " engines");
} }
// allow null for keys without attributes for compatibility // allow null for keys without attributes for compatibility
if ((parameter != null) && (parameter instanceof Key == false)) { if ((parameter != null) && (!(parameter instanceof Key))) {
throw new InvalidParameterException throw new InvalidParameterException
("Parameter must be instanceof Key for engine " + type); ("Parameter must be instanceof Key for engine " + type);
} }
if (hasKeyAttributes() == false) { if (!hasKeyAttributes()) {
return true; return true;
} }
if (parameter == null) { if (parameter == null) {

View file

@ -254,18 +254,10 @@ public class SecureClassLoader extends ClassLoader {
return true; return true;
} }
if (!(obj instanceof CodeSourceKey)) { return obj instanceof CodeSourceKey other
return false; && Objects.equals(cs.getLocationNoFragString(),
} other.cs.getLocationNoFragString())
&& cs.matchCerts(other.cs, true);
CodeSourceKey csk = (CodeSourceKey) obj;
if (!Objects.equals(cs.getLocationNoFragString(),
csk.cs.getLocationNoFragString())) {
return false;
}
return cs.matchCerts(csk.cs, true);
} }
} }

View file

@ -333,7 +333,7 @@ public abstract class Signature extends SignatureSpi {
// so it is a "real" Spi if it is an // so it is a "real" Spi if it is an
// instance of SignatureSpi but not Signature // instance of SignatureSpi but not Signature
boolean r = (instance instanceof SignatureSpi) boolean r = (instance instanceof SignatureSpi)
&& (instance instanceof Signature == false); && (!(instance instanceof Signature));
if ((debug != null) && (r == false)) { if ((debug != null) && (r == false)) {
debug.println("Not a SignatureSpi " + className); debug.println("Not a SignatureSpi " + className);
debug.println("Delayed provider selection may not be " debug.println("Delayed provider selection may not be "
@ -541,16 +541,15 @@ public abstract class Signature extends SignatureSpi {
// we should check whether it has a Key Usage // we should check whether it has a Key Usage
// extension marked as critical. // extension marked as critical.
//if (cert instanceof java.security.cert.X509Certificate) { //if (cert instanceof java.security.cert.X509Certificate) {
if (cert instanceof X509Certificate) { if (cert instanceof X509Certificate xcert) {
// Check whether the cert has a key usage extension // Check whether the cert has a key usage extension
// marked as a critical extension. // marked as a critical extension.
// The OID for KeyUsage extension is 2.5.29.15. // The OID for KeyUsage extension is 2.5.29.15.
X509Certificate c = (X509Certificate)cert; Set<String> critSet = xcert.getCriticalExtensionOIDs();
Set<String> critSet = c.getCriticalExtensionOIDs();
if (critSet != null && !critSet.isEmpty() if (critSet != null && !critSet.isEmpty()
&& critSet.contains(KnownOIDs.KeyUsage.value())) { && critSet.contains(KnownOIDs.KeyUsage.value())) {
boolean[] keyUsageInfo = c.getKeyUsage(); boolean[] keyUsageInfo = xcert.getKeyUsage();
// keyUsageInfo[0] is for digitalSignature. // keyUsageInfo[0] is for digitalSignature.
if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
throw new InvalidKeyException("Wrong key usage"); throw new InvalidKeyException("Wrong key usage");
@ -1178,7 +1177,7 @@ public abstract class Signature extends SignatureSpi {
} }
} else { } else {
Object o = s.newInstance(null); Object o = s.newInstance(null);
if (o instanceof SignatureSpi == false) { if (!(o instanceof SignatureSpi)) {
throw new NoSuchAlgorithmException throw new NoSuchAlgorithmException
("Not a SignatureSpi: " + o.getClass().getName()); ("Not a SignatureSpi: " + o.getClass().getName());
} }

View file

@ -123,16 +123,12 @@ public final class Timestamp implements Serializable {
* @return true if the timestamp are considered equal, false otherwise. * @return true if the timestamp are considered equal, false otherwise.
*/ */
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null || (!(obj instanceof Timestamp))) { if (this == obj) {
return false;
}
Timestamp that = (Timestamp)obj;
if (this == that) {
return true; return true;
} }
return (timestamp.equals(that.getTimestamp()) && return obj instanceof Timestamp other
signerCertPath.equals(that.getSignerCertPath())); && (timestamp.equals(other.getTimestamp()) &&
signerCertPath.equals(other.getSignerCertPath()));
} }
/** /**

View file

@ -334,9 +334,8 @@ implements java.io.Serializable
if (obj == this) if (obj == this)
return true; return true;
if (! (obj instanceof UnresolvedPermission)) if (!(obj instanceof UnresolvedPermission that))
return false; return false;
UnresolvedPermission that = (UnresolvedPermission) obj;
// check type // check type
if (!this.type.equals(that.type)) { if (!this.type.equals(that.type)) {

View file

@ -75,14 +75,13 @@ implements java.io.Serializable
*/ */
@Override @Override
public void add(Permission permission) { public void add(Permission permission) {
if (! (permission instanceof UnresolvedPermission)) if (!(permission instanceof UnresolvedPermission unresolvedPermission))
throw new IllegalArgumentException("invalid permission: "+ throw new IllegalArgumentException("invalid permission: "+
permission); permission);
UnresolvedPermission up = (UnresolvedPermission) permission;
// Add permission to map. NOTE: cannot use lambda for // Add permission to map. NOTE: cannot use lambda for
// remappingFunction parameter until JDK-8076596 is fixed. // remappingFunction parameter until JDK-8076596 is fixed.
perms.compute(up.getName(), perms.compute(unresolvedPermission.getName(),
new java.util.function.BiFunction<>() { new java.util.function.BiFunction<>() {
@Override @Override
public List<UnresolvedPermission> apply(String key, public List<UnresolvedPermission> apply(String key,
@ -90,10 +89,10 @@ implements java.io.Serializable
if (oldValue == null) { if (oldValue == null) {
List<UnresolvedPermission> v = List<UnresolvedPermission> v =
new CopyOnWriteArrayList<>(); new CopyOnWriteArrayList<>();
v.add(up); v.add(unresolvedPermission);
return v; return v;
} else { } else {
oldValue.add(up); oldValue.add(unresolvedPermission);
return oldValue; return oldValue;
} }
} }

View file

@ -181,16 +181,9 @@ public abstract class CertPath implements Serializable {
if (this == other) if (this == other)
return true; return true;
if (! (other instanceof CertPath)) return other instanceof CertPath that
return false; && that.getType().equals(this.type)
&& this.getCertificates().equals(that.getCertificates());
CertPath otherCP = (CertPath) other;
if (! otherCP.getType().equals(type))
return false;
List<? extends Certificate> thisCertList = this.getCertificates();
List<? extends Certificate> otherCertList = otherCP.getCertificates();
return(thisCertList.equals(otherCertList));
} }
/** /**

View file

@ -124,16 +124,11 @@ public final class URICertStoreParameters implements CertStoreParameters {
*/ */
@Override @Override
public boolean equals(Object p) { public boolean equals(Object p) {
if (p == null || (!(p instanceof URICertStoreParameters))) {
return false;
}
if (p == this) { if (p == this) {
return true; return true;
} }
return p instanceof URICertStoreParameters other
URICertStoreParameters other = (URICertStoreParameters)p; && uri.equals(other.getURI());
return uri.equals(other.getURI());
} }
/** /**

View file

@ -597,10 +597,9 @@ public class X509CRLSelector implements CRLSelector {
* {@code false} otherwise * {@code false} otherwise
*/ */
public boolean match(CRL crl) { public boolean match(CRL crl) {
if (!(crl instanceof X509CRL)) { if (!(crl instanceof X509CRL xcrl)) {
return false; return false;
} }
X509CRL xcrl = (X509CRL)crl;
/* match on issuer name */ /* match on issuer name */
if (issuerNames != null) { if (issuerNames != null) {

View file

@ -834,10 +834,9 @@ public class X509CertSelector implements CertSelector {
throw new IOException("name list size not 2"); throw new IOException("name list size not 2");
} }
Object o = nameList.get(0); Object o = nameList.get(0);
if (!(o instanceof Integer)) { if (!(o instanceof Integer nameType)) {
throw new IOException("expected an Integer"); throw new IOException("expected an Integer");
} }
int nameType = ((Integer)o).intValue();
o = nameList.get(1); o = nameList.get(1);
genNames.add(makeGeneralNameInterface(nameType, o)); genNames.add(makeGeneralNameInterface(nameType, o));
} }
@ -885,29 +884,29 @@ public class X509CertSelector implements CertSelector {
+ type + ")..."); + type + ")...");
} }
if (name instanceof String) { if (name instanceof String nameAsString) {
if (debug != null) { if (debug != null) {
debug.println("X509CertSelector.makeGeneralNameInterface() " debug.println("X509CertSelector.makeGeneralNameInterface() "
+ "name is String: " + name); + "name is String: " + nameAsString);
} }
switch (type) { switch (type) {
case NAME_RFC822: case NAME_RFC822:
result = new RFC822Name((String)name); result = new RFC822Name(nameAsString);
break; break;
case NAME_DNS: case NAME_DNS:
result = new DNSName((String)name); result = new DNSName(nameAsString);
break; break;
case NAME_DIRECTORY: case NAME_DIRECTORY:
result = new X500Name((String)name); result = new X500Name(nameAsString);
break; break;
case NAME_URI: case NAME_URI:
result = new URIName((String)name); result = new URIName(nameAsString);
break; break;
case NAME_IP: case NAME_IP:
result = new IPAddressName((String)name); result = new IPAddressName(nameAsString);
break; break;
case NAME_OID: case NAME_OID:
result = new OIDName((String)name); result = new OIDName(nameAsString);
break; break;
default: default:
throw new IOException("unable to parse String names of type " throw new IOException("unable to parse String names of type "
@ -1668,10 +1667,9 @@ public class X509CertSelector implements CertSelector {
throw new IOException("name list size not 2"); throw new IOException("name list size not 2");
} }
Object o = nameList.get(0); Object o = nameList.get(0);
if (!(o instanceof Integer)) { if (!(o instanceof Integer nameType)) {
throw new IOException("expected an Integer"); throw new IOException("expected an Integer");
} }
int nameType = ((Integer)o).intValue();
if ((nameType < 0) || (nameType > 8)) { if ((nameType < 0) || (nameType > 8)) {
throw new IOException("name type not 0-8"); throw new IOException("name type not 0-8");
} }
@ -1929,8 +1927,7 @@ public class X509CertSelector implements CertSelector {
*/ */
private static Extension getExtensionObject(X509Certificate cert, KnownOIDs extId) private static Extension getExtensionObject(X509Certificate cert, KnownOIDs extId)
throws IOException { throws IOException {
if (cert instanceof X509CertImpl) { if (cert instanceof X509CertImpl impl) {
X509CertImpl impl = (X509CertImpl) cert;
switch (extId) { switch (extId) {
case PrivateKeyUsage: case PrivateKeyUsage:
return impl.getPrivateKeyUsageExtension(); return impl.getPrivateKeyUsageExtension();
@ -1980,10 +1977,9 @@ public class X509CertSelector implements CertSelector {
* selected, {@code false} otherwise * selected, {@code false} otherwise
*/ */
public boolean match(Certificate cert) { public boolean match(Certificate cert) {
if (!(cert instanceof X509Certificate)) { if (!(cert instanceof X509Certificate xcert)) {
return false; return false;
} }
X509Certificate xcert = (X509Certificate)cert;
if (debug != null) { if (debug != null) {
debug.println("X509CertSelector.match(SN: " debug.println("X509CertSelector.match(SN: "

View file

@ -217,13 +217,12 @@ public class ECFieldF2m implements ECField {
*/ */
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) return true; if (this == obj) return true;
if (obj instanceof ECFieldF2m) {
return obj instanceof ECFieldF2m other
// no need to compare rp here since ks and rp // no need to compare rp here since ks and rp
// should be equivalent // should be equivalent
return ((m == ((ECFieldF2m)obj).m) && && (m == other.m)
(Arrays.equals(ks, ((ECFieldF2m) obj).ks))); && (Arrays.equals(ks, other.ks));
}
return false;
} }
/** /**

View file

@ -82,10 +82,9 @@ public class ECFieldFp implements ECField {
*/ */
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) return true; if (this == obj) return true;
if (obj instanceof ECFieldFp) {
return (p.equals(((ECFieldFp)obj).p)); return obj instanceof ECFieldFp other
} && p.equals(other.p);
return false;
} }
/** /**

View file

@ -96,11 +96,10 @@ public class ECPoint {
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) return true; if (this == obj) return true;
if (this == POINT_INFINITY) return false; if (this == POINT_INFINITY) return false;
if (obj instanceof ECPoint) {
return ((x.equals(((ECPoint)obj).x)) && return obj instanceof ECPoint other
(y.equals(((ECPoint)obj).y))); && ((x.equals(other.x))
} && (y.equals(other.y)));
return false;
} }
/** /**

View file

@ -169,15 +169,11 @@ public class EllipticCurve {
*/ */
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) return true; if (this == obj) return true;
if (obj instanceof EllipticCurve) {
EllipticCurve curve = (EllipticCurve) obj; return obj instanceof EllipticCurve other
if ((field.equals(curve.field)) && && field.equals(other.field)
(a.equals(curve.a)) && && a.equals(other.a)
(b.equals(curve.b))) { && b.equals(other.b);
return true;
}
}
return false;
} }
/** /**