uncheckedCast crusade (#1667)

This commit is contained in:
Andrzej Cichocki 2017-09-27 12:58:48 +01:00 committed by GitHub
parent c6c4c13bee
commit 9874e1ff34
51 changed files with 172 additions and 231 deletions

View File

@ -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}")
}

View File

@ -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<StateAndRef<ContractState>>.filterCashStateAndRefs(): List<StateAndRef<Cash.State>> {
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<Cash.State>
uncheckedCast(stateAndRef)
} else {
null
}

View File

@ -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 <reified M : Any> get(origin: KClass<*>): M = get(M::class, origin)

View File

@ -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 <A, B> ObservableValue<out A>.bind(function: (A) -> ObservableValue<B>): Obs
* propagate variance constraints and type inference fails.
*/
fun <A, B> ObservableValue<out A>.bindOut(function: (A) -> ObservableValue<out B>): ObservableValue<out B> =
@Suppress("UNCHECKED_CAST")
EasyBind.monadic(this).flatMap(function as (A) -> ObservableValue<B>)
EasyBind.monadic(this).flatMap(uncheckedCast(function))
/**
* enum class FilterCriterion { HEIGHT, NAME }
@ -105,8 +105,7 @@ fun <A, B> ObservableValue<out A>.bindOut(function: (A) -> ObservableValue<out B
*/
fun <A> ObservableList<out A>.filter(predicate: ObservableValue<(A) -> Boolean>): ObservableList<A> {
// We cast here to enforce variance, FilteredList should be covariant
@Suppress("UNCHECKED_CAST")
return FilteredList<A>(this as ObservableList<A>).apply {
return FilteredList<A>(uncheckedCast(this)).apply {
predicateProperty().bind(predicate.map { predicateFunction ->
Predicate<A> { predicateFunction(it) }
})
@ -120,13 +119,11 @@ fun <A> ObservableList<out A>.filter(predicate: ObservableValue<(A) -> Boolean>)
*/
fun <A> ObservableList<out A?>.filterNotNull(): ObservableList<A> {
//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<A?>).filtered(object : Predicate<A?> {
return uncheckedCast(uncheckedCast<Any, ObservableList<A?>>(this).filtered(object : Predicate<A?> {
override fun test(t: A?): Boolean {
return t != null
}
}) as ObservableList<A>
}))
}
/**

View File

@ -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<out A>(val generate: (SplittableRandom) -> Try<A>) {
fun <A> frequency(vararg generators: Pair<Double, Generator<A>>) = frequency(generators.toList())
fun <A> sequence(generators: List<Generator<A>>) = Generator {
fun <A> sequence(generators: List<Generator<A>>) = Generator<List<A>> {
val result = mutableListOf<A>()
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<List<A>>
is Try.Failure -> return@Generator uncheckedCast(element)
}
}
Try.Success(result)
@ -175,7 +175,7 @@ class Generator<out A>(val generate: (SplittableRandom) -> Try<A>) {
}
fun <A> replicatePoisson(meanSize: Double, generator: Generator<A>, atLeastOne: Boolean = false) = Generator {
fun <A> replicatePoisson(meanSize: Double, generator: Generator<A>, atLeastOne: Boolean = false) = Generator<List<A>> {
val chance = (meanSize - 1) / meanSize
val result = mutableListOf<A>()
var finish = false
@ -191,8 +191,7 @@ class Generator<out A>(val generate: (SplittableRandom) -> Try<A>) {
}
}
if (res is Try.Failure) {
@Suppress("UNCHECKED_CAST")
return@Generator res as Try<List<A>>
return@Generator uncheckedCast(res)
}
}
Try.Success(result)

View File

@ -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<I : RPCOps>(
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" +

View File

@ -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 <reified T : CommandData> Collection<CommandWithParties<CommandData>>
/** Ensures that a transaction has only one command that is of the given type, otherwise throws an exception. */
fun <C : CommandData> Collection<CommandWithParties<CommandData>>.requireSingleCommand(klass: Class<C>) =
mapNotNull { @Suppress("UNCHECKED_CAST") if (klass.isInstance(it.value)) it as CommandWithParties<C> else null }.single()
mapNotNull { if (klass.isInstance(it.value)) uncheckedCast<CommandWithParties<CommandData>, CommandWithParties<C>>(it) else null }.single()
/**
* Simple functionality for verifying a move command. Verifies that each input has a signature from its owning key.

View File

@ -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<T : Any>(val raw: SerializedBytes<T>, val sig: DigitalSign
@Throws(SignatureException::class)
fun verified(): T {
sig.by.verify(raw.bytes, sig)
@Suppress("UNCHECKED_CAST")
val data = raw.deserialize<Any>() as T
val data: T = uncheckedCast(raw.deserialize<Any>())
verifyData(data)
return data
}

View File

@ -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<PublicKey> = input.data.participants.map { it.owningKey }.toSet()
val keysThatSigned: Set<PublicKey> = commandData.signers.toSet()
@Suppress("UNCHECKED_CAST")
val upgradedContract = javaClass.classLoader.loadClass(command.upgradedContractClass).newInstance() as UpgradedContract<ContractState, *>
val upgradedContract: UpgradedContract<ContractState, *> = 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)

View File

@ -114,8 +114,7 @@ sealed class FetchDataFlow<T : NamedByHash, in W : Any>(
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<ArrayList<W>>,
requests: List<SecureHash>): List<T> {

View File

@ -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 <reified T> Stream<out T>.toTypedArray() = toArray { size -> arrayOfNulls<T>(size) } as Array<T>
// When toArray has filled in the array, the component type is no longer T? but T (that may itself be nullable):
inline fun <reified T> Stream<out T>.toTypedArray(): Array<T> = uncheckedCast(toArray { size -> arrayOfNulls<T>(size) })
fun <T> Class<T>.castIfPossible(obj: Any): T? = if (isInstance(obj)) cast(obj) else null
@ -256,8 +256,7 @@ fun <T: Any> KClass<T>.objectOrNewInstance(): T {
class DeclaredField<T>(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<Any?, T>(javaField.get(receiver))
set(value) = javaField.set(receiver, value)
}

View File

@ -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 <O, R> resolveEnclosingObjectFromExpression(expression: CriteriaExpression<O
}
}
@Suppress("UNCHECKED_CAST")
fun <O, C> resolveEnclosingObjectFromColumn(column: Column<O, C>): Class<O> = column.declaringClass as Class<O>
fun <O, C> resolveEnclosingObjectFromColumn(column: Column<O, C>): Class<O> = uncheckedCast(column.declaringClass)
fun <O, C> getColumnName(column: Column<O, C>): String = column.name
/**

View File

@ -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 <T : ContractState> outRef(index: Int): StateAndRef<T> = StateAndRef(outputs[index] as TransactionState<T>, StateRef(id, index))
fun <T : ContractState> outRef(index: Int): StateAndRef<T> = 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 <T : ContractState> outRefsOfType(clazz: Class<T>): List<StateAndRef<T>> {
return outputs.mapIndexedNotNull { index, state ->
@Suppress("UNCHECKED_CAST")
clazz.castIfPossible(state.data)?.let { StateAndRef(state as TransactionState<T>, StateRef(id, index)) }
clazz.castIfPossible(state.data)?.let { StateAndRef<T>(uncheckedCast(state), StateRef(id, index)) }
}
}

View File

@ -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 <T : ContractState> inRef(index: Int): StateAndRef<T> = inputs[index] as StateAndRef<T>
fun <T : ContractState> inRef(index: Int): StateAndRef<T> = 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 <T : ContractState> inRefsOfType(clazz: Class<T>): List<StateAndRef<T>> {
@Suppress("UNCHECKED_CAST")
return inputs.mapNotNull { if (clazz.isInstance(it.state.data)) it as StateAndRef<T> else null }
return inputs.mapNotNull { if (clazz.isInstance(it.state.data)) uncheckedCast<StateAndRef<ContractState>, StateAndRef<T>>(it) else null }
}
inline fun <reified T : ContractState> inRefsOfType(): List<StateAndRef<T>> = 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 <T : CommandData> getCommand(index: Int): Command<T> = Command(commands[index].value as T, commands[index].signers)
fun <T : CommandData> getCommand(index: Int): Command<T> = 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.

View File

@ -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<out T> 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)
}
}

View File

@ -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<out A> {
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 <B> map(function: (A) -> B): Try<B> = when (this) {
is Success -> Success(function(value))
is Failure -> this as Try<B>
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 <B> flatMap(function: (A) -> Try<B>): Try<B> = when (this) {
is Success -> function(value)
is Failure -> this as Try<B>
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 <B, C> combine(other: Try<B>, function: (A, B) -> C): Try<C> = when (this) {
is Success -> when (other) {
is Success -> Success(function(value, other.value))
is Failure -> other as Try<C>
is Failure -> uncheckedCast(other)
}
is Failure -> this as Try<C>
is Failure -> uncheckedCast(this)
}
data class Success<out A>(val value: A) : Try<A>() {

View File

@ -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 <T> replaceStartEnd(p: Perceivable<T>, start: Instant, end: Instant): Perceivable<T> =
when (p) {
is Const -> p
is TimePerceivable -> TimePerceivable(p.cmp, replaceStartEnd(p.instant, start, end)) as Perceivable<T>
is EndDate -> const(end) as Perceivable<T>
is StartDate -> const(start) as Perceivable<T>
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<T>(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<T>
is Fixing -> Fixing(p.source, replaceStartEnd(p.date, start, end), p.tenor) as Perceivable<T>
is PerceivableAnd -> (replaceStartEnd(p.left, start, end) and replaceStartEnd(p.right, start, end)) as Perceivable<T>
is PerceivableOr -> (replaceStartEnd(p.left, start, end) or replaceStartEnd(p.right, start, end)) as Perceivable<T>
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 <T> replaceFixing(tx: LedgerTransaction, perceivable: Perceivable<T>,
fixings: Map<FixOf, BigDecimal>, unusedFixings: MutableSet<FixOf>): Perceivable<T> =
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<T>
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<T>
uncheckedCast(Const(fixings[FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)]!!))
} else perceivable
}
else -> throw NotImplementedError("replaceFixing - " + perceivable.javaClass.name)

View File

@ -39,7 +39,6 @@ private fun rowsToAmount(currency: Currency, rows: Vault.Page<FungibleAsset<*>>)
} 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)
}

View File

@ -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])

View File

@ -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 <T> Config.getValue(receiver: Any, metadata: KProperty<*>): T {
operator fun <T : Any> 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 <T> Config.getValueInternal(path: String, type: KType): T {
return (if (type.arguments.isEmpty()) getSingleValue(path, type) else getCollectionValue(path, type)) as T
private fun <T : Any> 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<Proxy.Type>, name) // Any enum will do
private fun parseEnum(enumType: Class<*>, name: String): Enum<*> = enumBridge<Proxy.Type>(uncheckedCast(enumType), name) // Any enum will do
private fun <T : Enum<T>> enumBridge(clazz: Class<T>, name: String): T = java.lang.Enum.valueOf(clazz, name)

View File

@ -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<WireTransaction>() {
kryo.writeClassAndObject(output, obj.privacySalt)
}
@Suppress("UNCHECKED_CAST")
override fun read(kryo: Kryo, input: Input, type: Class<WireTransaction>): WireTransaction {
val componentGroups = kryo.readClassAndObject(input) as List<ComponentGroup>
val componentGroups: List<ComponentGroup> = uncheckedCast(kryo.readClassAndObject(input))
val privacySalt = kryo.readClassAndObject(input) as PrivacySalt
return WireTransaction(componentGroups, privacySalt)
}
@ -261,9 +261,8 @@ object NotaryChangeWireTransactionSerializer : Serializer<NotaryChangeWireTransa
kryo.writeClassAndObject(output, obj.newNotary)
}
@Suppress("UNCHECKED_CAST")
override fun read(kryo: Kryo, input: Input, type: Class<NotaryChangeWireTransaction>): NotaryChangeWireTransaction {
val inputs = kryo.readClassAndObject(input) as List<StateRef>
val inputs: List<StateRef> = 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<SignedTransaction>() {
kryo.writeClassAndObject(output, obj.sigs)
}
@Suppress("UNCHECKED_CAST")
override fun read(kryo: Kryo, input: Input, type: Class<SignedTransaction>): SignedTransaction {
return SignedTransaction(
kryo.readClassAndObject(input) as SerializedBytes<CoreTransaction>,
kryo.readClassAndObject(input) as List<TransactionSignature>
uncheckedCast<Any?, SerializedBytes<CoreTransaction>>(kryo.readClassAndObject(input)),
uncheckedCast<Any?, List<TransactionSignature>>(kryo.readClassAndObject(input))
)
}
}
@ -600,8 +598,7 @@ class ThrowableSerializer<T>(kryo: Kryo, type: Class<T>) : Serializer<Throwable>
}
}
@Suppress("UNCHECKED_CAST")
private val delegate: Serializer<Throwable> = ReflectionSerializerFactory.makeSerializer(kryo, FieldSerializer::class.java, type) as Serializer<Throwable>
private val delegate: Serializer<Throwable> = uncheckedCast(ReflectionSerializerFactory.makeSerializer(kryo, FieldSerializer::class.java, type))
override fun write(kryo: Kryo, output: Output, throwable: Throwable) {
delegate.write(kryo, output, throwable)

View File

@ -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<Any?, T>(kryo.readClassAndObject(input)) }
}
}
}

View File

@ -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<out Collection<*>>)
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.

View File

@ -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<T> : AMQPSerializer<T> {
abstract class CustomSerializer<T : Any> : AMQPSerializer<T> {
/**
* 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<T> : AMQPSerializer<T> {
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<T> : AMQPSerializer<T> {
* 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<T>(protected val clazz: Class<*>, protected val superClassSerializer: CustomSerializer<T>) : CustomSerializer<T>() {
class SubClass<T : Any>(protected val clazz: Class<*>, protected val superClassSerializer: CustomSerializer<T>) : CustomSerializer<T>() {
// TODO: should this be empty or contain the schema of the super?
override val schemaForDocumentation = Schema(emptyList())
@ -76,7 +76,7 @@ abstract class CustomSerializer<T> : AMQPSerializer<T> {
* Additional base features for a custom serializer for a particular class [withInheritance] is false
* or super class / interfaces [withInheritance] is true
*/
abstract class CustomSerializerImp<T>(protected val clazz: Class<T>, protected val withInheritance: Boolean) : CustomSerializer<T>() {
abstract class CustomSerializerImp<T : Any>(protected val clazz: Class<T>, protected val withInheritance: Boolean) : CustomSerializer<T>() {
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<T> : AMQPSerializer<T> {
/**
* Additional base features for a custom serializer for a particular class, that excludes subclasses.
*/
abstract class Is<T>(clazz: Class<T>) : CustomSerializerImp<T>(clazz, false)
abstract class Is<T : Any>(clazz: Class<T>) : CustomSerializerImp<T>(clazz, false)
/**
* Additional base features for a custom serializer for all implementations of a particular interface or super class.
*/
abstract class Implements<T>(clazz: Class<T>) : CustomSerializerImp<T>(clazz, true)
abstract class Implements<T : Any>(clazz: Class<T>) : CustomSerializerImp<T>(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<T> : AMQPSerializer<T> {
* 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<T, P>(clazz: Class<T>,
abstract class Proxy<T : Any, P : Any>(clazz: Class<T>,
protected val proxyClass: Class<P>,
protected val factory: SerializerFactory,
withInheritance: Boolean = true) : CustomSerializerImp<T>(clazz, withInheritance) {
@ -134,8 +134,7 @@ abstract class CustomSerializer<T> : AMQPSerializer<T> {
}
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<T> : AMQPSerializer<T> {
* @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<T>(clazz: Class<T>, withInheritance: Boolean = false,
abstract class ToString<T : Any>(clazz: Class<T>, withInheritance: Boolean = false,
private val maker: (String) -> T = clazz.getConstructor(String::class.java).let {
`constructor` ->
{ string -> `constructor`.newInstance(string) }

View File

@ -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<EnumJustUsedForCasting, Any>)
EnumMap(uncheckedCast<Map<*, *>, Map<EnumJustUsedForCasting, Any>>(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<out Map<*, *>>)
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.

View File

@ -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<TypeNotation>) : 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<TypeNotation>)
return Schema(uncheckedCast(list[0]))
}
}
@ -162,8 +162,7 @@ data class Field(val name: String, val type: String, val requires: List<String>,
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<String>, 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<String>, list[3] as Descriptor, list[4] as List<Field>)
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<String>, list[3] as String, list[4] as Descriptor, list[5] as List<Choice>)
return RestrictedType(list[0] as String, list[1] as? String, uncheckedCast(list[2]), list[3] as String, list[4] as Descriptor, uncheckedCast(list[5]))
}
}

View File

@ -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<Any>)
return CustomSerializer.SubClass(clazz, uncheckedCast(customSerializer))
}
}
}

View File

@ -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<Enu
private fun elementType(set: EnumSet<*>): Class<*> {
return if (set.isEmpty()) {
EnumSet.complementOf(set as EnumSet<MapSerializer.EnumJustUsedForCasting>).first().javaClass
EnumSet.complementOf(uncheckedCast<EnumSet<*>, EnumSet<MapSerializer.EnumJustUsedForCasting>>(set)).first().javaClass
} else {
set.first().javaClass
}
@ -24,9 +24,9 @@ class EnumSetSerializer(factory: SerializerFactory) : CustomSerializer.Proxy<Enu
override fun fromProxy(proxy: EnumSetProxy): EnumSet<*> {
return if (proxy.elements.isEmpty()) {
EnumSet.noneOf(proxy.clazz as Class<MapSerializer.EnumJustUsedForCasting>)
EnumSet.noneOf(uncheckedCast<Class<*>, Class<MapSerializer.EnumJustUsedForCasting>>(proxy.clazz))
} else {
EnumSet.copyOf(proxy.elements as List<MapSerializer.EnumJustUsedForCasting>)
EnumSet.copyOf(uncheckedCast<List<Any>, List<MapSerializer.EnumJustUsedForCasting>>(proxy.elements))
}
}

View File

@ -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<String, ClassField>)) {
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<String, ClassField>)) {
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<String, ClassField>)) {
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.

View File

@ -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<Int> = uncheckedCast(clazz.getMethod("getA").invoke(i))
assertEquals(1, (arr as Array<Int>)[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<String>
val arr: Array<String> = 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<String>
val arr2 = clazz.getMethod("getC").invoke(i) as Array<String>
val arr1: Array<String> = uncheckedCast(clazz.getMethod("getA").invoke(i))
val arr2: Array<String> = uncheckedCast(clazz.getMethod("getC").invoke(i))
assertEquals("bread", arr1[0])
assertEquals("spread", arr1[1])

View File

@ -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<InitiatedBy>().value.java
val (version, classWithAnnotation) = initiatingFlow.flowVersionAndInitiatingClass

View File

@ -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<T> {
val logicRef = FlowLogicRefFactoryImpl.createForRPC(logicType, *args)
@Suppress("UNCHECKED_CAST")
val logic = FlowLogicRefFactoryImpl.toFlowLogic(logicRef) as FlowLogic<T>
val logic: FlowLogic<T> = uncheckedCast(FlowLogicRefFactoryImpl.toFlowLogic(logicRef))
return startFlow(logic, flowInitiator, ourIdentity = null)
}

View File

@ -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<String, Any>,
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<CordaX500Name>()) as Set<CordaX500Name>
val expectedLegalNames: Set<CordaX500Name> = uncheckedCast(configuration[ArtemisTcpTransport.VERIFY_PEER_LEGAL_NAME] ?: emptySet<CordaX500Name>())
try {
val session = connection.channel
.pipeline()
@ -608,12 +607,11 @@ class NodeLoginModule : LoginModule {
private lateinit var verifierCertCheck: CertificateChainCheckPolicy.Check
private val principals = ArrayList<Principal>()
@Suppress("UNCHECKED_CAST")
override fun initialize(subject: Subject, callbackHandler: CallbackHandler, sharedState: Map<String, *>, options: Map<String, *>) {
this.subject = subject
this.callbackHandler = callbackHandler
userService = options[RPCUserService::class.java.name] as RPCUserService
val certChainChecks = options[CERT_CHAIN_CHECKS_OPTION_NAME] as Map<String, CertificateChainCheckPolicy.Check>
val certChainChecks: Map<String, CertificateChainCheckPolicy.Check> = uncheckedCast(options[CERT_CHAIN_CHECKS_OPTION_NAME])
peerCertCheck = certChainChecks[PEER_ROLE]!!
nodeCertCheck = certChainChecks[NODE_ROLE]!!
verifierCertCheck = certChainChecks[VERIFIER_ROLE]!!

View File

@ -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 <M : Any> MessagingService.onNext(topic: String, sessionId: Long): CordaFutu
val messageFuture = openFuture<M>()
runOnNextMessage(topic, sessionId) { message ->
messageFuture.capture {
@Suppress("UNCHECKED_CAST")
message.data.deserialize<Any>() as M
uncheckedCast(message.data.deserialize<Any>())
}
}
return messageFuture

View File

@ -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<R>(override val id: StateMachineRunId,
}
// TODO Dummy implementation of access to application specific audit logging
override fun recordAuditEvent(eventType: String, comment: String, extraAuditData: Map<String, String>): Unit {
override fun recordAuditEvent(eventType: String, comment: String, extraAuditData: Map<String, String>) {
val flowAuditEvent = FlowAppAuditEvent(
serviceHub.clock.instant(),
flowInitiator,
@ -430,8 +427,7 @@ class FlowStateMachineImpl<R>(override val id: StateMachineRunId,
val session = receiveRequest.session
val receiveType = receiveRequest.receiveType
if (receiveType.isInstance(message)) {
@Suppress("UNCHECKED_CAST")
return this as ReceivedSessionMessage<M>
return uncheckedCast(this)
} else if (message is SessionEnd) {
openSessions.values.remove(session)
if (message is ErrorSessionEnd) {
@ -519,7 +515,6 @@ class FlowStateMachineImpl<R>(override val id: StateMachineRunId,
}
}
@Suppress("UNCHECKED_CAST")
val Class<out FlowLogic<*>>.flowVersionAndInitiatingClass: Pair<Int, Class<out FlowLogic<*>>> get() {
var current: Class<*> = this
var found: Pair<Int, Class<out FlowLogic<*>>>? = null
@ -528,7 +523,7 @@ val Class<out FlowLogic<*>>.flowVersionAndInitiatingClass: Pair<Int, Class<out F
if (annotation != null) {
if (found != null) throw IllegalArgumentException("${InitiatingFlow::class.java.name} can only be annotated once")
require(annotation.version > 0) { "Flow versions have to be greater or equal to 1" }
found = annotation.version to (current as Class<out FlowLogic<*>>)
found = annotation.version to uncheckedCast(current)
}
current = current.superclass
?: return found

View File

@ -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 <P : FlowLogic<T>, T> findStateMachines(flowClass: Class<P>): List<Pair<P, CordaFuture<T>>> {
@Suppress("UNCHECKED_CAST")
return mutex.locked {
stateMachines.keys.mapNotNull {
flowClass.castIfPossible(it.logic)?.let { it to (it.stateMachine as FlowStateMachineImpl<T>).resultFuture }
flowClass.castIfPossible(it.logic)?.let { it to uncheckedCast<FlowStateMachine<*>, FlowStateMachineImpl<T>>(it.stateMachine).resultFuture }
}
}
}

View File

@ -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<T : PathManager<T>>(path: Path) : Closeable {
fun handle(): T {
handleCounter.incrementAndGet()
@Suppress("UNCHECKED_CAST")
return this as T
return uncheckedCast(this)
}
override fun close() {

View File

@ -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<out ContractStat
}
}
is ColumnPredicate.BinaryComparison -> {
@Suppress("UNCHECKED_CAST")
val literal = columnPredicate.rightLiteral as Comparable<Any?>?
val literal: Comparable<Any?>? = uncheckedCast(columnPredicate.rightLiteral)
@Suppress("UNCHECKED_CAST")
column as Path<Comparable<Any?>?>
when (columnPredicate.operator) {
@ -139,10 +139,8 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
is ColumnPredicate.Between -> {
@Suppress("UNCHECKED_CAST")
column as Path<Comparable<Any?>?>
@Suppress("UNCHECKED_CAST")
val fromLiteral = columnPredicate.rightFromLiteral as Comparable<Any?>?
@Suppress("UNCHECKED_CAST")
val toLiteral = columnPredicate.rightToLiteral as Comparable<Any?>?
val fromLiteral: Comparable<Any?>? = uncheckedCast(columnPredicate.rightFromLiteral)
val toLiteral: Comparable<Any?>? = uncheckedCast(columnPredicate.rightToLiteral)
criteriaBuilder.between(column, fromLiteral, toLiteral)
}
is ColumnPredicate.NullExpression -> {

View File

@ -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 <T : ContractState> _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> {
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<Vault.Update<T>>
val updates: Observable<Vault.Update<T>> = 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<String, MutableSet<String>>()
distinctTypes.forEach { type ->
@Suppress("UNCHECKED_CAST")
val concreteType = Class.forName(type) as Class<ContractState>
val concreteType: Class<ContractState> = 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<Class<T>> = mutableSetOf()
clazz.interfaces.forEach {
if (!it.equals(ContractState::class.java)) {
@Suppress("UNCHECKED_CAST")
myInterfaces.add(it as Class<T>)
myInterfaces.addAll(deriveContractInterfaces(it))
myInterfaces.add(uncheckedCast(it))
myInterfaces.addAll(deriveContractInterfaces(uncheckedCast(it)))
}
}
return myInterfaces

View File

@ -233,8 +233,7 @@ object InteractiveShell {
return
}
@Suppress("UNCHECKED_CAST")
val clazz = matches.single() as Class<FlowLogic<*>>
val clazz: Class<FlowLogic<*>> = 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<Unit>? {
// 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<Any>).subscribe(subscriber)
uncheckedCast(observable).subscribe(subscriber)
return subscriber.future
}

View File

@ -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<FixingSession>): Triple<TransactionBuilder, List<PublicKey>, List<TransactionSignature>> {
@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<FixableDealState> by transient {
val state = serviceHub.loadState(payload.ref) as TransactionState<FixableDealState>
val state: TransactionState<FixableDealState> = uncheckedCast(serviceHub.loadState(payload.ref))
StateAndRef(state, payload.ref)
}

View File

@ -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<AcceptDealFlow> = node2.internals.registerInitiatedFlow(AcceptDealFlow::class.java)
@Suppress("UNCHECKED_CAST")
val acceptorTxFuture = acceptDealFlows.toFuture().toCompletableFuture().thenCompose {
(it.stateMachine as FlowStateMachine<SignedTransaction>).resultFuture.toCompletableFuture()
uncheckedCast<FlowStateMachine<*>, FlowStateMachine<SignedTransaction>>(it.stateMachine).resultFuture.toCompletableFuture()
}
showProgressFor(listOf(node1, node2))

View File

@ -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<String>) {
require(args.size == 4)
@Suppress("UNCHECKED_CAST")
val rpcClass = Class.forName(args[0]) as Class<RPCOps>
val rpcClass: Class<RPCOps> = uncheckedCast(Class.forName(args[0]))
val hostAndPort = NetworkHostAndPort.parse(args[1])
val username = args[2]
val password = args[3]

View File

@ -1,4 +1,4 @@
@file:Suppress("UNUSED_PARAMETER", "UNCHECKED_CAST")
@file:Suppress("UNUSED_PARAMETER")
@file:JvmName("CoreTestUtils")
package net.corda.testing

View File

@ -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<E : Any> {
class Single<E : Any, T : E>(val single: ExpectCompose.Single<E, T>) : ExpectComposeState<E>() {
override fun nextState(event: E): Pair<() -> Unit, ExpectComposeState<E>>? =
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<E : Any> {
is ExpectCompose.Single<E, *> -> {
// 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<E, E>)
Single(uncheckedCast(expectCompose))
}
is ExpectCompose.Sequential -> {
if (expectCompose.sequence.size > 0) {

View File

@ -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 <reified R, A> R.getField(name: String): A {
private inline fun <reified R, A : Any> 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 {

View File

@ -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 <A, R> measure(a: Iterable<A>, f: (A) -> R) =
measure(listOf(a), f.reflect()!!) { (f as ((Any?)->R))(it[0]) }
@Suppress("UNCHECKED_CAST")
fun <A, B, R> measure(a: Iterable<A>, b: Iterable<B>, f: (A, B) -> R) =
measure(listOf(a, b), f.reflect()!!) { (f as ((Any?,Any?)->R))(it[0], it[1]) }
@Suppress("UNCHECKED_CAST")
fun <A, B, C, R> measure(a: Iterable<A>, b: Iterable<B>, c: Iterable<C>, 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 <A, B, C, D, R> measure(a: Iterable<A>, b: Iterable<B>, c: Iterable<C>, d: Iterable<D>, 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 <A : Any, R> measure(a: Iterable<A>, f: (A) -> R) =
measure(listOf(a), f.reflect()!!) { f(uncheckedCast(it[0])) }
fun <A : Any, B : Any, R> measure(a: Iterable<A>, b: Iterable<B>, f: (A, B) -> R) =
measure(listOf(a, b), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1])) }
fun <A : Any, B : Any, C : Any, R> measure(a: Iterable<A>, b: Iterable<B>, c: Iterable<C>, f: (A, B, C) -> R) =
measure(listOf(a, b, c), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1]), uncheckedCast(it[2])) }
fun <A : Any, B : Any, C : Any, D : Any, R> measure(a: Iterable<A>, b: Iterable<B>, c: Iterable<C>, d: Iterable<D>, 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 <R> measure(paramIterables: List<Iterable<Any?>>, kCallable: KCallable<R>, call: (Array<Any?>) -> R): Iterable<MeasureResult<R>> {
val kParameters = kCallable.parameters

View File

@ -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<S>
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<S>
return uncheckedCast(stateAndRef)
}
}

View File

@ -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<String, Any>) = User(
map.getOrElse("username", { "none" }) as String,
map.getOrElse("password", { "none" }) as String,
LinkedHashSet<String>(map.getOrElse("permissions", { emptyList<String>() }) as Collection<String>)
LinkedHashSet(uncheckedCast<Any, Collection<String>>(map.getOrElse("permissions", { emptyList<String>() })))
)
fun user(name: String) = User(name, "letmein", setOf("ALL"))

View File

@ -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 <T> 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}")
}
}

View File

@ -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<CordaX500Name> {
object CordaConverterProvider : ParamConverterProvider {
override fun <T : Any> getConverter(rawType: Class<T>, genericType: Type?, annotations: Array<out Annotation>?): ParamConverter<T>? {
if (rawType == CordaX500Name::class.java) {
@Suppress("UNCHECKED_CAST")
return CordaX500NameConverter as ParamConverter<T>
return uncheckedCast(CordaX500NameConverter)
}
return null
}