Skip to content

Commit e2bcd04

Browse files
committed
ENT-11263: Remove TooGenericExceptionCaught detekt rule
1 parent 11d0054 commit e2bcd04

File tree

43 files changed

+59
-294
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+59
-294
lines changed

client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt

-2
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,6 @@ internal class RPCClientProxyHandler(
150150
}
151151
}
152152

153-
@Suppress("TooGenericExceptionCaught")
154153
private fun closeObservable(observable: UnicastSubject<Notification<*>>) {
155154
// Notify listeners of the observables that the connection is being terminated.
156155
try {
@@ -589,7 +588,6 @@ internal class RPCClientProxyHandler(
589588
}
590589
if (observableIds != null) {
591590
log.debug { "Reaping ${observableIds.size} observables" }
592-
@Suppress("TooGenericExceptionCaught")
593591
try {
594592
sendMessage(RPCApi.ClientToServer.ObservablesClosed(observableIds))
595593
} catch(ex: Exception) {

core-tests/src/test/kotlin/net/corda/coretests/flows/FlowExternalAsyncOperationTest.kt

-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,6 @@ class FlowExternalAsyncOperationTest : AbstractFlowExternalOperationTest() {
253253
@StartableByRPC
254254
class FlowWithExternalAsyncOperationThatDirectlyAccessesServiceHubFailsRetry(party: Party) : FlowWithExternalProcess(party) {
255255

256-
@Suppress("TooGenericExceptionCaught")
257256
@Suspendable
258257
override fun testCode(): Any {
259258
return await(ExternalAsyncOperation(serviceHub) { _, _ ->

core-tests/src/test/kotlin/net/corda/coretests/flows/FlowExternalOperationTest.kt

-1
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,6 @@ class FlowExternalOperationTest : AbstractFlowExternalOperationTest() {
293293
@StartableByRPC
294294
class FlowWithExternalOperationThatDirectlyAccessesServiceHubFailsRetry(party: Party) : FlowWithExternalProcess(party) {
295295

296-
@Suppress("TooGenericExceptionCaught")
297296
@Suspendable
298297
override fun testCode(): Any {
299298
try {

core/src/main/kotlin/net/corda/core/crypto/internal/PlatformSecureRandom.kt

+7-7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import java.io.InputStream
1414
import java.security.Provider
1515
import java.security.SecureRandom
1616
import java.security.SecureRandomSpi
17+
import kotlin.system.exitProcess
1718

1819
/**
1920
* This has been migrated into a separate class so that it
@@ -29,23 +30,22 @@ val platformSecureRandom: () -> SecureRandom = when {
2930
}
3031

3132
class PlatformSecureRandomService(provider: Provider)
32-
: Provider.Service(provider, "SecureRandom", algorithm, PlatformSecureRandomSpi::javaClass.name, null, null) {
33+
: Provider.Service(provider, "SecureRandom", ALGORITHM, PlatformSecureRandomSpi::javaClass.name, null, null) {
3334

3435
companion object {
35-
const val algorithm = "CordaPRNG"
36+
const val ALGORITHM = "CordaPRNG"
37+
3638
private val logger = loggerFor<PlatformSecureRandomService>()
3739
}
3840

3941
private val instance: SecureRandomSpi = if (SystemUtils.IS_OS_LINUX) tryAndUseLinuxSecureRandomSpi() else PlatformSecureRandomSpi()
4042

41-
@Suppress("TooGenericExceptionCaught", "TooGenericExceptionThrown")
4243
private fun tryAndUseLinuxSecureRandomSpi(): SecureRandomSpi = try {
4344
LinuxSecureRandomSpi()
4445
} catch (e: Exception) {
4546
logger.error("Unable to initialise LinuxSecureRandomSpi. The exception logged with this message might assist with diagnosis." +
4647
" The process will now exit.", e)
47-
System.exit(1)
48-
throw RuntimeException("Never reached, but calms the compiler.")
48+
exitProcess(1)
4949
}
5050

5151
override fun newInstance(constructorParameter: Any?) = instance
@@ -63,7 +63,7 @@ private class PlatformSecureRandomSpi : SecureRandomSpi() {
6363
override fun engineGenerateSeed(numBytes: Int): ByteArray = secureRandom.generateSeed(numBytes)
6464
}
6565

66-
@Suppress("TooGenericExceptionCaught", "TooGenericExceptionThrown")
66+
@Suppress("TooGenericExceptionThrown")
6767
private class LinuxSecureRandomSpi : SecureRandomSpi() {
6868
private fun openURandom(): InputStream {
6969
try {
@@ -91,5 +91,5 @@ private class LinuxSecureRandomSpi : SecureRandomSpi() {
9191

9292
// This is safe to share because of the underlying implementation of SecureRandomSpi
9393
private val sharedSecureRandom: SecureRandom by lazy(LazyThreadSafetyMode.PUBLICATION) {
94-
SecureRandom.getInstance(PlatformSecureRandomService.algorithm)
94+
SecureRandom.getInstance(PlatformSecureRandomService.ALGORITHM)
9595
}

core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt

-3
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ fun <ELEMENT> CordaFuture<out ELEMENT>.mapError(transform: (Throwable) -> Throwa
8484
* But if this future or the transform fails, the returned future's outcome is the same throwable.
8585
* In the case where this future fails, the transform is not invoked.
8686
*/
87-
@Suppress("TooGenericExceptionCaught")
8887
fun <V, W> CordaFuture<out V>.flatMap(transform: (V) -> CordaFuture<out W>): CordaFuture<W> = CordaFutureImpl<W>().also { result ->
8988
thenMatch(success@ {
9089
result.captureLater(try {
@@ -146,7 +145,6 @@ interface ValueOrException<in V> {
146145
fun captureLater(f: CordaFuture<out V>) = f.then { capture { f.getOrThrow() } }
147146

148147
/** Run the given block (in the foreground) and set this future to its outcome. */
149-
@Suppress("TooGenericExceptionCaught")
150148
fun capture(block: () -> V): Boolean {
151149
return set(try {
152150
block()
@@ -174,7 +172,6 @@ class CordaFutureImpl<V>(private val impl: CompletableFuture<V> = CompletableFut
174172
override fun setException(t: Throwable) = impl.completeExceptionally(t)
175173
override fun <W> then(callback: (CordaFuture<V>) -> W) = thenImpl(defaultLog, callback)
176174
/** For testing only. */
177-
@Suppress("TooGenericExceptionCaught")
178175
fun <W> thenImpl(log: Logger, callback: (CordaFuture<V>) -> W) {
179176
impl.whenComplete { _, _ ->
180177
try {

core/src/main/kotlin/net/corda/core/internal/telemetry/TelemetryServiceImpl.kt

+1-2
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,6 @@ class TelemetryServiceImpl : SingletonSerializeAsToken(), TelemetryService {
178178
}
179179
}
180180

181-
@Suppress("TooGenericExceptionCaught")
182181
inline fun <R> span(name: String, attributes: Map<String, String> = emptyMap(), flowLogic: FlowLogic<*>? = null, block: () -> R): R {
183182
val telemetryId = startSpan(name, attributes, flowLogic)
184183
try {
@@ -195,7 +194,7 @@ class TelemetryServiceImpl : SingletonSerializeAsToken(), TelemetryService {
195194
}
196195

197196
@CordaInternal
198-
@Suppress("LongParameterList", "TooGenericExceptionCaught")
197+
@Suppress("LongParameterList")
199198
inline fun <R> spanForFlow(name: String, attributes: Map<String, String>, flowLogic: FlowLogic<*>? = null, remoteSerializedTelemetry: SerializedTelemetry? = null, block: () -> R): R {
200199
val telemetryId = startSpanForFlow(name, attributes, flowLogic, remoteSerializedTelemetry)
201200
try {

core/src/main/kotlin/net/corda/core/internal/verification/Verifier.kt

-1
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,6 @@ private class Validator(private val ltx: LedgerTransaction, private val transact
440440
* Verify the given [LedgerTransaction]. This includes validating
441441
* its contents, as well as executing all of its smart contracts.
442442
*/
443-
@Suppress("TooGenericExceptionCaught")
444443
class TransactionVerifier(private val transactionClassLoader: ClassLoader) : Function<Supplier<LedgerTransaction>, Unit> {
445444
// Loads the contract class from the transactionClassLoader.
446445
private fun createContractClass(id: SecureHash, contractClassName: ContractClassName): Class<out Contract> {

core/src/main/kotlin/net/corda/core/observable/internal/ResilientSubscriber.kt

-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ class ResilientSubscriber<T>(actual: Subscriber<in T>) : SafeSubscriber<T>(actua
3333
* It only delegates to [SafeSubscriber.onError] if it wraps an [ActionSubscriber] which is
3434
* a leaf in an Subscribers' tree structure.
3535
*/
36-
@Suppress("TooGenericExceptionCaught")
3736
override fun onNext(t: T) {
3837
try {
3938
actual.onNext(t)
@@ -62,7 +61,6 @@ class ResilientSubscriber<T>(actual: Subscriber<in T>) : SafeSubscriber<T>(actua
6261
/**
6362
* Duplicate of [SafeSubscriber._onError]. However, it will not call [Subscriber.unsubscribe].
6463
*/
65-
@Suppress("TooGenericExceptionCaught")
6664
override fun _onError(e: Throwable) {
6765
@Suppress("DEPRECATION")
6866
RxJavaPlugins.getInstance().errorHandler.handleError(e)

core/src/main/kotlin/net/corda/core/serialization/internal/AttachmentsClassLoader.kt

+14-22
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import net.corda.core.contracts.TransactionVerificationException
88
import net.corda.core.contracts.TransactionVerificationException.OverlappingAttachmentsException
99
import net.corda.core.contracts.TransactionVerificationException.PackageOwnershipException
1010
import net.corda.core.crypto.SecureHash
11-
import net.corda.core.internal.JAVA_1_2_CLASS_FILE_FORMAT_MAJOR_VERSION
1211
import net.corda.core.internal.JAVA_17_CLASS_FILE_FORMAT_MAJOR_VERSION
12+
import net.corda.core.internal.JAVA_1_2_CLASS_FILE_FORMAT_MAJOR_VERSION
1313
import net.corda.core.internal.JarSignatureCollector
1414
import net.corda.core.internal.NamedCacheFactory
1515
import net.corda.core.internal.PlatformVersionSwitches
@@ -118,16 +118,11 @@ class AttachmentsClassLoader(attachments: List<Attachment>,
118118
// Reset the value to prevent Error due to a factory already defined
119119
factoryField.set(null, null)
120120
// Set our custom factory and wrap the current one into it
121-
URL.setURLStreamHandlerFactory(
122-
// Set the factory to a decorator
123-
object : URLStreamHandlerFactory {
124-
// route between our own and the pre-existing factory
125-
override fun createURLStreamHandler(protocol: String): URLStreamHandler? {
126-
return AttachmentURLStreamHandlerFactory.createURLStreamHandler(protocol)
127-
?: existingFactory.createURLStreamHandler(protocol)
128-
}
129-
}
130-
)
121+
URL.setURLStreamHandlerFactory { protocol ->
122+
// route between our own and the pre-existing factory
123+
AttachmentURLStreamHandlerFactory.createURLStreamHandler(protocol)
124+
?: existingFactory.createURLStreamHandler(protocol)
125+
}
131126
}
132127
}
133128
}
@@ -158,9 +153,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>,
158153
checkAttachments(attachments)
159154
}
160155

161-
private class AttachmentHashContext(
162-
val txId: SecureHash,
163-
val buffer: ByteArray = ByteArray(DEFAULT_BUFFER_SIZE))
156+
private class AttachmentHashContext(val buffer: ByteArray = ByteArray(DEFAULT_BUFFER_SIZE))
164157

165158
private fun hash(inputStream : InputStream, ctx : AttachmentHashContext) : SecureHash.SHA256 {
166159
val md = MessageDigest.getInstance(SecureHash.SHA2_256)
@@ -189,7 +182,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>,
189182
// This function attempts to strike a balance between security and usability when it comes to the no-overlap rule.
190183
// TODO - investigate potential exploits.
191184
private fun shouldCheckForNoOverlap(path: String, targetPlatformVersion: Int): Boolean {
192-
require(path.toLowerCase() == path)
185+
require(path.lowercase() == path)
193186
require(!path.contains('\\'))
194187

195188
return when {
@@ -234,7 +227,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>,
234227
// claim their parts of the Java package namespace via registration with the zone operator.
235228

236229
val classLoaderEntries = mutableMapOf<String, SecureHash>()
237-
val ctx = AttachmentHashContext(sampleTxId)
230+
val ctx = AttachmentHashContext()
238231
for (attachment in attachments) {
239232
// We may have been given an attachment loaded from the database in which case, important info like
240233
// signers is already calculated.
@@ -270,7 +263,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>,
270263
// filesystem tries to be case insensitive. This may break developers who attempt to use ProGuard.
271264
//
272265
// Also convert to Unix path separators as all resource/class lookups will expect this.
273-
val path = entry.name.toLowerCase(Locale.US).replace('\\', '/')
266+
val path = entry.name.lowercase(Locale.US).replace('\\', '/')
274267

275268
// Namespace ownership. We only check class files: resources are loaded relative to a JAR anyway.
276269
if (path.endsWith(".class")) {
@@ -285,7 +278,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>,
285278
for ((namespace, pubkey) in params.packageOwnership) {
286279
// Note that due to the toLowerCase() call above, we'll be comparing against a lowercased
287280
// version of the ownership claim.
288-
val ns = namespace.toLowerCase(Locale.US)
281+
val ns = namespace.lowercase(Locale.US)
289282
// We need an additional . to avoid matching com.foo.Widget against com.foobar.Zap
290283
if (pkgName == ns || pkgName.startsWith("$ns.")) {
291284
if (pubkey !in signers)
@@ -358,7 +351,7 @@ object AttachmentsClassLoaderBuilder {
358351
val attachmentIds = attachments.mapTo(LinkedHashSet(), Attachment::id)
359352

360353
val cache = attachmentsClassLoaderCache ?: fallBackCache
361-
val cachedSerializationContext = cache.computeIfAbsent(AttachmentsClassLoaderKey(attachmentIds, params), Function { key ->
354+
val cachedSerializationContext = cache.computeIfAbsent(AttachmentsClassLoaderKey(attachmentIds, params)) { key ->
362355
// Create classloader and load serializers, whitelisted classes
363356
val transactionClassLoader = AttachmentsClassLoader(attachments, key.params, txId, isAttachmentTrusted, parent)
364357
val serializers = try {
@@ -380,9 +373,9 @@ object AttachmentsClassLoaderBuilder {
380373
.withWhitelist(whitelistedClasses)
381374
.withCustomSerializers(serializers)
382375
.withoutCarpenter()
383-
})
376+
}
384377

385-
val serializationContext = cachedSerializationContext.withProperties(mapOf<Any, Any>(
378+
val serializationContext = cachedSerializationContext.withProperties(mapOf(
386379
// Duplicate the SerializationContext from the cache and give
387380
// it these extra properties, just for this transaction.
388381
// However, keep a strong reference to the cached SerializationContext so we can
@@ -489,7 +482,6 @@ class AttachmentsClassLoaderCacheImpl(cacheFactory: NamedCacheFactory) : Singlet
489482
private val toBeClosed = ConcurrentHashMap.newKeySet<ToBeClosed>()
490483
private val expiryQueue = ReferenceQueue<SerializationContext>()
491484

492-
@Suppress("TooGenericExceptionCaught")
493485
private fun purgeExpiryQueue() {
494486
// Close the AttachmentsClassLoader for every SerializationContext
495487
// that has already been garbage-collected.

core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt

-1
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,6 @@ private constructor(
290290
// upgraded attachments
291291
@CordaInternal
292292
@JvmSynthetic
293-
@Suppress("TooGenericExceptionCaught")
294293
internal fun loadUpgradedContract(className: ContractClassName, id: SecureHash, classLoader: ClassLoader): UpgradedContract<ContractState, *> {
295294
return try {
296295
loadClassOfType<UpgradedContract<ContractState, *>>(className, false, classLoader)

core/src/test/kotlin/net/corda/core/crypto/CryptoUtilsTest.kt

+3-3
Original file line numberDiff line numberDiff line change
@@ -943,17 +943,17 @@ class CryptoUtilsTest {
943943
Security.removeProvider(CordaSecurityProvider.PROVIDER_NAME)
944944
// Try after removing CordaSecurityProvider.
945945
val secureRandomNotRegisteredCordaProvider = SecureRandom()
946-
assertNotEquals(PlatformSecureRandomService.algorithm, secureRandomNotRegisteredCordaProvider.algorithm)
946+
assertNotEquals(PlatformSecureRandomService.ALGORITHM, secureRandomNotRegisteredCordaProvider.algorithm)
947947

948948
// Now register CordaSecurityProvider as last Provider.
949949
Security.addProvider(CordaSecurityProvider())
950950
val secureRandomRegisteredLastCordaProvider = SecureRandom()
951-
assertNotEquals(PlatformSecureRandomService.algorithm, secureRandomRegisteredLastCordaProvider.algorithm)
951+
assertNotEquals(PlatformSecureRandomService.ALGORITHM, secureRandomRegisteredLastCordaProvider.algorithm)
952952

953953
// Remove Corda Provider again and add it as the first Provider entry.
954954
Security.removeProvider(CordaSecurityProvider.PROVIDER_NAME)
955955
Security.insertProviderAt(CordaSecurityProvider(), 1) // This is base-1.
956956
val secureRandomRegisteredFirstCordaProvider = SecureRandom()
957-
assertEquals(PlatformSecureRandomService.algorithm, secureRandomRegisteredFirstCordaProvider.algorithm)
957+
assertEquals(PlatformSecureRandomService.ALGORITHM, secureRandomRegisteredFirstCordaProvider.algorithm)
958958
}
959959
}

0 commit comments

Comments
 (0)