diff --git a/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt b/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt index 4fcd8415b4..809dbc45a9 100644 --- a/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt +++ b/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt @@ -17,6 +17,7 @@ import net.corda.core.identity.AbstractParty import net.corda.core.identity.AnonymousParty import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.CordaRPCOps import net.corda.core.node.NodeInfo import net.corda.core.node.services.IdentityService @@ -266,8 +267,7 @@ object JacksonSupport { parser.nextToken() } try { - @Suppress("UNCHECKED_CAST") - return SecureHash.parse(parser.text) as T + return uncheckedCast(SecureHash.parse(parser.text)) } catch (e: Exception) { throw JsonParseException(parser, "Invalid hash ${parser.text}: ${e.message}") } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt index 6a81eb0dc9..e62f531dcf 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt @@ -6,6 +6,7 @@ import net.corda.client.jfx.utils.fold import net.corda.client.jfx.utils.map import net.corda.core.contracts.ContractState import net.corda.core.contracts.StateAndRef +import net.corda.core.internal.uncheckedCast import net.corda.core.node.services.Vault import net.corda.finance.contracts.asset.Cash import rx.Observable @@ -37,10 +38,9 @@ class ContractStateModel { companion object { private fun Collection>.filterCashStateAndRefs(): List> { return this.map { stateAndRef -> - @Suppress("UNCHECKED_CAST") if (stateAndRef.state.data is Cash.State) { // Kotlin doesn't unify here for some reason - stateAndRef as StateAndRef + uncheckedCast(stateAndRef) } else { null } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt index 71a6b66733..feb3548ed2 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt @@ -4,6 +4,7 @@ import javafx.beans.property.ObjectProperty import javafx.beans.value.ObservableValue import javafx.beans.value.WritableValue import javafx.collections.ObservableList +import net.corda.core.internal.uncheckedCast import org.reactfx.EventSink import org.reactfx.EventStream import rx.Observable @@ -78,9 +79,7 @@ object Models { if (model.javaClass != klass.java) { throw IllegalStateException("Model stored as ${klass.qualifiedName} has type ${model.javaClass}") } - - @Suppress("UNCHECKED_CAST") - return model as M + return uncheckedCast(model) } inline fun get(origin: KClass<*>): M = get(M::class, origin) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt index 10ae4aeff6..89366935fa 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt @@ -14,6 +14,7 @@ import javafx.collections.ObservableMap import javafx.collections.transformation.FilteredList import net.corda.core.contracts.ContractState import net.corda.core.contracts.StateAndRef +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.DataFeed import net.corda.core.node.services.Vault import org.fxmisc.easybind.EasyBind @@ -92,8 +93,7 @@ fun ObservableValue.bind(function: (A) -> ObservableValue): Obs * propagate variance constraints and type inference fails. */ fun ObservableValue.bindOut(function: (A) -> ObservableValue): ObservableValue = - @Suppress("UNCHECKED_CAST") - EasyBind.monadic(this).flatMap(function as (A) -> ObservableValue) + EasyBind.monadic(this).flatMap(uncheckedCast(function)) /** * enum class FilterCriterion { HEIGHT, NAME } @@ -105,8 +105,7 @@ fun ObservableValue.bindOut(function: (A) -> ObservableValue ObservableList.filter(predicate: ObservableValue<(A) -> Boolean>): ObservableList { // We cast here to enforce variance, FilteredList should be covariant - @Suppress("UNCHECKED_CAST") - return FilteredList(this as ObservableList).apply { + return FilteredList(uncheckedCast(this)).apply { predicateProperty().bind(predicate.map { predicateFunction -> Predicate { predicateFunction(it) } }) @@ -120,13 +119,11 @@ fun ObservableList.filter(predicate: ObservableValue<(A) -> Boolean>) */ fun ObservableList.filterNotNull(): ObservableList { //TODO This is a tactical work round for an issue with SAM conversion (https://youtrack.jetbrains.com/issue/ALL-1552) so that the M10 explorer works. - @Suppress("UNCHECKED_CAST") - return (this as ObservableList).filtered(object : Predicate { + return uncheckedCast(uncheckedCast>(this).filtered(object : Predicate { override fun test(t: A?): Boolean { return t != null - } - }) as ObservableList + })) } /** diff --git a/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt b/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt index 3993383a1a..e01c39d6f9 100644 --- a/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt +++ b/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt @@ -1,6 +1,7 @@ package net.corda.client.mock import net.corda.client.mock.Generator.Companion.choice +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.Try import java.util.* @@ -115,14 +116,13 @@ class Generator(val generate: (SplittableRandom) -> Try) { fun frequency(vararg generators: Pair>) = frequency(generators.toList()) - fun sequence(generators: List>) = Generator { + fun sequence(generators: List>) = Generator> { val result = mutableListOf() for (generator in generators) { val element = generator.generate(it) - @Suppress("UNCHECKED_CAST") when (element) { is Try.Success -> result.add(element.value) - is Try.Failure -> return@Generator element as Try> + is Try.Failure -> return@Generator uncheckedCast(element) } } Try.Success(result) @@ -175,7 +175,7 @@ class Generator(val generate: (SplittableRandom) -> Try) { } - fun replicatePoisson(meanSize: Double, generator: Generator, atLeastOne: Boolean = false) = Generator { + fun replicatePoisson(meanSize: Double, generator: Generator, atLeastOne: Boolean = false) = Generator> { val chance = (meanSize - 1) / meanSize val result = mutableListOf() var finish = false @@ -191,8 +191,7 @@ class Generator(val generate: (SplittableRandom) -> Try) { } } if (res is Try.Failure) { - @Suppress("UNCHECKED_CAST") - return@Generator res as Try> + return@Generator uncheckedCast(res) } } Try.Success(result) diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt index d4716f947f..773c511da9 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClient.kt @@ -4,6 +4,7 @@ import net.corda.client.rpc.RPCConnection import net.corda.client.rpc.RPCException import net.corda.core.crypto.random63BitValue import net.corda.core.internal.logElapsedTime +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.RPCOps import net.corda.core.serialization.SerializationContext import net.corda.core.serialization.SerializationDefaults @@ -114,10 +115,7 @@ class RPCClient( val proxyHandler = RPCClientProxyHandler(rpcConfiguration, username, password, serverLocator, clientAddress, rpcOpsClass, serializationContext) try { proxyHandler.start() - - @Suppress("UNCHECKED_CAST") - val ops = Proxy.newProxyInstance(rpcOpsClass.classLoader, arrayOf(rpcOpsClass), proxyHandler) as I - + val ops: I = uncheckedCast(Proxy.newProxyInstance(rpcOpsClass.classLoader, arrayOf(rpcOpsClass), proxyHandler)) val serverProtocolVersion = ops.protocolVersion if (serverProtocolVersion < rpcConfiguration.minimumServerProtocolVersion) { throw RPCException("Requested minimum protocol version (${rpcConfiguration.minimumServerProtocolVersion}) is higher" + diff --git a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt index 51036f8dfe..d43ae5c001 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt @@ -4,6 +4,7 @@ package net.corda.core.contracts import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import java.security.PublicKey import java.util.* @@ -58,7 +59,7 @@ inline fun Collection> /** Ensures that a transaction has only one command that is of the given type, otherwise throws an exception. */ fun Collection>.requireSingleCommand(klass: Class) = - mapNotNull { @Suppress("UNCHECKED_CAST") if (klass.isInstance(it.value)) it as CommandWithParties else null }.single() + mapNotNull { if (klass.isInstance(it.value)) uncheckedCast, CommandWithParties>(it) else null }.single() /** * Simple functionality for verifying a move command. Verifies that each input has a signature from its owning key. diff --git a/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt b/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt index 472a8a1024..bc39699f55 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt @@ -1,5 +1,6 @@ package net.corda.core.crypto +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.SerializedBytes import net.corda.core.serialization.deserialize @@ -23,8 +24,7 @@ open class SignedData(val raw: SerializedBytes, val sig: DigitalSign @Throws(SignatureException::class) fun verified(): T { sig.by.verify(raw.bytes, sig) - @Suppress("UNCHECKED_CAST") - val data = raw.deserialize() as T + val data: T = uncheckedCast(raw.deserialize()) verifyData(data) return data } diff --git a/core/src/main/kotlin/net/corda/core/flows/ContractUpgradeFlow.kt b/core/src/main/kotlin/net/corda/core/flows/ContractUpgradeFlow.kt index 0612d5d9aa..c3ee51a861 100644 --- a/core/src/main/kotlin/net/corda/core/flows/ContractUpgradeFlow.kt +++ b/core/src/main/kotlin/net/corda/core/flows/ContractUpgradeFlow.kt @@ -3,6 +3,7 @@ package net.corda.core.flows import co.paralleluniverse.fibers.Suspendable import net.corda.core.contracts.* import net.corda.core.internal.ContractUpgradeUtils +import net.corda.core.internal.uncheckedCast import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import java.security.PublicKey @@ -30,8 +31,7 @@ object ContractUpgradeFlow { val command = commandData.value val participantKeys: Set = input.data.participants.map { it.owningKey }.toSet() val keysThatSigned: Set = commandData.signers.toSet() - @Suppress("UNCHECKED_CAST") - val upgradedContract = javaClass.classLoader.loadClass(command.upgradedContractClass).newInstance() as UpgradedContract + val upgradedContract: UpgradedContract = uncheckedCast(javaClass.classLoader.loadClass(command.upgradedContractClass).newInstance()) requireThat { "The signing keys include all participant keys" using keysThatSigned.containsAll(participantKeys) "Inputs state reference the legacy contract" using (input.contract == upgradedContract.legacyContract) diff --git a/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt b/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt index 0789c535ba..28b44dfa4e 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt @@ -114,8 +114,7 @@ sealed class FetchDataFlow( protected abstract fun load(txid: SecureHash): T? - @Suppress("UNCHECKED_CAST") - protected open fun convert(wire: W): T = wire as T + protected open fun convert(wire: W): T = uncheckedCast(wire) private fun validateFetchResponse(maybeItems: UntrustworthyData>, requests: List): List { diff --git a/core/src/main/kotlin/net/corda/core/internal/InternalUtils.kt b/core/src/main/kotlin/net/corda/core/internal/InternalUtils.kt index 0ef6a73f84..5d3eafdca1 100644 --- a/core/src/main/kotlin/net/corda/core/internal/InternalUtils.kt +++ b/core/src/main/kotlin/net/corda/core/internal/InternalUtils.kt @@ -226,8 +226,8 @@ private fun IntProgression.toSpliterator(): Spliterator.OfInt { fun IntProgression.stream(parallel: Boolean = false): IntStream = StreamSupport.intStream(toSpliterator(), parallel) -@Suppress("UNCHECKED_CAST") // When toArray has filled in the array, the component type is no longer T? but T (that may itself be nullable). -inline fun Stream.toTypedArray() = toArray { size -> arrayOfNulls(size) } as Array +// When toArray has filled in the array, the component type is no longer T? but T (that may itself be nullable): +inline fun Stream.toTypedArray(): Array = uncheckedCast(toArray { size -> arrayOfNulls(size) }) fun Class.castIfPossible(obj: Any): T? = if (isInstance(obj)) cast(obj) else null @@ -256,8 +256,7 @@ fun KClass.objectOrNewInstance(): T { class DeclaredField(clazz: Class<*>, name: String, private val receiver: Any?) { private val javaField = clazz.getDeclaredField(name).apply { isAccessible = true } var value: T - @Suppress("UNCHECKED_CAST") - get() = javaField.get(receiver) as T + get() = uncheckedCast(javaField.get(receiver)) set(value) = javaField.set(receiver, value) } diff --git a/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt b/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt index 811bc1ee2e..1ee9ab89d4 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt @@ -2,6 +2,7 @@ package net.corda.core.node.services.vault +import net.corda.core.internal.uncheckedCast import net.corda.core.schemas.PersistentState import net.corda.core.serialization.CordaSerializable import java.lang.reflect.Field @@ -88,8 +89,7 @@ fun resolveEnclosingObjectFromExpression(expression: CriteriaExpression resolveEnclosingObjectFromColumn(column: Column): Class = column.declaringClass as Class +fun resolveEnclosingObjectFromColumn(column: Column): Class = uncheckedCast(column.declaringClass) fun getColumnName(column: Column): String = column.name /** diff --git a/core/src/main/kotlin/net/corda/core/transactions/BaseTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/BaseTransaction.kt index da0d98dbe7..3ff6773082 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/BaseTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/BaseTransaction.kt @@ -4,6 +4,7 @@ import net.corda.core.contracts.* import net.corda.core.identity.Party import net.corda.core.internal.indexOfOrThrow import net.corda.core.internal.castIfPossible +import net.corda.core.internal.uncheckedCast import java.util.function.Predicate /** @@ -40,8 +41,7 @@ abstract class BaseTransaction : NamedByHash { /** * Returns a [StateAndRef] for the given output index. */ - @Suppress("UNCHECKED_CAST") - fun outRef(index: Int): StateAndRef = StateAndRef(outputs[index] as TransactionState, StateRef(id, index)) + fun outRef(index: Int): StateAndRef = StateAndRef(uncheckedCast(outputs[index]), StateRef(id, index)) /** * Returns a [StateAndRef] for the requested output state, or throws [IllegalArgumentException] if not found. @@ -111,8 +111,7 @@ abstract class BaseTransaction : NamedByHash { */ fun outRefsOfType(clazz: Class): List> { return outputs.mapIndexedNotNull { index, state -> - @Suppress("UNCHECKED_CAST") - clazz.castIfPossible(state.data)?.let { StateAndRef(state as TransactionState, StateRef(id, index)) } + clazz.castIfPossible(state.data)?.let { StateAndRef(uncheckedCast(state), StateRef(id, index)) } } } diff --git a/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt index 4fa5778071..f54d02e5fc 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/LedgerTransaction.kt @@ -4,6 +4,7 @@ import net.corda.core.contracts.* import net.corda.core.crypto.SecureHash import net.corda.core.identity.Party import net.corda.core.internal.castIfPossible +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.CordaSerializable import java.util.* import java.util.function.Predicate @@ -52,8 +53,7 @@ data class LedgerTransaction( * @param index The index into the inputs. * @return The [StateAndRef] */ - @Suppress("UNCHECKED_CAST") - fun inRef(index: Int): StateAndRef = inputs[index] as StateAndRef + fun inRef(index: Int): StateAndRef = uncheckedCast(inputs[index]) /** * Verifies this transaction and runs contract code. At this stage it is assumed that signatures have already been verified. @@ -230,8 +230,7 @@ data class LedgerTransaction( * @return the possibly empty list of inputs [StateAndRef] matching the clazz restriction. */ fun inRefsOfType(clazz: Class): List> { - @Suppress("UNCHECKED_CAST") - return inputs.mapNotNull { if (clazz.isInstance(it.state.data)) it as StateAndRef else null } + return inputs.mapNotNull { if (clazz.isInstance(it.state.data)) uncheckedCast, StateAndRef>(it) else null } } inline fun inRefsOfType(): List> = inRefsOfType(T::class.java) @@ -307,8 +306,7 @@ data class LedgerTransaction( * @param index the position of the item in the commands. * @return The Command at the requested index */ - @Suppress("UNCHECKED_CAST") - fun getCommand(index: Int): Command = Command(commands[index].value as T, commands[index].signers) + fun getCommand(index: Int): Command = Command(uncheckedCast(commands[index].value), commands[index].signers) /** * Helper to simplify getting all [Command] items with a [CommandData] of a particular class, interface, or base class. diff --git a/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt index a726dbf7fb..b12ea8353d 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt @@ -1,6 +1,7 @@ package net.corda.core.utilities import net.corda.core.internal.concurrent.get +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.CordaSerializable import org.slf4j.Logger import org.slf4j.LoggerFactory @@ -101,14 +102,13 @@ private class TransientProperty internal constructor(private val initiali @Transient private var initialised = false @Transient private var value: T? = null - @Suppress("UNCHECKED_CAST") @Synchronized override operator fun getValue(thisRef: Any?, property: KProperty<*>): T { if (!initialised) { value = initialiser() initialised = true } - return value as T + return uncheckedCast(value) } } diff --git a/core/src/main/kotlin/net/corda/core/utilities/Try.kt b/core/src/main/kotlin/net/corda/core/utilities/Try.kt index 4ff2224ade..cfe471c1b1 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/Try.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/Try.kt @@ -1,5 +1,6 @@ package net.corda.core.utilities +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.CordaSerializable import net.corda.core.utilities.Try.Failure import net.corda.core.utilities.Try.Success @@ -35,30 +36,27 @@ sealed class Try { abstract fun getOrThrow(): A /** Maps the given function to the value from this [Success], or returns `this` if this is a [Failure]. */ - @Suppress("UNCHECKED_CAST") inline fun map(function: (A) -> B): Try = when (this) { is Success -> Success(function(value)) - is Failure -> this as Try + is Failure -> uncheckedCast(this) } /** Returns the given function applied to the value from this [Success], or returns `this` if this is a [Failure]. */ - @Suppress("UNCHECKED_CAST") inline fun flatMap(function: (A) -> Try): Try = when (this) { is Success -> function(value) - is Failure -> this as Try + is Failure -> uncheckedCast(this) } /** * Maps the given function to the values from this [Success] and [other], or returns `this` if this is a [Failure] * or [other] if [other] is a [Failure]. */ - @Suppress("UNCHECKED_CAST") inline fun combine(other: Try, function: (A, B) -> C): Try = when (this) { is Success -> when (other) { is Success -> Success(function(value, other.value)) - is Failure -> other as Try + is Failure -> uncheckedCast(other) } - is Failure -> this as Try + is Failure -> uncheckedCast(this) } data class Success(val value: A) : Try() { diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt index 6f12d53844..7abb5ed97d 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt @@ -3,6 +3,7 @@ package net.corda.finance.contracts.universal import net.corda.core.contracts.* import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.finance.contracts.BusinessCalendar @@ -124,19 +125,18 @@ class UniversalContract : Contract { } } - @Suppress("UNCHECKED_CAST") fun replaceStartEnd(p: Perceivable, start: Instant, end: Instant): Perceivable = when (p) { is Const -> p - is TimePerceivable -> TimePerceivable(p.cmp, replaceStartEnd(p.instant, start, end)) as Perceivable - is EndDate -> const(end) as Perceivable - is StartDate -> const(start) as Perceivable + is TimePerceivable -> uncheckedCast(TimePerceivable(p.cmp, replaceStartEnd(p.instant, start, end))) + is EndDate -> uncheckedCast(const(end)) + is StartDate -> uncheckedCast(const(start)) is UnaryPlus -> UnaryPlus(replaceStartEnd(p.arg, start, end)) is PerceivableOperation -> PerceivableOperation(replaceStartEnd(p.left, start, end), p.op, replaceStartEnd(p.right, start, end)) - is Interest -> Interest(replaceStartEnd(p.amount, start, end), p.dayCountConvention, replaceStartEnd(p.interest, start, end), replaceStartEnd(p.start, start, end), replaceStartEnd(p.end, start, end)) as Perceivable - is Fixing -> Fixing(p.source, replaceStartEnd(p.date, start, end), p.tenor) as Perceivable - is PerceivableAnd -> (replaceStartEnd(p.left, start, end) and replaceStartEnd(p.right, start, end)) as Perceivable - is PerceivableOr -> (replaceStartEnd(p.left, start, end) or replaceStartEnd(p.right, start, end)) as Perceivable + is Interest -> uncheckedCast(Interest(replaceStartEnd(p.amount, start, end), p.dayCountConvention, replaceStartEnd(p.interest, start, end), replaceStartEnd(p.start, start, end), replaceStartEnd(p.end, start, end))) + is Fixing -> uncheckedCast(Fixing(p.source, replaceStartEnd(p.date, start, end), p.tenor)) + is PerceivableAnd -> uncheckedCast(replaceStartEnd(p.left, start, end) and replaceStartEnd(p.right, start, end)) + is PerceivableOr -> uncheckedCast(replaceStartEnd(p.left, start, end) or replaceStartEnd(p.right, start, end)) is ActorPerceivable -> p else -> throw NotImplementedError("replaceStartEnd " + p.javaClass.name) } @@ -276,7 +276,6 @@ class UniversalContract : Contract { } } - @Suppress("UNCHECKED_CAST") fun replaceFixing(tx: LedgerTransaction, perceivable: Perceivable, fixings: Map, unusedFixings: MutableSet): Perceivable = when (perceivable) { @@ -284,14 +283,14 @@ class UniversalContract : Contract { is UnaryPlus -> UnaryPlus(replaceFixing(tx, perceivable.arg, fixings, unusedFixings)) is PerceivableOperation -> PerceivableOperation(replaceFixing(tx, perceivable.left, fixings, unusedFixings), perceivable.op, replaceFixing(tx, perceivable.right, fixings, unusedFixings)) - is Interest -> Interest(replaceFixing(tx, perceivable.amount, fixings, unusedFixings), + is Interest -> uncheckedCast(Interest(replaceFixing(tx, perceivable.amount, fixings, unusedFixings), perceivable.dayCountConvention, replaceFixing(tx, perceivable.interest, fixings, unusedFixings), - perceivable.start, perceivable.end) as Perceivable + perceivable.start, perceivable.end)) is Fixing -> { val dt = eval(tx, perceivable.date) if (dt != null && fixings.containsKey(FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor))) { unusedFixings.remove(FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)) - Const(fixings[FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)]!!) as Perceivable + uncheckedCast(Const(fixings[FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)]!!)) } else perceivable } else -> throw NotImplementedError("replaceFixing - " + perceivable.javaClass.name) diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt index 7f6c84010d..2e28208a6f 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt @@ -39,7 +39,6 @@ private fun rowsToAmount(currency: Currency, rows: Vault.Page>) } else { require(rows.otherResults.size == 2) require(rows.otherResults[1] == currency.currencyCode) - @Suppress("UNCHECKED_CAST") val quantity = rows.otherResults[0] as Long Amount(quantity, currency) } diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt index 770e0ae5a2..b9b7bd7091 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/CashTests.kt @@ -594,7 +594,6 @@ class CashTests : TestDependencyInjectionBase() { makeSpend(100.DOLLARS, THEIR_IDENTITY_1) } database.transaction { - @Suppress("UNCHECKED_CAST") val vaultState = vaultStatesUnconsumed.elementAt(0) assertEquals(vaultState.ref, wtx.inputs[0]) assertEquals(vaultState.state.data.copy(owner = THEIR_IDENTITY_1), wtx.getOutput(0)) @@ -622,7 +621,6 @@ class CashTests : TestDependencyInjectionBase() { makeSpend(10.DOLLARS, THEIR_IDENTITY_1) } database.transaction { - @Suppress("UNCHECKED_CAST") val vaultState = vaultStatesUnconsumed.elementAt(0) val changeAmount = 90.DOLLARS `issued by` defaultIssuer val likelyChangeState = wtx.outputs.map(TransactionState<*>::data).filter { state -> @@ -649,7 +647,6 @@ class CashTests : TestDependencyInjectionBase() { makeSpend(500.DOLLARS, THEIR_IDENTITY_1) } database.transaction { - @Suppress("UNCHECKED_CAST") val vaultState0 = vaultStatesUnconsumed.elementAt(0) val vaultState1 = vaultStatesUnconsumed.elementAt(1) assertEquals(vaultState0.ref, wtx.inputs[0]) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt b/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt index 052a361267..1463229b13 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/config/ConfigUtilities.kt @@ -5,6 +5,7 @@ import com.typesafe.config.Config import com.typesafe.config.ConfigUtil import net.corda.core.identity.CordaX500Name import net.corda.core.internal.noneOrSingle +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.NetworkHostAndPort import org.slf4j.LoggerFactory import java.net.Proxy @@ -25,7 +26,7 @@ import kotlin.reflect.jvm.jvmErasure annotation class OldConfig(val value: String) // TODO Move other config parsing to use parseAs and remove this -operator fun Config.getValue(receiver: Any, metadata: KProperty<*>): T { +operator fun Config.getValue(receiver: Any, metadata: KProperty<*>): T { return getValueInternal(metadata.name, metadata.returnType) } @@ -52,9 +53,8 @@ fun Config.toProperties(): Properties { { it.value.unwrapped().toString() }) } -@Suppress("UNCHECKED_CAST") -private fun Config.getValueInternal(path: String, type: KType): T { - return (if (type.arguments.isEmpty()) getSingleValue(path, type) else getCollectionValue(path, type)) as T +private fun Config.getValueInternal(path: String, type: KType): T { + return uncheckedCast(if (type.arguments.isEmpty()) getSingleValue(path, type) else getCollectionValue(path, type)) } private fun Config.getSingleValue(path: String, type: KType): Any? { @@ -122,8 +122,7 @@ private fun Config.defaultToOldPath(property: KProperty<*>): String { return property.name } -@Suppress("UNCHECKED_CAST") -private fun parseEnum(enumType: Class<*>, name: String): Enum<*> = enumBridge(enumType as Class, name) // Any enum will do +private fun parseEnum(enumType: Class<*>, name: String): Enum<*> = enumBridge(uncheckedCast(enumType), name) // Any enum will do private fun > enumBridge(clazz: Class, name: String): T = java.lang.Enum.valueOf(clazz, name) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/Kryo.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/Kryo.kt index 06f73a4a95..06820db6c2 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/Kryo.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/Kryo.kt @@ -14,6 +14,7 @@ import net.corda.core.crypto.CompositeKey import net.corda.core.crypto.Crypto import net.corda.core.crypto.TransactionSignature import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.SerializationContext import net.corda.core.serialization.SerializeAsTokenContext import net.corda.core.serialization.SerializedBytes @@ -245,9 +246,8 @@ object WireTransactionSerializer : Serializer() { kryo.writeClassAndObject(output, obj.privacySalt) } - @Suppress("UNCHECKED_CAST") override fun read(kryo: Kryo, input: Input, type: Class): WireTransaction { - val componentGroups = kryo.readClassAndObject(input) as List + val componentGroups: List = uncheckedCast(kryo.readClassAndObject(input)) val privacySalt = kryo.readClassAndObject(input) as PrivacySalt return WireTransaction(componentGroups, privacySalt) } @@ -261,9 +261,8 @@ object NotaryChangeWireTransactionSerializer : Serializer): NotaryChangeWireTransaction { - val inputs = kryo.readClassAndObject(input) as List + val inputs: List = uncheckedCast(kryo.readClassAndObject(input)) val notary = kryo.readClassAndObject(input) as Party val newNotary = kryo.readClassAndObject(input) as Party @@ -278,11 +277,10 @@ object SignedTransactionSerializer : Serializer() { kryo.writeClassAndObject(output, obj.sigs) } - @Suppress("UNCHECKED_CAST") override fun read(kryo: Kryo, input: Input, type: Class): SignedTransaction { return SignedTransaction( - kryo.readClassAndObject(input) as SerializedBytes, - kryo.readClassAndObject(input) as List + uncheckedCast>(kryo.readClassAndObject(input)), + uncheckedCast>(kryo.readClassAndObject(input)) ) } } @@ -600,8 +598,7 @@ class ThrowableSerializer(kryo: Kryo, type: Class) : Serializer } } - @Suppress("UNCHECKED_CAST") - private val delegate: Serializer = ReflectionSerializerFactory.makeSerializer(kryo, FieldSerializer::class.java, type) as Serializer + private val delegate: Serializer = uncheckedCast(ReflectionSerializerFactory.makeSerializer(kryo, FieldSerializer::class.java, type)) override fun write(kryo: Kryo, output: Output, throwable: Throwable) { delegate.write(kryo, output, throwable) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializationScheme.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializationScheme.kt index 299b77ae84..648d6e5817 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializationScheme.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializationScheme.kt @@ -14,6 +14,7 @@ import com.google.common.cache.CacheBuilder import net.corda.core.contracts.Attachment import net.corda.core.crypto.SecureHash import net.corda.core.internal.LazyPool +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.* import net.corda.core.utilities.ByteSequence import net.corda.core.utilities.OpaqueBytes @@ -204,11 +205,10 @@ abstract class AbstractKryoSerializationScheme : SerializationScheme { Input(byteSequence.bytes, byteSequence.offset + headerSize, byteSequence.size - headerSize).use { input -> return pool.run { kryo -> withContext(kryo, context) { - @Suppress("UNCHECKED_CAST") if (context.objectReferencesEnabled) { - kryo.readClassAndObject(input) as T + uncheckedCast(kryo.readClassAndObject(input)) } else { - kryo.withoutReferences { kryo.readClassAndObject(input) as T } + kryo.withoutReferences { uncheckedCast(kryo.readClassAndObject(input)) } } } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt index 615cea26af..43a0234f95 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt @@ -1,5 +1,6 @@ package net.corda.nodeapi.internal.serialization.amqp +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.NonEmptySet import org.apache.qpid.proton.amqp.Symbol import org.apache.qpid.proton.codec.Data @@ -36,8 +37,7 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali fun deriveParameterizedType(declaredType: Type, declaredClass: Class<*>, actualClass: Class<*>?): ParameterizedType { if(supportedTypes.containsKey(declaredClass)) { // Simple case - it is already known to be a collection. - @Suppress("UNCHECKED_CAST") - return deriveParametrizedType(declaredType, declaredClass as Class>) + return deriveParametrizedType(declaredType, uncheckedCast(declaredClass)) } else if (actualClass != null && Collection::class.java.isAssignableFrom(actualClass)) { // Declared class is not collection, but [actualClass] is - represent it accordingly. diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt index 7188a99b50..242f829511 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt @@ -1,5 +1,6 @@ package net.corda.nodeapi.internal.serialization.amqp +import net.corda.core.internal.uncheckedCast import net.corda.nodeapi.internal.serialization.amqp.SerializerFactory.Companion.nameForType import org.apache.qpid.proton.amqp.Symbol import org.apache.qpid.proton.codec.Data @@ -9,7 +10,7 @@ import java.lang.reflect.Type * Base class for serializers of core platform types that do not conform to the usual serialization rules and thus * cannot be automatically serialized. */ -abstract class CustomSerializer : AMQPSerializer { +abstract class CustomSerializer : AMQPSerializer { /** * This is a collection of custom serializers that this custom serializer depends on. e.g. for proxy objects * that refer to other custom types etc. @@ -36,8 +37,7 @@ abstract class CustomSerializer : AMQPSerializer { override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) { data.withDescribed(descriptor) { - @Suppress("UNCHECKED_CAST") - writeDescribedObject(obj as T, data, type, output) + writeDescribedObject(uncheckedCast(obj), data, type, output) } } @@ -49,7 +49,7 @@ abstract class CustomSerializer : AMQPSerializer { * subclass in the schema, so that we can distinguish between subclasses. */ // TODO: should this be a custom serializer at all, or should it just be a plain AMQPSerializer? - class SubClass(protected val clazz: Class<*>, protected val superClassSerializer: CustomSerializer) : CustomSerializer() { + class SubClass(protected val clazz: Class<*>, protected val superClassSerializer: CustomSerializer) : CustomSerializer() { // TODO: should this be empty or contain the schema of the super? override val schemaForDocumentation = Schema(emptyList()) @@ -76,7 +76,7 @@ abstract class CustomSerializer : AMQPSerializer { * Additional base features for a custom serializer for a particular class [withInheritance] is false * or super class / interfaces [withInheritance] is true */ - abstract class CustomSerializerImp(protected val clazz: Class, protected val withInheritance: Boolean) : CustomSerializer() { + abstract class CustomSerializerImp(protected val clazz: Class, protected val withInheritance: Boolean) : CustomSerializer() { override val type: Type get() = clazz override val typeDescriptor = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(clazz)}") override fun writeClassInfo(output: SerializationOutput) {} @@ -87,12 +87,12 @@ abstract class CustomSerializer : AMQPSerializer { /** * Additional base features for a custom serializer for a particular class, that excludes subclasses. */ - abstract class Is(clazz: Class) : CustomSerializerImp(clazz, false) + abstract class Is(clazz: Class) : CustomSerializerImp(clazz, false) /** * Additional base features for a custom serializer for all implementations of a particular interface or super class. */ - abstract class Implements(clazz: Class) : CustomSerializerImp(clazz, true) + abstract class Implements(clazz: Class) : CustomSerializerImp(clazz, true) /** * Additional base features over and above [Implements] or [Is] custom serializer for when the serialized form should be @@ -101,7 +101,7 @@ abstract class CustomSerializer : AMQPSerializer { * The proxy class must use only types which are either native AMQP or other types for which there are pre-registered * custom serializers. */ - abstract class Proxy(clazz: Class, + abstract class Proxy(clazz: Class, protected val proxyClass: Class

, protected val factory: SerializerFactory, withInheritance: Boolean = true) : CustomSerializerImp(clazz, withInheritance) { @@ -134,8 +134,7 @@ abstract class CustomSerializer : AMQPSerializer { } override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): T { - @Suppress("UNCHECKED_CAST") - val proxy = proxySerializer.readObject(obj, schema, input) as P + val proxy: P = uncheckedCast(proxySerializer.readObject(obj, schema, input)) return fromProxy(proxy) } } @@ -151,7 +150,7 @@ abstract class CustomSerializer : AMQPSerializer { * @param make A lambda for constructing an instance, that defaults to calling a constructor that expects a string. * @param unmake A lambda that extracts the string value for an instance, that defaults to the [toString] method. */ - abstract class ToString(clazz: Class, withInheritance: Boolean = false, + abstract class ToString(clazz: Class, withInheritance: Boolean = false, private val maker: (String) -> T = clazz.getConstructor(String::class.java).let { `constructor` -> { string -> `constructor`.newInstance(string) } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/MapSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/MapSerializer.kt index b343e96469..1fa710d59a 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/MapSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/MapSerializer.kt @@ -1,5 +1,6 @@ package net.corda.nodeapi.internal.serialization.amqp +import net.corda.core.internal.uncheckedCast import org.apache.qpid.proton.amqp.Symbol import org.apache.qpid.proton.codec.Data import java.io.NotSerializableException @@ -31,8 +32,7 @@ class MapSerializer(private val declaredType: ParameterizedType, factory: Serial LinkedHashMap::class.java to { map -> LinkedHashMap(map) }, TreeMap::class.java to { map -> TreeMap(map) }, EnumMap::class.java to { map -> - @Suppress("UNCHECKED_CAST") - EnumMap(map as Map) + EnumMap(uncheckedCast, Map>(map)) } )) @@ -44,8 +44,7 @@ class MapSerializer(private val declaredType: ParameterizedType, factory: Serial declaredClass.checkSupportedMapType() if(supportedTypes.containsKey(declaredClass)) { // Simple case - it is already known to be a map. - @Suppress("UNCHECKED_CAST") - return deriveParametrizedType(declaredType, declaredClass as Class>) + return deriveParametrizedType(declaredType, uncheckedCast(declaredClass)) } else if (actualClass != null && Map::class.java.isAssignableFrom(actualClass)) { // Declared class is not map, but [actualClass] is - represent it accordingly. diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/Schema.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/Schema.kt index 4ec6bb32cf..adb0c44f0c 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/Schema.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/Schema.kt @@ -2,6 +2,7 @@ package net.corda.nodeapi.internal.serialization.amqp import com.google.common.hash.Hasher import com.google.common.hash.Hashing +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.loggerFor import net.corda.core.utilities.toBase64 @@ -94,8 +95,7 @@ data class Schema(val types: List) : DescribedType { override fun newInstance(described: Any?): Schema { val list = described as? List<*> ?: throw IllegalStateException("Was expecting a list") - @Suppress("UNCHECKED_CAST") - return Schema(list[0] as List) + return Schema(uncheckedCast(list[0])) } } @@ -162,8 +162,7 @@ data class Field(val name: String, val type: String, val requires: List, override fun newInstance(described: Any?): Field { val list = described as? List<*> ?: throw IllegalStateException("Was expecting a list") - @Suppress("UNCHECKED_CAST") - return Field(list[0] as String, list[1] as String, list[2] as List, list[3] as? String, list[4] as? String, list[5] as Boolean, list[6] as Boolean) + return Field(list[0] as String, list[1] as String, uncheckedCast(list[2]), list[3] as? String, list[4] as? String, list[5] as Boolean, list[6] as Boolean) } } @@ -223,8 +222,7 @@ data class CompositeType(override val name: String, override val label: String?, override fun newInstance(described: Any?): CompositeType { val list = described as? List<*> ?: throw IllegalStateException("Was expecting a list") - @Suppress("UNCHECKED_CAST") - return CompositeType(list[0] as String, list[1] as? String, list[2] as List, list[3] as Descriptor, list[4] as List) + return CompositeType(list[0] as String, list[1] as? String, uncheckedCast(list[2]), list[3] as Descriptor, uncheckedCast(list[4])) } } @@ -273,8 +271,7 @@ data class RestrictedType(override val name: String, override fun newInstance(described: Any?): RestrictedType { val list = described as? List<*> ?: throw IllegalStateException("Was expecting a list") - @Suppress("UNCHECKED_CAST") - return RestrictedType(list[0] as String, list[1] as? String, list[2] as List, list[3] as String, list[4] as Descriptor, list[5] as List) + return RestrictedType(list[0] as String, list[1] as? String, uncheckedCast(list[2]), list[3] as String, list[4] as Descriptor, uncheckedCast(list[5])) } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt index 0077285e77..fe05093168 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt @@ -2,6 +2,7 @@ package net.corda.nodeapi.internal.serialization.amqp import com.google.common.primitives.Primitives import com.google.common.reflect.TypeResolver +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.ClassWhitelist import net.corda.core.serialization.CordaSerializable import net.corda.nodeapi.internal.serialization.carpenter.* @@ -262,8 +263,7 @@ class SerializerFactory(val whitelist: ClassWhitelist, cl: ClassLoader) { return customSerializer } else { // Make a subclass serializer for the subclass and return that... - @Suppress("UNCHECKED_CAST") - return CustomSerializer.SubClass(clazz, customSerializer as CustomSerializer) + return CustomSerializer.SubClass(clazz, uncheckedCast(customSerializer)) } } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/custom/EnumSetSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/custom/EnumSetSerializer.kt index 29527d21dd..5f86857ffe 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/custom/EnumSetSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/custom/EnumSetSerializer.kt @@ -1,11 +1,11 @@ package net.corda.nodeapi.internal.serialization.amqp.custom +import net.corda.core.internal.uncheckedCast import net.corda.nodeapi.internal.serialization.amqp.CustomSerializer import net.corda.nodeapi.internal.serialization.amqp.MapSerializer import net.corda.nodeapi.internal.serialization.amqp.SerializerFactory import java.util.* -@Suppress("UNCHECKED_CAST") /** * A serializer that writes out an [EnumSet] as a type, plus list of instances in the set. */ @@ -16,7 +16,7 @@ class EnumSetSerializer(factory: SerializerFactory) : CustomSerializer.Proxy): Class<*> { return if (set.isEmpty()) { - EnumSet.complementOf(set as EnumSet).first().javaClass + EnumSet.complementOf(uncheckedCast, EnumSet>(set)).first().javaClass } else { set.first().javaClass } @@ -24,9 +24,9 @@ class EnumSetSerializer(factory: SerializerFactory) : CustomSerializer.Proxy { return if (proxy.elements.isEmpty()) { - EnumSet.noneOf(proxy.clazz as Class) + EnumSet.noneOf(uncheckedCast, Class>(proxy.clazz)) } else { - EnumSet.copyOf(proxy.elements as List) + EnumSet.copyOf(uncheckedCast, List>(proxy.elements)) } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenter.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenter.kt index d47bc1bf52..9f727e09c7 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenter.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenter.kt @@ -237,10 +237,9 @@ class ClassCarpenter(cl: ClassLoader = Thread.currentThread().contextClassLoader } private fun ClassWriter.generateGetters(schema: Schema) { - @Suppress("UNCHECKED_CAST") - for ((name, type) in (schema.fields as Map)) { + for ((name, type) in schema.fields) { visitMethod(ACC_PUBLIC, "get" + name.capitalize(), "()" + type.descriptor, null, null).apply { - type.addNullabilityAnnotation(this) + (type as ClassField).addNullabilityAnnotation(this) visitCode() visitVarInsn(ALOAD, 0) // Load 'this' visitFieldInsn(GETFIELD, schema.jvmName, name, type.descriptor) @@ -258,8 +257,7 @@ class ClassCarpenter(cl: ClassLoader = Thread.currentThread().contextClassLoader } private fun ClassWriter.generateAbstractGetters(schema: Schema) { - @Suppress("UNCHECKED_CAST") - for ((name, field) in (schema.fields as Map)) { + for ((name, field) in schema.fields) { val opcodes = ACC_ABSTRACT + ACC_PUBLIC // abstract method doesn't have any implementation so just end visitMethod(opcodes, "get" + name.capitalize(), "()${field.descriptor}", null, null).visitEnd() @@ -363,9 +361,8 @@ class ClassCarpenter(cl: ClassLoader = Thread.currentThread().contextClassLoader // Assign the fields from parameters. var slot = 1 + superclassFields.size - @Suppress("UNCHECKED_CAST") - for ((name, field) in (schema.fields as Map)) { - field.nullTest(this, slot) + for ((name, field) in schema.fields) { + (field as ClassField).nullTest(this, slot) visitVarInsn(ALOAD, 0) // Load 'this' onto the stack slot += load(slot, field) // Load the contents of the parameter onto the stack. diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTest.kt index 913ea207c1..0c1c610c5a 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTest.kt @@ -1,5 +1,6 @@ package net.corda.nodeapi.internal.serialization.carpenter +import net.corda.core.internal.uncheckedCast import net.corda.nodeapi.internal.serialization.AllWhitelist import org.junit.Test import java.beans.Introspector @@ -323,7 +324,6 @@ class ClassCarpenterTest { } @Test - @Suppress("UNCHECKED_CAST") fun `int array`() { val className = "iEnjoyPotato" val schema = ClassSchema( @@ -356,7 +356,6 @@ class ClassCarpenterTest { } @Test - @Suppress("UNCHECKED_CAST") fun `integer array`() { val className = "iEnjoyFlan" val schema = ClassSchema( @@ -366,16 +365,15 @@ class ClassCarpenterTest { val clazz = cc.build(schema) val i = clazz.constructors[0].newInstance(arrayOf(1, 2, 3)) as SimpleFieldAccess - val arr = clazz.getMethod("getA").invoke(i) + val arr: Array = uncheckedCast(clazz.getMethod("getA").invoke(i)) - assertEquals(1, (arr as Array)[0]) + assertEquals(1, arr[0]) assertEquals(2, arr[1]) assertEquals(3, arr[2]) assertEquals("$className{a=[1, 2, 3]}", i.toString()) } @Test - @Suppress("UNCHECKED_CAST") fun `int array with ints`() { val className = "iEnjoyCrumble" val schema = ClassSchema( @@ -395,7 +393,6 @@ class ClassCarpenterTest { } @Test - @Suppress("UNCHECKED_CAST") fun `multiple int arrays`() { val className = "iEnjoyJam" val schema = ClassSchema( @@ -417,7 +414,6 @@ class ClassCarpenterTest { } @Test - @Suppress("UNCHECKED_CAST") fun `string array`() { val className = "iEnjoyToast" val schema = ClassSchema( @@ -427,7 +423,7 @@ class ClassCarpenterTest { val clazz = cc.build(schema) val i = clazz.constructors[0].newInstance(arrayOf("toast", "butter", "jam")) - val arr = clazz.getMethod("getA").invoke(i) as Array + val arr: Array = uncheckedCast(clazz.getMethod("getA").invoke(i)) assertEquals("toast", arr[0]) assertEquals("butter", arr[1]) @@ -435,7 +431,6 @@ class ClassCarpenterTest { } @Test - @Suppress("UNCHECKED_CAST") fun `string arrays`() { val className = "iEnjoyToast" val schema = ClassSchema( @@ -452,8 +447,8 @@ class ClassCarpenterTest { "and on the side", arrayOf("some pickles", "some fries")) - val arr1 = clazz.getMethod("getA").invoke(i) as Array - val arr2 = clazz.getMethod("getC").invoke(i) as Array + val arr1: Array = uncheckedCast(clazz.getMethod("getA").invoke(i)) + val arr2: Array = uncheckedCast(clazz.getMethod("getC").invoke(i)) assertEquals("bread", arr1[0]) assertEquals("spread", arr1[1]) diff --git a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt index 0c6b9cec56..50e9ac4866 100644 --- a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt @@ -18,6 +18,7 @@ import net.corda.core.internal.concurrent.doneFuture import net.corda.core.internal.concurrent.flatMap import net.corda.core.internal.concurrent.openFuture import net.corda.core.internal.toX509CertHolder +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.RPCOps import net.corda.core.messaging.SingleMessageRecipient @@ -322,11 +323,9 @@ abstract class AbstractNode(open val configuration: NodeConfiguration, } else { log.warn(deprecatedFlowConstructorMessage(initiatedFlow)) } - @Suppress("UNCHECKED_CAST") - { flowSession: FlowSession -> partyCtor.newInstance(flowSession.counterparty) as F } + { flowSession: FlowSession -> uncheckedCast(partyCtor.newInstance(flowSession.counterparty)) } } else { - @Suppress("UNCHECKED_CAST") - { flowSession: FlowSession -> flowSessionCtor.newInstance(flowSession) as F } + { flowSession: FlowSession -> uncheckedCast(flowSessionCtor.newInstance(flowSession)) } } val initiatingFlow = initiatedFlow.requireAnnotation().value.java val (version, classWithAnnotation) = initiatingFlow.flowVersionAndInitiatingClass diff --git a/node/src/main/kotlin/net/corda/node/services/api/ServiceHubInternal.kt b/node/src/main/kotlin/net/corda/node/services/api/ServiceHubInternal.kt index 1e2625ffb4..5492f24c1d 100644 --- a/node/src/main/kotlin/net/corda/node/services/api/ServiceHubInternal.kt +++ b/node/src/main/kotlin/net/corda/node/services/api/ServiceHubInternal.kt @@ -8,6 +8,7 @@ import net.corda.core.flows.StateMachineRunId import net.corda.core.identity.Party import net.corda.core.internal.FlowStateMachine import net.corda.core.internal.VisibleForTesting +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.DataFeed import net.corda.core.messaging.SingleMessageRecipient import net.corda.core.messaging.StateMachineTransactionMapping @@ -132,8 +133,7 @@ interface ServiceHubInternal : ServiceHub { flowInitiator: FlowInitiator, vararg args: Any?): FlowStateMachineImpl { val logicRef = FlowLogicRefFactoryImpl.createForRPC(logicType, *args) - @Suppress("UNCHECKED_CAST") - val logic = FlowLogicRefFactoryImpl.toFlowLogic(logicRef) as FlowLogic + val logic: FlowLogic = uncheckedCast(FlowLogicRefFactoryImpl.toFlowLogic(logicRef)) return startFlow(logic, flowInitiator, ourIdentity = null) } diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt index 784776820c..32c866da19 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt @@ -11,6 +11,7 @@ import net.corda.core.internal.ThreadBox import net.corda.core.internal.concurrent.openFuture import net.corda.core.internal.div import net.corda.core.internal.noneOrSingle +import net.corda.core.internal.uncheckedCast import net.corda.core.node.NodeInfo import net.corda.core.node.services.NetworkMapCache import net.corda.core.node.services.NetworkMapCache.MapChange @@ -56,7 +57,6 @@ import java.math.BigInteger import java.security.KeyStore import java.security.KeyStoreException import java.security.Principal -import java.security.cert.X509Certificate import java.util.* import java.util.concurrent.Executor import java.util.concurrent.ScheduledExecutorService @@ -478,8 +478,7 @@ private class VerifyingNettyConnector(configuration: MutableMap, override fun createConnection(): Connection? { val connection = super.createConnection() as? NettyConnection if (sslEnabled && connection != null) { - @Suppress("UNCHECKED_CAST") - val expectedLegalNames = (configuration[ArtemisTcpTransport.VERIFY_PEER_LEGAL_NAME] ?: emptySet()) as Set + val expectedLegalNames: Set = uncheckedCast(configuration[ArtemisTcpTransport.VERIFY_PEER_LEGAL_NAME] ?: emptySet()) try { val session = connection.channel .pipeline() @@ -608,12 +607,11 @@ class NodeLoginModule : LoginModule { private lateinit var verifierCertCheck: CertificateChainCheckPolicy.Check private val principals = ArrayList() - @Suppress("UNCHECKED_CAST") override fun initialize(subject: Subject, callbackHandler: CallbackHandler, sharedState: Map, options: Map) { this.subject = subject this.callbackHandler = callbackHandler userService = options[RPCUserService::class.java.name] as RPCUserService - val certChainChecks = options[CERT_CHAIN_CHECKS_OPTION_NAME] as Map + val certChainChecks: Map = uncheckedCast(options[CERT_CHAIN_CHECKS_OPTION_NAME]) peerCertCheck = certChainChecks[PEER_ROLE]!! nodeCertCheck = certChainChecks[NODE_ROLE]!! verifierCertCheck = certChainChecks[VERIFIER_ROLE]!! diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt b/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt index 062919084e..b05dc10c02 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt @@ -4,6 +4,7 @@ import com.google.common.util.concurrent.ListenableFuture import net.corda.core.concurrent.CordaFuture import net.corda.core.identity.CordaX500Name import net.corda.core.internal.concurrent.openFuture +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.MessageRecipients import net.corda.core.messaging.SingleMessageRecipient import net.corda.core.node.services.PartyInfo @@ -161,8 +162,7 @@ fun MessagingService.onNext(topic: String, sessionId: Long): CordaFutu val messageFuture = openFuture() runOnNextMessage(topic, sessionId) { message -> messageFuture.capture { - @Suppress("UNCHECKED_CAST") - message.data.deserialize() as M + uncheckedCast(message.data.deserialize()) } } return messageFuture diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt index 1556ef31c3..b3103f979e 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt @@ -12,12 +12,9 @@ import net.corda.core.crypto.random63BitValue import net.corda.core.flows.* import net.corda.core.identity.Party import net.corda.core.identity.PartyAndCertificate -import net.corda.core.internal.FlowStateMachine -import net.corda.core.internal.abbreviate +import net.corda.core.internal.* import net.corda.core.internal.concurrent.OpenFuture import net.corda.core.internal.concurrent.openFuture -import net.corda.core.internal.isRegularFile -import net.corda.core.internal.staticField import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.* import net.corda.node.services.api.FlowAppAuditEvent @@ -281,7 +278,7 @@ class FlowStateMachineImpl(override val id: StateMachineRunId, } // TODO Dummy implementation of access to application specific audit logging - override fun recordAuditEvent(eventType: String, comment: String, extraAuditData: Map): Unit { + override fun recordAuditEvent(eventType: String, comment: String, extraAuditData: Map) { val flowAuditEvent = FlowAppAuditEvent( serviceHub.clock.instant(), flowInitiator, @@ -430,8 +427,7 @@ class FlowStateMachineImpl(override val id: StateMachineRunId, val session = receiveRequest.session val receiveType = receiveRequest.receiveType if (receiveType.isInstance(message)) { - @Suppress("UNCHECKED_CAST") - return this as ReceivedSessionMessage + return uncheckedCast(this) } else if (message is SessionEnd) { openSessions.values.remove(session) if (message is ErrorSessionEnd) { @@ -519,7 +515,6 @@ class FlowStateMachineImpl(override val id: StateMachineRunId, } } -@Suppress("UNCHECKED_CAST") val Class>.flowVersionAndInitiatingClass: Pair>> get() { var current: Class<*> = this var found: Pair>>? = null @@ -528,7 +523,7 @@ val Class>.flowVersionAndInitiatingClass: Pair 0) { "Flow versions have to be greater or equal to 1" } - found = annotation.version to (current as Class>) + found = annotation.version to uncheckedCast(current) } current = current.superclass ?: return found diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt index dc2a8342cb..2382614752 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt @@ -14,9 +14,7 @@ import net.corda.core.crypto.SecureHash import net.corda.core.crypto.random63BitValue import net.corda.core.flows.* import net.corda.core.identity.Party -import net.corda.core.internal.ThreadBox -import net.corda.core.internal.bufferUntilSubscribed -import net.corda.core.internal.castIfPossible +import net.corda.core.internal.* import net.corda.core.messaging.DataFeed import net.corda.core.serialization.SerializationDefaults.CHECKPOINT_CONTEXT import net.corda.core.serialization.SerializationDefaults.SERIALIZATION_FACTORY @@ -149,10 +147,9 @@ class StateMachineManager(val serviceHub: ServiceHubInternal, /** Returns a list of all state machines executing the given flow logic at the top level (subflows do not count) */ fun

, T> findStateMachines(flowClass: Class

): List>> { - @Suppress("UNCHECKED_CAST") return mutex.locked { stateMachines.keys.mapNotNull { - flowClass.castIfPossible(it.logic)?.let { it to (it.stateMachine as FlowStateMachineImpl).resultFuture } + flowClass.castIfPossible(it.logic)?.let { it to uncheckedCast, FlowStateMachineImpl>(it.stateMachine).resultFuture } } } } diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/PathManager.kt b/node/src/main/kotlin/net/corda/node/services/transactions/PathManager.kt index 7a031540f9..20e69d5aae 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/PathManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/PathManager.kt @@ -1,5 +1,6 @@ package net.corda.node.services.transactions +import net.corda.core.internal.uncheckedCast import net.corda.nodeapi.internal.addShutdownHook import java.io.Closeable import java.nio.file.Path @@ -31,8 +32,7 @@ open class PathManager>(path: Path) : Closeable { fun handle(): T { handleCounter.incrementAndGet() - @Suppress("UNCHECKED_CAST") - return this as T + return uncheckedCast(this) } override fun close() { diff --git a/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt b/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt index 575d1cbfc9..30c32220f7 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt @@ -3,6 +3,7 @@ package net.corda.node.services.vault import net.corda.core.contracts.ContractState import net.corda.core.contracts.StateRef import net.corda.core.identity.AbstractParty +import net.corda.core.internal.uncheckedCast import net.corda.core.node.services.Vault import net.corda.core.node.services.VaultQueryException import net.corda.core.node.services.vault.* @@ -111,8 +112,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class { - @Suppress("UNCHECKED_CAST") - val literal = columnPredicate.rightLiteral as Comparable? + val literal: Comparable? = uncheckedCast(columnPredicate.rightLiteral) @Suppress("UNCHECKED_CAST") column as Path?> when (columnPredicate.operator) { @@ -139,10 +139,8 @@ class HibernateQueryCriteriaParser(val contractStateType: Class { @Suppress("UNCHECKED_CAST") column as Path?> - @Suppress("UNCHECKED_CAST") - val fromLiteral = columnPredicate.rightFromLiteral as Comparable? - @Suppress("UNCHECKED_CAST") - val toLiteral = columnPredicate.rightToLiteral as Comparable? + val fromLiteral: Comparable? = uncheckedCast(columnPredicate.rightFromLiteral) + val toLiteral: Comparable? = uncheckedCast(columnPredicate.rightToLiteral) criteriaBuilder.between(column, fromLiteral, toLiteral) } is ColumnPredicate.NullExpression -> { diff --git a/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt b/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt index 27afbc2040..3501c2db34 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/HibernateVaultQueryImpl.kt @@ -7,6 +7,7 @@ import net.corda.core.contracts.TransactionState import net.corda.core.crypto.SecureHash import net.corda.core.internal.ThreadBox import net.corda.core.internal.bufferUntilSubscribed +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.DataFeed import net.corda.core.node.services.Vault import net.corda.core.node.services.VaultQueryException @@ -153,8 +154,7 @@ class HibernateVaultQueryImpl(val hibernateConfig: HibernateConfiguration, override fun _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class): DataFeed, Vault.Update> { return mutex.locked { val snapshotResults = _queryBy(criteria, paging, sorting, contractStateType) - @Suppress("UNCHECKED_CAST") - val updates = vault.updatesPublisher.bufferUntilSubscribed().filter { it.containsType(contractStateType, snapshotResults.stateTypes) } as Observable> + val updates: Observable> = uncheckedCast(vault.updatesPublisher.bufferUntilSubscribed().filter { it.containsType(contractStateType, snapshotResults.stateTypes) }) DataFeed(snapshotResults, updates) } } @@ -180,8 +180,7 @@ class HibernateVaultQueryImpl(val hibernateConfig: HibernateConfiguration, val contractInterfaceToConcreteTypes = mutableMapOf>() distinctTypes.forEach { type -> - @Suppress("UNCHECKED_CAST") - val concreteType = Class.forName(type) as Class + val concreteType: Class = uncheckedCast(Class.forName(type)) val contractInterfaces = deriveContractInterfaces(concreteType) contractInterfaces.map { val contractInterface = contractInterfaceToConcreteTypes.getOrPut(it.name, { mutableSetOf() }) @@ -196,9 +195,8 @@ class HibernateVaultQueryImpl(val hibernateConfig: HibernateConfiguration, val myInterfaces: MutableSet> = mutableSetOf() clazz.interfaces.forEach { if (!it.equals(ContractState::class.java)) { - @Suppress("UNCHECKED_CAST") - myInterfaces.add(it as Class) - myInterfaces.addAll(deriveContractInterfaces(it)) + myInterfaces.add(uncheckedCast(it)) + myInterfaces.addAll(deriveContractInterfaces(uncheckedCast(it))) } } return myInterfaces diff --git a/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt b/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt index 668236515a..35e695d78e 100644 --- a/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt +++ b/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt @@ -233,8 +233,7 @@ object InteractiveShell { return } - @Suppress("UNCHECKED_CAST") - val clazz = matches.single() as Class> + val clazz: Class> = uncheckedCast(matches.single()) try { // TODO Flow invocation should use startFlowDynamic. val fsm = runFlowFromString({ node.services.startFlow(it, FlowInitiator.Shell) }, inputData, clazz) @@ -434,8 +433,6 @@ object InteractiveShell { } } - // Kotlin bug: USELESS_CAST warning is generated below but the IDE won't let us remove it. - @Suppress("USELESS_CAST", "UNCHECKED_CAST") private fun maybeFollow(response: Any?, printerFun: (Any?) -> String, toStream: PrintWriter): OpenFuture? { // Match on a couple of common patterns for "important" observables. It's tough to do this in a generic // way because observables can be embedded anywhere in the object graph, and can emit other arbitrary @@ -454,7 +451,7 @@ object InteractiveShell { } ?: return null val subscriber = PrintingSubscriber(printerFun, toStream) - (observable as Observable).subscribe(subscriber) + uncheckedCast(observable).subscribe(subscriber) return subscriber.future } diff --git a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt index e7d1074362..f2cb795f36 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt @@ -5,7 +5,7 @@ import net.corda.core.contracts.* import net.corda.core.crypto.TransactionSignature import net.corda.core.flows.* import net.corda.core.identity.Party -import net.corda.core.node.NodeInfo +import net.corda.core.internal.uncheckedCast import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.TransactionBuilder @@ -46,7 +46,6 @@ object FixingFlow { @Suspendable override fun assembleSharedTX(handshake: TwoPartyDealFlow.Handshake): Triple, List> { - @Suppress("UNCHECKED_CAST") val fixOf = deal.nextFixingOf()!! // TODO Do we need/want to substitute in new public keys for the Parties? @@ -91,9 +90,8 @@ object FixingFlow { class Floater(override val otherSideSession: FlowSession, override val payload: FixingSession, override val progressTracker: ProgressTracker = TwoPartyDealFlow.Primary.tracker()) : TwoPartyDealFlow.Primary() { - @Suppress("UNCHECKED_CAST") private val dealToFix: StateAndRef by transient { - val state = serviceHub.loadState(payload.ref) as TransactionState + val state: TransactionState = uncheckedCast(serviceHub.loadState(payload.ref)) StateAndRef(state, payload.ref) } diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt index 4642412d9b..687ccbe857 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/IRSSimulation.kt @@ -11,6 +11,7 @@ import net.corda.core.flows.InitiatedBy import net.corda.core.flows.InitiatingFlow import net.corda.core.identity.Party import net.corda.core.internal.FlowStateMachine +import net.corda.core.internal.uncheckedCast import net.corda.core.node.services.queryBy import net.corda.core.toFuture import net.corda.core.transactions.SignedTransaction @@ -155,9 +156,8 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten val acceptDealFlows: Observable = node2.internals.registerInitiatedFlow(AcceptDealFlow::class.java) - @Suppress("UNCHECKED_CAST") val acceptorTxFuture = acceptDealFlows.toFuture().toCompletableFuture().thenCompose { - (it.stateMachine as FlowStateMachine).resultFuture.toCompletableFuture() + uncheckedCast, FlowStateMachine>(it.stateMachine).resultFuture.toCompletableFuture() } showProgressFor(listOf(node1, node2)) diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/RPCDriver.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/RPCDriver.kt index 8bb2bd9a0c..4aff94842f 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/RPCDriver.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/RPCDriver.kt @@ -10,6 +10,7 @@ import net.corda.core.identity.CordaX500Name import net.corda.core.internal.concurrent.fork import net.corda.core.internal.concurrent.map import net.corda.core.internal.div +import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.RPCOps import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.RPCUserService @@ -507,8 +508,7 @@ class RandomRpcUser { @JvmStatic fun main(args: Array) { require(args.size == 4) - @Suppress("UNCHECKED_CAST") - val rpcClass = Class.forName(args[0]) as Class + val rpcClass: Class = uncheckedCast(Class.forName(args[0])) val hostAndPort = NetworkHostAndPort.parse(args[1]) val username = args[2] val password = args[3] diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt index 5a55586924..bedda6486b 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/CoreTestUtils.kt @@ -1,4 +1,4 @@ -@file:Suppress("UNUSED_PARAMETER", "UNCHECKED_CAST") +@file:Suppress("UNUSED_PARAMETER") @file:JvmName("CoreTestUtils") package net.corda.testing diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/Expect.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/Expect.kt index 1128186c67..0db4754f4c 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/Expect.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/Expect.kt @@ -1,6 +1,7 @@ package net.corda.testing import com.google.common.util.concurrent.SettableFuture +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.getOrThrow import org.slf4j.Logger import org.slf4j.LoggerFactory @@ -213,9 +214,8 @@ private sealed class ExpectComposeState { class Single(val single: ExpectCompose.Single) : ExpectComposeState() { override fun nextState(event: E): Pair<() -> Unit, ExpectComposeState>? = if (single.expect.clazz.isAssignableFrom(event.javaClass)) { - @Suppress("UNCHECKED_CAST") - val coercedEvent = event as T - if (single.expect.match(event)) { + val coercedEvent: T = uncheckedCast(event) + if (single.expect.match(coercedEvent)) { Pair({ single.expect.expectClosure(coercedEvent) }, Finished()) } else { null @@ -285,8 +285,7 @@ private sealed class ExpectComposeState { is ExpectCompose.Single -> { // This coercion should not be needed but kotlin can't reason about existential type variables(T) // so here we're coercing T into E (even though T is invariant). - @Suppress("UNCHECKED_CAST") - Single(expectCompose as ExpectCompose.Single) + Single(uncheckedCast(expectCompose)) } is ExpectCompose.Sequential -> { if (expectCompose.sequence.size > 0) { diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/FlowStackSnapshot.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/FlowStackSnapshot.kt index 94eb3a7a12..d51d5e7fe5 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/FlowStackSnapshot.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/FlowStackSnapshot.kt @@ -16,6 +16,7 @@ import net.corda.core.internal.div import net.corda.core.internal.write import net.corda.core.serialization.SerializeAsToken import net.corda.client.jackson.JacksonSupport +import net.corda.core.internal.uncheckedCast import net.corda.node.services.statemachine.FlowStackSnapshotFactory import java.nio.file.Path import java.time.Instant @@ -134,11 +135,10 @@ class FlowStackSnapshotFactoryImpl : FlowStackSnapshotFactory { } -private inline fun R.getField(name: String): A { +private inline fun R.getField(name: String): A { val field = R::class.java.getDeclaredField(name) field.isAccessible = true - @Suppress("UNCHECKED_CAST") - return field.get(this) as A + return uncheckedCast(field.get(this)) } private fun getFiberStack(fiber: Fiber<*>): Stack { diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/Measure.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/Measure.kt index d3a6f9f65d..102cc0f413 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/Measure.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/Measure.kt @@ -1,5 +1,6 @@ package net.corda.testing +import net.corda.core.internal.uncheckedCast import kotlin.reflect.KCallable import kotlin.reflect.jvm.reflect @@ -9,18 +10,14 @@ import kotlin.reflect.jvm.reflect * different combinations of parameters. */ -@Suppress("UNCHECKED_CAST") -fun measure(a: Iterable, f: (A) -> R) = - measure(listOf(a), f.reflect()!!) { (f as ((Any?)->R))(it[0]) } -@Suppress("UNCHECKED_CAST") -fun measure(a: Iterable, b: Iterable, f: (A, B) -> R) = - measure(listOf(a, b), f.reflect()!!) { (f as ((Any?,Any?)->R))(it[0], it[1]) } -@Suppress("UNCHECKED_CAST") -fun measure(a: Iterable, b: Iterable, c: Iterable, f: (A, B, C) -> R) = - measure(listOf(a, b, c), f.reflect()!!) { (f as ((Any?,Any?,Any?)->R))(it[0], it[1], it[2]) } -@Suppress("UNCHECKED_CAST") -fun measure(a: Iterable, b: Iterable, c: Iterable, d: Iterable, f: (A, B, C, D) -> R) = - measure(listOf(a, b, c, d), f.reflect()!!) { (f as ((Any?,Any?,Any?,Any?)->R))(it[0], it[1], it[2], it[3]) } +fun measure(a: Iterable, f: (A) -> R) = + measure(listOf(a), f.reflect()!!) { f(uncheckedCast(it[0])) } +fun measure(a: Iterable, b: Iterable, f: (A, B) -> R) = + measure(listOf(a, b), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1])) } +fun measure(a: Iterable, b: Iterable, c: Iterable, f: (A, B, C) -> R) = + measure(listOf(a, b, c), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1]), uncheckedCast(it[2])) } +fun measure(a: Iterable, b: Iterable, c: Iterable, d: Iterable, f: (A, B, C, D) -> R) = + measure(listOf(a, b, c, d), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1]), uncheckedCast(it[2]), uncheckedCast(it[3])) } private fun measure(paramIterables: List>, kCallable: KCallable, call: (Array) -> R): Iterable> { val kParameters = kCallable.parameters diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt index 84d0512a05..6db7662380 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt @@ -5,6 +5,7 @@ import net.corda.core.cordapp.CordappProvider import net.corda.core.crypto.* import net.corda.core.crypto.NullKeys.NULL_SIGNATURE import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.node.ServiceHub import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.TransactionBuilder @@ -188,8 +189,8 @@ data class TestLedgerDSLInterpreter private constructor( nonVerifiedTransactionWithLocations[stateRef.txhash] ?: throw TransactionResolutionException(stateRef.txhash) val output = transactionWithLocation.transaction.outputs[stateRef.index] - return if (S::class.java.isAssignableFrom(output.data.javaClass)) @Suppress("UNCHECKED_CAST") { - output as TransactionState + return if (S::class.java.isAssignableFrom(output.data.javaClass)) { + uncheckedCast(output) } else { throw TypeMismatch(requested = S::class.java, actual = output.data.javaClass) } @@ -313,8 +314,7 @@ data class TestLedgerDSLInterpreter private constructor( } else if (!clazz.isAssignableFrom(stateAndRef.state.data.javaClass)) { throw TypeMismatch(requested = clazz, actual = stateAndRef.state.data.javaClass) } else { - @Suppress("UNCHECKED_CAST") - return stateAndRef as StateAndRef + return uncheckedCast(stateAndRef) } } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/model/User.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/model/User.kt index aadbeb7e06..c55f3bc5d3 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/model/User.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/model/User.kt @@ -2,14 +2,14 @@ package net.corda.demobench.model +import net.corda.core.internal.uncheckedCast import net.corda.nodeapi.User import java.util.* -@Suppress("UNCHECKED_CAST") fun toUser(map: Map) = User( map.getOrElse("username", { "none" }) as String, map.getOrElse("password", { "none" }) as String, - LinkedHashSet(map.getOrElse("permissions", { emptyList() }) as Collection) + LinkedHashSet(uncheckedCast>(map.getOrElse("permissions", { emptyList() }))) ) fun user(name: String) = User(name, "letmein", setOf("ALL")) diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/model/SettingsModel.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/model/SettingsModel.kt index 5df84b94fd..19bba7b639 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/model/SettingsModel.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/model/SettingsModel.kt @@ -7,6 +7,7 @@ import javafx.beans.property.SimpleObjectProperty import net.corda.core.internal.createDirectories import net.corda.core.internal.div import net.corda.core.internal.exists +import net.corda.core.internal.uncheckedCast import tornadofx.* import java.nio.file.Files import java.nio.file.Path @@ -52,14 +53,13 @@ class SettingsModel(path: Path = Paths.get("conf")) : Component(), Observable { // Save all changes in memory to properties file. fun commit() = Files.newOutputStream(path).use { config.store(it, "") } - @Suppress("UNCHECKED_CAST") private operator fun Properties.getValue(receiver: Any, metadata: KProperty<*>): T { return when (metadata.returnType.javaType) { - String::class.java -> string(metadata.name, "") as T - Int::class.java -> string(metadata.name, "0").toInt() as T - Boolean::class.java -> boolean(metadata.name) as T - Currency::class.java -> Currency.getInstance(string(metadata.name, "USD")) as T - Path::class.java -> Paths.get(string(metadata.name, "")).toAbsolutePath() as T + String::class.java -> uncheckedCast(string(metadata.name, "")) + Int::class.java -> uncheckedCast(string(metadata.name, "0").toInt()) + Boolean::class.java -> uncheckedCast(boolean(metadata.name)) + Currency::class.java -> uncheckedCast(Currency.getInstance(string(metadata.name, "USD"))) + Path::class.java -> uncheckedCast(Paths.get(string(metadata.name, "")).toAbsolutePath()) else -> throw IllegalArgumentException("Unsupported type ${metadata.returnType}") } } diff --git a/webserver/src/main/kotlin/net/corda/webserver/converters/Converters.kt b/webserver/src/main/kotlin/net/corda/webserver/converters/Converters.kt index ca47c80173..f0e20a037e 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/converters/Converters.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/converters/Converters.kt @@ -1,6 +1,7 @@ package net.corda.webserver.converters import net.corda.core.identity.CordaX500Name +import net.corda.core.internal.uncheckedCast import java.lang.reflect.Type import javax.ws.rs.ext.ParamConverter import javax.ws.rs.ext.ParamConverterProvider @@ -15,8 +16,7 @@ object CordaX500NameConverter : ParamConverter { object CordaConverterProvider : ParamConverterProvider { override fun getConverter(rawType: Class, genericType: Type?, annotations: Array?): ParamConverter? { if (rawType == CordaX500Name::class.java) { - @Suppress("UNCHECKED_CAST") - return CordaX500NameConverter as ParamConverter + return uncheckedCast(CordaX500NameConverter) } return null }