ENT-11351 - Compiler warnings pass 4 (#7663)

* Compiler warnings

* Resolve detekt errors

* Reverted code change; added warning suppression

* Address PR review comments
This commit is contained in:
Chris Cochrane
2024-01-29 13:49:00 +00:00
committed by GitHub
parent a7d0684fe7
commit 9b794795a0
19 changed files with 39 additions and 26 deletions

View File

@ -315,8 +315,7 @@ object JacksonSupport {
private class CertPathSerializer : JsonSerializer<CertPath>() { private class CertPathSerializer : JsonSerializer<CertPath>() {
override fun serialize(value: CertPath, gen: JsonGenerator, serializers: SerializerProvider) { override fun serialize(value: CertPath, gen: JsonGenerator, serializers: SerializerProvider) {
val certificates = value.certificates as List<X509Certificate> gen.writeObject(CertPathWrapper(value.type, uncheckedCast(value.certificates)))
gen.writeObject(CertPathWrapper(value.type, certificates))
} }
} }

View File

@ -85,7 +85,7 @@ class FastThreadLocalTest {
} }
private class UnserializableObj { private class UnserializableObj {
@Suppress("unused") @Suppress("unused", "IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION")
private val fail: Nothing by lazy { throw UnsupportedOperationException("Nice try.") } private val fail: Nothing by lazy { throw UnsupportedOperationException("Nice try.") }
} }

View File

@ -257,7 +257,7 @@ class FlowExternalOperationTest : AbstractFlowExternalOperationTest() {
@Suspendable @Suspendable
override fun testCode() { override fun testCode() {
val e = createException() val e = createException()
await(ExternalOperation(serviceHub, (SerializableLambda2 { _, _ -> throw e }))) await<Nothing>(ExternalOperation(serviceHub, (SerializableLambda2 { _, _ -> throw e })))
} }
private fun createException() = when (exceptionType) { private fun createException() = when (exceptionType) {
@ -273,7 +273,7 @@ class FlowExternalOperationTest : AbstractFlowExternalOperationTest() {
@Suspendable @Suspendable
override fun testCode(): Any = try { override fun testCode(): Any = try {
await(ExternalOperation(serviceHub) { _, _ -> await<Nothing>(ExternalOperation(serviceHub) { _, _ ->
throw IllegalStateException("threw exception in background process") throw IllegalStateException("threw exception in background process")
}) })
} catch (e: IllegalStateException) { } catch (e: IllegalStateException) {
@ -287,7 +287,7 @@ class FlowExternalOperationTest : AbstractFlowExternalOperationTest() {
@Suspendable @Suspendable
override fun testCode(): Any = override fun testCode(): Any =
await(ExternalOperation(serviceHub) { serviceHub, _ -> await<Nothing>(ExternalOperation(serviceHub) { serviceHub, _ ->
serviceHub.cordaService(FutureService::class.java).throwHospitalHandledException() serviceHub.cordaService(FutureService::class.java).throwHospitalHandledException()
}) })
} }
@ -298,7 +298,7 @@ class FlowExternalOperationTest : AbstractFlowExternalOperationTest() {
@Suspendable @Suspendable
override fun testCode(): Any { override fun testCode(): Any {
try { try {
await(ExternalOperation(serviceHub) { _, _ -> await<Nothing>(ExternalOperation(serviceHub) { _, _ ->
serviceHub.cordaService(FutureService::class.java).throwHospitalHandledException() serviceHub.cordaService(FutureService::class.java).throwHospitalHandledException()
}) })
} catch (e: NullPointerException) { } catch (e: NullPointerException) {

View File

@ -74,12 +74,12 @@ data class _L_i__ (val listy: List<_i_>)
data class _ALd_ (val a: Array<List<Double>>) data class _ALd_ (val a: Array<List<Double>>)
@Suppress("UNUSED_PARAMETER") @Suppress("UNUSED_PARAMETER", "PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun main (args: Array<String>) { fun main (args: Array<String>) {
initialiseSerialization() initialiseSerialization()
val path = "../cpp-serializer/bin/test-files"; val path = "../cpp-serializer/bin/test-files";
File("$path/_i_").writeBytes (_i_ (69).serialize().bytes) File("$path/_i_").writeBytes (_i_ (69).serialize().bytes)
File("$path/_Oi_").writeBytes (_Oi_ (Integer (1)).serialize().bytes) File("$path/_Oi_").writeBytes (_Oi_ (Integer.valueOf (1) as Integer).serialize().bytes)
File("$path/_l_").writeBytes (_l_ (100000000000L).serialize().bytes) File("$path/_l_").writeBytes (_l_ (100000000000L).serialize().bytes)
File("$path/_Li_").writeBytes (_Li_(listOf (1, 2, 3, 4, 5, 6)).serialize().bytes) File("$path/_Li_").writeBytes (_Li_(listOf (1, 2, 3, 4, 5, 6)).serialize().bytes)
File("$path/_Ai_").writeBytes (_Ai_(arrayOf (1, 2, 3, 4, 5, 6)).serialize().bytes) File("$path/_Ai_").writeBytes (_Ai_(arrayOf (1, 2, 3, 4, 5, 6)).serialize().bytes)

View File

@ -138,6 +138,7 @@ abstract class AbstractCashSelection(private val maxRetries : Int = 8, private v
if (stateRefs.isNotEmpty()) { if (stateRefs.isNotEmpty()) {
// TODO: future implementation to retrieve contract states from a Vault BLOB store // TODO: future implementation to retrieve contract states from a Vault BLOB store
@Suppress("UNCHECKED_CAST")
stateAndRefs.addAll(services.loadStates(stateRefs) as Collection<out StateAndRef<Cash.State>>) stateAndRefs.addAll(services.loadStates(stateRefs) as Collection<out StateAndRef<Cash.State>>)
} }

View File

@ -8,6 +8,7 @@ import net.corda.core.crypto.newSecureRandom
import net.corda.core.internal.CertRole import net.corda.core.internal.CertRole
import net.corda.core.internal.SignedDataWithCert import net.corda.core.internal.SignedDataWithCert
import net.corda.core.internal.signWithCert import net.corda.core.internal.signWithCert
import net.corda.core.internal.uncheckedCast
import net.corda.core.internal.validate import net.corda.core.internal.validate
import net.corda.core.utilities.days import net.corda.core.utilities.days
import net.corda.core.utilities.millis import net.corda.core.utilities.millis
@ -424,7 +425,7 @@ val CertPath.x509Certificates: List<X509Certificate>
get() { get() {
require(type == "X.509") { "Not an X.509 cert path: $this" } require(type == "X.509") { "Not an X.509 cert path: $this" }
// We're not mapping the list to avoid creating a new one. // We're not mapping the list to avoid creating a new one.
return certificates as List<X509Certificate> return uncheckedCast(certificates)
} }
val Certificate.x509: X509Certificate get() = requireNotNull(this as? X509Certificate) { "Not an X.509 certificate: $this" } val Certificate.x509: X509Certificate get() = requireNotNull(this as? X509Certificate) { "Not an X.509 certificate: $this" }

View File

@ -490,7 +490,8 @@ class ThrowableSerializer<T>(kryo: Kryo, type: Class<T>) : Serializer<Throwable>
} }
} }
private val delegate: Serializer<Throwable> = uncheckedCast(SerializerFactory.ReflectionSerializerFactory.newSerializer(kryo, FieldSerializer::class.java, type)) as Serializer<Throwable> @Suppress("UNCHECKED_CAST")
private val delegate: Serializer<Throwable> = SerializerFactory.ReflectionSerializerFactory.newSerializer(kryo, FieldSerializer::class.java, type) as Serializer<Throwable>
override fun write(kryo: Kryo, output: Output, throwable: Throwable) { override fun write(kryo: Kryo, output: Output, throwable: Throwable) {
delegate.write(kryo, output, throwable) delegate.write(kryo, output, throwable)

View File

@ -9,7 +9,6 @@ import org.apache.activemq.artemis.core.remoting.impl.ssl.DefaultOpenSSLContextF
import org.apache.activemq.artemis.core.remoting.impl.ssl.DefaultSSLContextFactory import org.apache.activemq.artemis.core.remoting.impl.ssl.DefaultSSLContextFactory
import org.apache.activemq.artemis.spi.core.remoting.ssl.SSLContextConfig import org.apache.activemq.artemis.spi.core.remoting.ssl.SSLContextConfig
import org.apache.activemq.artemis.utils.ClassloadingUtil import org.apache.activemq.artemis.utils.ClassloadingUtil
import org.apache.commons.io.IOUtils
import java.io.File import java.io.File
import java.io.InputStream import java.io.InputStream
import java.net.MalformedURLException import java.net.MalformedURLException
@ -125,4 +124,12 @@ private fun findResource(resourceName: String): URL {
* This is an inline function for [InputStream] so it can be closed and * This is an inline function for [InputStream] so it can be closed and
* ignore an exception. * ignore an exception.
*/ */
private fun InputStream?.closeQuietly() = IOUtils.closeQuietly(this) private fun InputStream?.closeQuietly() {
try {
this?.close()
}
catch ( ex : Exception ) {
// quietly absorb problems
}
}

View File

@ -52,13 +52,14 @@ class AbstractPartyDescriptor(private val wellKnownPartyFromX500Name: (CordaX500
} }
} }
@Suppress("UNCHECKED_CAST")
override fun <X : Any> unwrap(value: AbstractParty?, type: Class<X>, options: WrapperOptions): X? { override fun <X : Any> unwrap(value: AbstractParty?, type: Class<X>, options: WrapperOptions): X? {
return if (value != null) { return if (value != null) {
if (AbstractParty::class.java.isAssignableFrom(type)) { if (AbstractParty::class.java.isAssignableFrom(type)) {
return uncheckedCast(value) return uncheckedCast(value)
} }
if (String::class.java.isAssignableFrom(type)) { if (String::class.java.isAssignableFrom(type)) {
return uncheckedCast(toString(value)) as X? return toString(value) as X?
} }
throw unknownUnwrap(type) throw unknownUnwrap(type)
} else { } else {

View File

@ -38,7 +38,6 @@ import net.corda.core.internal.FlowIORequest
import net.corda.core.internal.WaitForStateConsumption import net.corda.core.internal.WaitForStateConsumption
import net.corda.core.internal.declaredField import net.corda.core.internal.declaredField
import net.corda.core.internal.objectOrNewInstance import net.corda.core.internal.objectOrNewInstance
import net.corda.core.internal.uncheckedCast
import net.corda.core.node.AppServiceHub.Companion.SERVICE_PRIORITY_NORMAL import net.corda.core.node.AppServiceHub.Companion.SERVICE_PRIORITY_NORMAL
import net.corda.core.node.ServiceHub import net.corda.core.node.ServiceHub
import net.corda.core.serialization.SerializeAsToken import net.corda.core.serialization.SerializeAsToken
@ -594,6 +593,7 @@ class CheckpointDumperImpl(private val checkpointStorage: CheckpointStorage, pri
gen.writeEndArray() gen.writeEndArray()
} }
override fun handledType(): Class<Map<Any, Any>> = uncheckedCast(Map::class.java) as Class<Map<Any, Any>> @Suppress("UNCHECKED_CAST")
override fun handledType(): Class<Map<Any, Any>> = Map::class.java as Class<Map<Any, Any>>
} }
} }

View File

@ -40,7 +40,7 @@ internal class RpcBrokerConfiguration(baseDirectory: Path, maxMessageSize: Int,
queueConfigs = queueConfigurations() queueConfigs = queueConfigurations()
managementNotificationAddress = SimpleString(ArtemisMessagingComponent.NOTIFICATIONS_ADDRESS) managementNotificationAddress = SimpleString(ArtemisMessagingComponent.NOTIFICATIONS_ADDRESS)
addressesSettings = mapOf( addressSettings = mapOf(
"${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.#" to AddressSettings().apply { "${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.#" to AddressSettings().apply {
maxSizeBytes = 5L * maxMessageSize maxSizeBytes = 5L * maxMessageSize
addressFullMessagePolicy = AddressFullMessagePolicy.PAGE addressFullMessagePolicy = AddressFullMessagePolicy.PAGE

View File

@ -1239,6 +1239,7 @@ internal class SingleThreadedStateMachineManager(
null null
} else { } else {
val existingFuture = activeOrRemovedClientIdFutureForReattach(it, clientId) val existingFuture = activeOrRemovedClientIdFutureForReattach(it, clientId)
@Suppress("UNCHECKED_CAST")
existingFuture?.let {existingFuture.get() } as FlowStateMachineHandle<T> existingFuture?.let {existingFuture.get() } as FlowStateMachineHandle<T>
} }
} }

View File

@ -839,7 +839,8 @@ class NodeVaultService(
@Throws(VaultQueryException::class) @Throws(VaultQueryException::class)
override fun <T : ContractState> _trackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>): DataFeed<Vault.Page<T>, Vault.Update<T>> { 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 { return mutex.locked {
val updates: Observable<Vault.Update<T>> = uncheckedCast(_updatesPublisher.bufferUntilSubscribed()) as Observable<Vault.Update<T>> @Suppress("UNCHECKED_CAST")
val updates: Observable<Vault.Update<T>> = _updatesPublisher.bufferUntilSubscribed() as Observable<Vault.Update<T>>
if (contextTransactionOrNull != null) { if (contextTransactionOrNull != null) {
log.warn("trackBy is called with an already existing, open DB transaction. As a result, there might be states missing from both the snapshot and observable, included in the returned data feed, because of race conditions.") log.warn("trackBy is called with an already existing, open DB transaction. As a result, there might be states missing from both the snapshot and observable, included in the returned data feed, because of race conditions.")
} }

View File

@ -26,6 +26,7 @@ import net.corda.core.internal.notary.NotaryInternalException
import net.corda.core.internal.notary.isConsumedByTheSameTx import net.corda.core.internal.notary.isConsumedByTheSameTx
import net.corda.core.internal.notary.validateTimeWindow import net.corda.core.internal.notary.validateTimeWindow
import net.corda.core.internal.toTypedArray import net.corda.core.internal.toTypedArray
import net.corda.core.internal.uncheckedCast
import net.corda.core.schemas.PersistentStateRef import net.corda.core.schemas.PersistentStateRef
import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.CordaSerializable
import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken
@ -215,7 +216,7 @@ object BFTSmart {
} }
override fun appExecuteBatch(command: Array<ByteArray>, mcs: Array<MessageContext>): Array<ByteArray?> { override fun appExecuteBatch(command: Array<ByteArray>, mcs: Array<MessageContext>): Array<ByteArray?> {
return Arrays.stream(command).map(this::executeCommand).toTypedArray() as Array<ByteArray?> return uncheckedCast(Arrays.stream(command).map(this::executeCommand).toTypedArray())
} }
/** /**

View File

@ -15,7 +15,6 @@ import net.corda.core.flows.StartableByRPC
import net.corda.core.flows.StateMachineRunId import net.corda.core.flows.StateMachineRunId
import net.corda.core.identity.Party import net.corda.core.identity.Party
import net.corda.core.internal.RPC_UPLOADER import net.corda.core.internal.RPC_UPLOADER
import net.corda.core.internal.uncheckedCast
import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.CordaRPCOps
import net.corda.core.messaging.StateMachineUpdate import net.corda.core.messaging.StateMachineUpdate
import net.corda.core.messaging.startFlow import net.corda.core.messaging.startFlow
@ -408,7 +407,8 @@ class CordaRPCOpsImplTest {
@Test(timeout=300_000) @Test(timeout=300_000)
fun `non-ContractState class for the contractStateType param in vault queries`() { fun `non-ContractState class for the contractStateType param in vault queries`() {
CURRENT_RPC_CONTEXT.set(RpcAuthContext(InvocationContext.rpc(testActor()), buildSubject("TEST_USER", emptySet()))) CURRENT_RPC_CONTEXT.set(RpcAuthContext(InvocationContext.rpc(testActor()), buildSubject("TEST_USER", emptySet())))
val nonContractStateClass = uncheckedCast(Cash::class.java) as Class<ContractState> @Suppress("UNCHECKED_CAST")
val nonContractStateClass = Cash::class.java as Class<ContractState>
withPermissions(invokeRpc("vaultTrack"), invokeRpc("vaultQuery")) { withPermissions(invokeRpc("vaultTrack"), invokeRpc("vaultQuery")) {
assertThatThrownBy { rpc.vaultQuery(nonContractStateClass) }.hasMessageContaining(Cash::class.java.name) assertThatThrownBy { rpc.vaultQuery(nonContractStateClass) }.hasMessageContaining(Cash::class.java.name)
assertThatThrownBy { rpc.vaultTrack(nonContractStateClass) }.hasMessageContaining(Cash::class.java.name) assertThatThrownBy { rpc.vaultTrack(nonContractStateClass) }.hasMessageContaining(Cash::class.java.name)

View File

@ -598,7 +598,7 @@ class FlowClientIdTests {
@Test(timeout = 300_000) @Test(timeout = 300_000)
fun `flow that fails does not retain its checkpoint nor its exception in the database if not started with a client id`() { fun `flow that fails does not retain its checkpoint nor its exception in the database if not started with a client id`() {
assertFailsWith<IllegalStateException> { assertFailsWith<IllegalStateException> {
aliceNode.services.startFlow(ExceptionFlow { IllegalStateException("another exception") }).resultFuture.getOrThrow() aliceNode.services.startFlow(ExceptionFlow { IllegalStateException("another exception") }).resultFuture.getOrThrow<Nothing>()
} }
aliceNode.services.database.transaction { aliceNode.services.database.transaction {

View File

@ -775,7 +775,7 @@ class FlowFrameworkTests {
assertFailsWith<TimeoutException> { assertFailsWith<TimeoutException> {
val fiber = aliceNode.services.startFlow(ExceptionFlow { HospitalizeFlowException("Overnight observation") }) val fiber = aliceNode.services.startFlow(ExceptionFlow { HospitalizeFlowException("Overnight observation") })
flowId = fiber.id flowId = fiber.id
fiber.resultFuture.getOrThrow(10.seconds) fiber.resultFuture.getOrThrow<Nothing>(10.seconds)
} }
aliceNode.database.transaction { aliceNode.database.transaction {

View File

@ -204,7 +204,7 @@ data class RPCDriverDSL(
QueueConfiguration(RPCApi.RPC_CLIENT_BINDING_ADDITIONS).setAddress(NOTIFICATION_ADDRESS) QueueConfiguration(RPCApi.RPC_CLIENT_BINDING_ADDITIONS).setAddress(NOTIFICATION_ADDRESS)
.setFilterString(RPCApi.RPC_CLIENT_BINDING_ADDITION_FILTER_EXPRESSION).setDurable(false) .setFilterString(RPCApi.RPC_CLIENT_BINDING_ADDITION_FILTER_EXPRESSION).setDurable(false)
) )
addressesSettings = mapOf( addressSettings = mapOf(
"${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.#" to AddressSettings().apply { "${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.#" to AddressSettings().apply {
maxSizeBytes = maxBufferedBytesPerClient maxSizeBytes = maxBufferedBytesPerClient
addressFullMessagePolicy = AddressFullMessagePolicy.PAGE addressFullMessagePolicy = AddressFullMessagePolicy.PAGE

View File

@ -1,7 +1,6 @@
package net.corda.webserver.converters package net.corda.webserver.converters
import net.corda.core.identity.CordaX500Name import net.corda.core.identity.CordaX500Name
import net.corda.core.internal.uncheckedCast
import java.lang.reflect.Type import java.lang.reflect.Type
import javax.ws.rs.ext.ParamConverter import javax.ws.rs.ext.ParamConverter
import javax.ws.rs.ext.ParamConverterProvider import javax.ws.rs.ext.ParamConverterProvider
@ -14,9 +13,10 @@ object CordaX500NameConverter : ParamConverter<CordaX500Name> {
@Provider @Provider
object CordaConverterProvider : ParamConverterProvider { object CordaConverterProvider : ParamConverterProvider {
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getConverter(rawType: Class<T>, genericType: Type?, annotations: Array<out Annotation>?): ParamConverter<T>? { override fun <T : Any> getConverter(rawType: Class<T>, genericType: Type?, annotations: Array<out Annotation>?): ParamConverter<T>? {
if (rawType == CordaX500Name::class.java) { if (rawType == CordaX500Name::class.java) {
return uncheckedCast(CordaX500NameConverter) as ParamConverter<T>? return CordaX500NameConverter as ParamConverter<T>?
} }
return null return null
} }