Skip to content

Commit ee71bf5

Browse files
ENT-11351 - Compiler warnings pass 5 (corda#7666)
* Reduce compiler warnings * Address PR review comments * Acually make use of capitalize(),decapitalize()
1 parent 9b79479 commit ee71bf5

File tree

31 files changed

+129
-57
lines changed

31 files changed

+129
-57
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Implement the new post-1.2 APIs which are used by core and serialization
2+
@file:Suppress("unused")
3+
package kotlin
4+
5+
inline val Char.code: Int get() = this.toInt()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Implement the new post-1.2 APIs which are used by core and serialization
2+
@file:Suppress("NOTHING_TO_INLINE", "unused")
3+
4+
package kotlin.text
5+
6+
import java.util.Locale
7+
8+
inline fun Char.isLowerCase(): Boolean = Character.isLowerCase(this)
9+
public fun Char.lowercase(locale: Locale): String = toString().lowercase(locale)
10+
inline fun Char.lowercaseChar(): Char = Character.toLowerCase(this)
11+
inline fun Char.uppercase(): String = toString().uppercase()
12+
fun Char.uppercase(locale: Locale): String = toString().uppercase(locale)
13+
inline fun Char.titlecaseChar(): Char = Character.toTitleCase(this)
14+
fun Char.titlecase(locale: Locale): String {
15+
val localizedUppercase = uppercase(locale)
16+
if (localizedUppercase.length > 1) {
17+
return if (this == '\u0149') localizedUppercase else localizedUppercase[0] + localizedUppercase.substring(1).lowercase()
18+
}
19+
if (localizedUppercase != uppercase()) {
20+
return localizedUppercase
21+
}
22+
return titlecaseChar().toString()
23+
}
24+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Implement the new post-1.2 APIs which are used by core and serialization
2+
@file:Suppress("NOTHING_TO_INLINE", "unused")
3+
package kotlin.text
4+
5+
// StringBuilder
6+
fun StringBuilder.append(vararg value: String?): StringBuilder {
7+
for (item in value)
8+
append(item)
9+
return this
10+
}
11+
inline fun StringBuilder.appendLine(): StringBuilder = append('\n')
12+
inline fun StringBuilder.appendLine(value: String?): StringBuilder = append(value).appendLine()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Implement the new post-1.2 APIs which are used by core and serialization
2+
@file:Suppress("unused")
3+
4+
package kotlin.text
5+
6+
inline fun String.replaceFirstChar(transform: (Char) -> CharSequence): String {
7+
return if (isNotEmpty()) transform(this[0]).toString() + substring(1) else this
8+
}

core-1.2/src/main/kotlin/kotlin/text/KotlinText1.2.kt core-1.2/src/main/kotlin/kotlin/text/StringsJVM1.2.kt

+3-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ package kotlin.text
55

66
import java.util.Locale
77

8+
// String extensions
89
inline fun String.lowercase(): String = (this as java.lang.String).toLowerCase(Locale.ROOT)
9-
1010
inline fun String.lowercase(locale: Locale): String = (this as java.lang.String).toLowerCase(locale)
11+
inline fun String.uppercase(): String = (this as java.lang.String).toUpperCase(Locale.ROOT)
12+
inline fun String.uppercase(locale: Locale): String = (this as java.lang.String).toUpperCase(locale)

core/src/main/kotlin/net/corda/core/crypto/SecureHash.kt

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import net.corda.core.utilities.OpaqueBytes
1111
import net.corda.core.utilities.parseAsHex
1212
import net.corda.core.utilities.toHexString
1313
import java.security.MessageDigest
14+
import java.util.Locale
1415
import java.util.concurrent.ConcurrentHashMap
1516
import java.util.concurrent.ConcurrentMap
1617
import java.util.function.Supplier
@@ -182,7 +183,7 @@ sealed class SecureHash(bytes: ByteArray) : OpaqueBytes(bytes) {
182183
*/
183184
@JvmStatic
184185
fun parse(str: String?): SHA256 {
185-
return str?.toUpperCase()?.parseAsHex()?.let {
186+
return str?.uppercase(Locale.getDefault())?.parseAsHex()?.let {
186187
when (it.size) {
187188
32 -> interner.intern(SHA256(it))
188189
else -> throw IllegalArgumentException("Provided string is ${it.size} bytes not 32 bytes in hex: $str")

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

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import net.corda.core.internal.loadClassOfType
55
import java.security.MessageDigest
66
import java.security.NoSuchAlgorithmException
77
import java.util.Collections
8+
import java.util.Locale
89
import java.util.concurrent.ConcurrentHashMap
910

1011
sealed class DigestAlgorithmFactory {
@@ -44,7 +45,7 @@ sealed class DigestAlgorithmFactory {
4445
private val factories = ConcurrentHashMap<String, DigestAlgorithmFactory>()
4546

4647
private fun check(algorithm: String) {
47-
require(algorithm.toUpperCase() == algorithm) { "Hash algorithm name $this must be in the upper case" }
48+
require(algorithm.uppercase(Locale.getDefault()) == algorithm) { "Hash algorithm name $this must be in the upper case" }
4849
require(algorithm !in BANNED) { "$algorithm is forbidden!" }
4950
}
5051

core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ abstract class SignTransactionFlow @JvmOverloads constructor(val otherSideSessio
292292
try {
293293
checkTransaction(stx)
294294
} catch (e: Exception) {
295-
if (e is IllegalStateException || e is IllegalArgumentException || e is AssertionError)
295+
if (e is IllegalStateException || e is IllegalArgumentException)
296296
throw FlowException(e)
297297
else
298298
throw e

core/src/main/kotlin/net/corda/core/identity/PartyAndCertificate.kt

+3-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class PartyAndCertificate(val certPath: CertPath) {
2626
require(certs.size >= 2) { "Certificate path must at least include subject and issuing certificates" }
2727
certificate = certs[0] as X509Certificate
2828
val role = CertRole.extract(certificate)
29-
require(role?.isIdentity ?: false) { "Party certificate ${certificate.subjectDN} does not have a well known or confidential identity role. Found: $role" }
29+
require(role?.isIdentity ?: false) { "Party certificate ${certificate.getSubjectX500Principal()} does not have a well known or confidential identity role. Found: $role" }
3030
}
3131

3232
@Transient
@@ -46,6 +46,7 @@ class PartyAndCertificate(val certPath: CertPath) {
4646
fun verify(trustAnchor: TrustAnchor): PKIXCertPathValidatorResult = verify(setOf(trustAnchor))
4747

4848
/** Verify the certificate path is valid against one of the specified trust anchors. */
49+
@Suppress("UNCHECKED_CAST")
4950
fun verify(trustAnchors: Set<TrustAnchor>): PKIXCertPathValidatorResult {
5051
val result = certPath.validate(trustAnchors)
5152
// Apply Corda-specific validity rules to the chain. This only applies to chains with any roles present, so
@@ -60,7 +61,7 @@ class PartyAndCertificate(val certPath: CertPath) {
6061
throw CertPathValidatorException("Child certificate whose issuer includes a Corda role, must also specify Corda role")
6162
}
6263
if (!role.isValidParent(parentRole)) {
63-
val certificateString = certificate.subjectDN.toString()
64+
val certificateString = certificate.getSubjectX500Principal().toString()
6465
throw CertPathValidatorException("The issuing certificate for $certificateString has role $parentRole, expected one of ${role.validParents}")
6566
}
6667
}

core/src/main/kotlin/net/corda/core/internal/AbstractAttachment.kt

+3-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import java.io.IOException
1111
import java.io.InputStream
1212
import java.io.OutputStream
1313
import java.security.PublicKey
14+
import java.util.Locale
1415
import java.util.jar.JarInputStream
1516

1617
const val DEPLOYED_CORDAPP_UPLOADER = "app"
@@ -60,6 +61,7 @@ abstract class AbstractAttachment(dataLoader: () -> ByteArray, val uploader: Str
6061
openAsJAR().use(JarSignatureCollector::collectSigners)
6162
}
6263

64+
@Suppress("OVERRIDE_DEPRECATION")
6365
override val signers: List<Party> by lazy {
6466
openAsJAR().use(JarSignatureCollector::collectSigningParties)
6567
}
@@ -71,7 +73,7 @@ abstract class AbstractAttachment(dataLoader: () -> ByteArray, val uploader: Str
7173

7274
@Throws(IOException::class)
7375
fun JarInputStream.extractFile(path: String, outputTo: OutputStream) {
74-
fun String.norm() = toLowerCase().split('\\', '/') // XXX: Should this really be locale-sensitive?
76+
fun String.norm() = lowercase(Locale.getDefault()).split('\\', '/') // XXX: Should this really be locale-sensitive?
7577
val p = path.norm()
7678
while (true) {
7779
val e = nextJarEntry ?: break

core/src/main/kotlin/net/corda/core/internal/InternalUtils.kt

+13-3
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import java.security.cert.X509Certificate
5252
import java.time.Duration
5353
import java.time.temporal.Temporal
5454
import java.util.Collections
55+
import java.util.Locale
5556
import java.util.PrimitiveIterator
5657
import java.util.Spliterator
5758
import java.util.Spliterator.DISTINCT
@@ -341,9 +342,7 @@ val <T : Any> Class<T>.kotlinObjectInstance: T? get() {
341342
field?.let {
342343
if (it.type == this && it.isPublic && it.isStatic && it.isFinal) {
343344
it.isAccessible = true
344-
345-
// TODO JDK17: Why does uncheckedCast(...) cause class cast exception?
346-
// uncheckedCast(it.get(null))
345+
@Suppress("UNCHECKED_CAST")
347346
it.get(null) as T
348347
} else {
349348
null
@@ -624,3 +623,14 @@ val Logger.level: Level
624623

625624
const val JAVA_1_2_CLASS_FILE_FORMAT_MAJOR_VERSION = 46
626625
const val JAVA_17_CLASS_FILE_FORMAT_MAJOR_VERSION = 61
626+
627+
/**
628+
* String extension functions - to keep calling code readable following upgrade to Kotlin 1.9
629+
*/
630+
fun String.capitalize() : String {
631+
return this.replaceFirstChar { it.titlecase(Locale.getDefault()) }
632+
}
633+
fun String.decapitalize() : String {
634+
return this.replaceFirstChar { it.lowercase(Locale.getDefault()) }
635+
}
636+

core/src/main/kotlin/net/corda/core/node/services/VaultService.kt

+11-11
Original file line numberDiff line numberDiff line change
@@ -123,24 +123,24 @@ class Vault<out T : ContractState>(val states: Iterable<StateAndRef<T>>) {
123123

124124
override fun toString(): String {
125125
val sb = StringBuilder()
126-
sb.appendln("${consumed.size} consumed, ${produced.size} produced")
127-
sb.appendln("")
128-
sb.appendln("Consumed:")
126+
sb.appendLine("${consumed.size} consumed, ${produced.size} produced")
127+
sb.appendLine("")
128+
sb.appendLine("Consumed:")
129129
consumed.forEach {
130-
sb.appendln("${it.ref}: ${it.state}")
130+
sb.appendLine("${it.ref}: ${it.state}")
131131
}
132-
sb.appendln("")
133-
sb.appendln("Produced:")
132+
sb.appendLine("")
133+
sb.appendLine("Produced:")
134134
produced.forEach {
135-
sb.appendln("${it.ref}: ${it.state}")
135+
sb.appendLine("${it.ref}: ${it.state}")
136136
}
137-
sb.appendln("References:")
137+
sb.appendLine("References:")
138138
references.forEach {
139-
sb.appendln("${it.ref}: ${it.state}")
139+
sb.appendLine("${it.ref}: ${it.state}")
140140
}
141-
sb.appendln("Consuming TxIds:")
141+
sb.appendLine("Consuming TxIds:")
142142
consumingTxIds.forEach {
143-
sb.appendln("${it.key}: ${it.value}")
143+
sb.appendLine("${it.key}: ${it.value}")
144144
}
145145
return sb.toString()
146146
}

core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ object CommonSchemaV1 : MappedSchema(schemaFamily = CommonSchema.javaClass, vers
2626

2727
/** X500Name of participant parties **/
2828
@Transient
29-
open var participants: MutableSet<AbstractParty>? = null,
29+
var participants: MutableSet<AbstractParty>? = null,
3030

3131
/**
3232
* Represents a [LinearState] [UniqueIdentifier]
@@ -51,7 +51,7 @@ object CommonSchemaV1 : MappedSchema(schemaFamily = CommonSchema.javaClass, vers
5151

5252
/** X500Name of participant parties **/
5353
@Transient
54-
open var participants: MutableSet<AbstractParty?>? = null,
54+
var participants: MutableSet<AbstractParty?>? = null,
5555

5656
/** [OwnableState] attributes */
5757

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

+7-7
Original file line numberDiff line numberDiff line change
@@ -362,29 +362,29 @@ class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: Pr
362362

363363
override fun toString(): String {
364364
val buf = StringBuilder()
365-
buf.appendln("Transaction:")
365+
buf.appendLine("Transaction:")
366366
for (reference in references) {
367367
val emoji = Emoji.rightArrow
368-
buf.appendln("${emoji}REFS: $reference")
368+
buf.appendLine("${emoji}REFS: $reference")
369369
}
370370
for (input in inputs) {
371371
val emoji = Emoji.rightArrow
372-
buf.appendln("${emoji}INPUT: $input")
372+
buf.appendLine("${emoji}INPUT: $input")
373373
}
374374
for ((data) in outputs) {
375375
val emoji = Emoji.leftArrow
376-
buf.appendln("${emoji}OUTPUT: $data")
376+
buf.appendLine("${emoji}OUTPUT: $data")
377377
}
378378
for (command in commands) {
379379
val emoji = Emoji.diamond
380-
buf.appendln("${emoji}COMMAND: $command")
380+
buf.appendLine("${emoji}COMMAND: $command")
381381
}
382382
for (attachment in attachments) {
383383
val emoji = Emoji.paperclip
384-
buf.appendln("${emoji}ATTACHMENT: $attachment")
384+
buf.appendLine("${emoji}ATTACHMENT: $attachment")
385385
}
386386
if (networkParametersHash != null) {
387-
buf.appendln("PARAMETERS HASH: $networkParametersHash")
387+
buf.appendLine("PARAMETERS HASH: $networkParametersHash")
388388
}
389389
return buf.toString()
390390
}

core/src/main/kotlin/net/corda/core/utilities/Try.kt

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ sealed class Try<out A> {
6060
* Maps the given function to the values from this [Success] and [other], or returns `this` if this is a [Failure]
6161
* or [other] if [other] is a [Failure].
6262
*/
63+
@Suppress("UNCHECKED_CAST")
6364
inline fun <B, C> combine(other: Try<B>, function: (A, B) -> C): Try<C> = when (this) {
6465
is Success -> when (other) {
6566
is Success -> Success(function(value, other.value))

core/src/test/kotlin/net/corda/core/internal/InternalUtilsTest.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,10 @@ open class InternalUtilsTest {
8989

9090
@Test(timeout=300_000)
9191
fun `Stream toTypedArray works`() {
92-
val a: Array<String> = Stream.of("one", "two").toTypedArray() as Array<String>
92+
val a: Array<String> = uncheckedCast(Stream.of("one", "two").toTypedArray())
9393
assertEquals(Array<String>::class.java, a.javaClass)
9494
assertArrayEquals(arrayOf("one", "two"), a)
95-
val b: Array<String?> = Stream.of("one", "two", null).toTypedArray() as Array<String?>
95+
val b: Array<String?> = uncheckedCast(Stream.of("one", "two", null).toTypedArray())
9696
assertEquals(Array<String?>::class.java, b.javaClass)
9797
assertArrayEquals(arrayOf("one", "two", null), b)
9898
}

core/src/test/kotlin/net/corda/core/internal/concurrent/CordaFutureImplTest.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class CordaFutureTest {
2121
assertEquals(100, e.fork { 100 }.getOrThrow())
2222
val x = Exception()
2323
val f = e.fork { throw x }
24-
Assertions.assertThatThrownBy { f.getOrThrow() }.isSameAs(x)
24+
Assertions.assertThatThrownBy { f.getOrThrow<Nothing>() }.isSameAs(x)
2525
} finally {
2626
e.shutdown()
2727
}
@@ -54,7 +54,7 @@ class CordaFutureTest {
5454
val x = Exception()
5555
val g = f.map { throw x }
5656
f.set(100)
57-
Assertions.assertThatThrownBy { g.getOrThrow() }.isSameAs(x)
57+
Assertions.assertThatThrownBy { g.getOrThrow<Nothing>() }.isSameAs(x)
5858
}
5959
run {
6060
val block = mock<(Any?) -> Any?>()

serialization/src/main/kotlin/net/corda/serialization/internal/AllButBlacklisted.kt

-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ object AllButBlacklisted : ClassWhitelist {
4848
Runtime::class.java.name,
4949
ZipFile::class.java.name,
5050
Provider::class.java.name,
51-
SecurityManager::class.java.name,
5251
Random::class.java.name,
5352

5453
// Known blacklisted interfaces.

serialization/src/main/kotlin/net/corda/serialization/internal/amqp/ComposableTypePropertySerializer.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ object AMQPCharPropertyReadStrategy : PropertyReadStrategy {
255255
override fun readProperty(obj: Any?, schemas: SerializationSchemas,
256256
input: DeserializationInput, context: SerializationContext
257257
): Any? {
258-
return if (obj == null) null else (obj as Short).toChar()
258+
return if (obj == null) null else (obj as Short).toInt().toChar()
259259
}
260260
}
261261

@@ -266,6 +266,6 @@ class AMQPCharPropertyWriteStategy(private val reader: PropertyReader) : Propert
266266
context: SerializationContext, debugIndent: Int
267267
) {
268268
val input = reader.read(obj)
269-
if (input != null) data.putShort((input as Char).toShort()) else data.putNull()
269+
if (input != null) data.putShort((input as Char).code.toShort()) else data.putNull()
270270
}
271271
}

serialization/src/main/kotlin/net/corda/serialization/internal/amqp/PropertyDescriptor.kt

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package net.corda.serialization.internal.amqp
22

33
import com.google.common.reflect.TypeToken
4+
import net.corda.core.internal.decapitalize
45
import net.corda.core.internal.isPublic
56
import net.corda.core.serialization.SerializableCalculatedProperty
67
import net.corda.serialization.internal.amqp.MethodClassifier.*
@@ -20,9 +21,9 @@ import java.util.*
2021
*/
2122
data class PropertyDescriptor(val field: Field?, val setter: Method?, val getter: Method?) {
2223
override fun toString() = StringBuilder("").apply {
23-
appendln("Property - ${field?.name ?: "null field"}\n")
24-
appendln(" getter - ${getter?.name ?: "no getter"}")
25-
appendln(" setter - ${setter?.name ?: "no setter"}")
24+
appendLine("Property - ${field?.name ?: "null field"}\n")
25+
appendLine(" getter - ${getter?.name ?: "no getter"}")
26+
appendLine(" setter - ${setter?.name ?: "no setter"}")
2627
}.toString()
2728

2829
/**
@@ -159,7 +160,7 @@ private fun getPropertyNamedMethod(method: Method): PropertyNamedMethod? {
159160
return propertyMethodRegex.find(method.name)?.let { result ->
160161
PropertyNamedMethod(
161162
result.groups[2]!!.value,
162-
MethodClassifier.valueOf(result.groups[1]!!.value.toUpperCase()),
163+
MethodClassifier.valueOf(result.groups[1]!!.value.uppercase(Locale.getDefault())),
163164
method)
164165
}
165166
}

0 commit comments

Comments
 (0)