diff --git a/client/jackson/src/main/kotlin/net/corda/jackson/StringToMethodCallParser.kt b/client/jackson/src/main/kotlin/net/corda/jackson/StringToMethodCallParser.kt index edc4767343..7ef42412e1 100644 --- a/client/jackson/src/main/kotlin/net/corda/jackson/StringToMethodCallParser.kt +++ b/client/jackson/src/main/kotlin/net/corda/jackson/StringToMethodCallParser.kt @@ -5,12 +5,10 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.google.common.collect.HashMultimap import com.google.common.collect.Multimap -import com.google.common.collect.MultimapBuilder import net.corda.jackson.StringToMethodCallParser.ParsedMethodCall import org.slf4j.LoggerFactory import java.lang.reflect.Constructor import java.lang.reflect.Method -import java.util.* import java.util.concurrent.Callable import javax.annotation.concurrent.ThreadSafe import kotlin.reflect.KClass @@ -75,14 +73,14 @@ import kotlin.reflect.jvm.kotlinFunction @ThreadSafe open class StringToMethodCallParser @JvmOverloads constructor( targetType: Class, - private val om: ObjectMapper = JacksonSupport.createNonRpcMapper(YAMLFactory())) -{ + private val om: ObjectMapper = JacksonSupport.createNonRpcMapper(YAMLFactory())) { /** Same as the regular constructor but takes a Kotlin reflection [KClass] instead of a Java [Class]. */ constructor(targetType: KClass) : this(targetType.java) companion object { @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") private val ignoredNames = Object::class.java.methods.map { it.name } + private fun methodsFromType(clazz: Class<*>): Multimap { val result = HashMultimap.create() for ((key, value) in clazz.methods.filterNot { it.isSynthetic && it.name !in ignoredNames }.map { it.name to it }) { @@ -90,6 +88,7 @@ open class StringToMethodCallParser @JvmOverloads constructor( } return result } + private val log = LoggerFactory.getLogger(StringToMethodCallParser::class.java)!! } @@ -126,7 +125,7 @@ open class StringToMethodCallParser @JvmOverloads constructor( return method.parameters.mapIndexed { index, param -> when { param.isNamePresent -> param.name - // index + 1 because the first Kotlin reflection param is 'this', but that doesn't match Java reflection. + // index + 1 because the first Kotlin reflection param is 'this', but that doesn't match Java reflection. kf != null -> kf.parameters[index + 1].name ?: throw UnparseableCallException.ReflectionDataMissing(method.name, index) else -> throw UnparseableCallException.ReflectionDataMissing(method.name, index) } @@ -193,7 +192,7 @@ open class StringToMethodCallParser @JvmOverloads constructor( val parameterString = "{ $args }" val tree: JsonNode = om.readTree(parameterString) ?: throw UnparseableCallException(args) if (tree.size() > parameters.size) throw UnparseableCallException.TooManyParameters(methodNameHint, args) - val inOrderParams: List = parameters.mapIndexed { index, param -> + val inOrderParams: List = parameters.mapIndexed { _, param -> val (argName, argType) = param val entry = tree[argName] ?: throw UnparseableCallException.MissingParameter(methodNameHint, argName, args) om.readValue(entry.traverse(om), argType) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt index 77447feb58..61f60e53aa 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt @@ -31,7 +31,7 @@ class ChosenList( } init { - chosenListObservable.addListener { observable: Observable -> rechoose() } + chosenListObservable.addListener { _: Observable -> rechoose() } currentList.addListener(listener) beginChange() nextAdd(0, currentList.size) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt index 4e2153c905..3b349ce67d 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt @@ -38,7 +38,7 @@ class FlattenedList(val sourceList: ObservableList } private fun createListener(wrapped: WrappedObservableValue): ChangeListener { - val listener = ChangeListener { _observableValue, oldValue, newValue -> + val listener = ChangeListener { _, oldValue, _ -> val currentIndex = indexMap[wrapped]!!.first beginChange() nextReplace(currentIndex, currentIndex + 1, listOf(oldValue)) @@ -55,7 +55,7 @@ class FlattenedList(val sourceList: ObservableList val from = c.from val to = c.to val permutation = IntArray(to, { c.getPermutation(it) }) - indexMap.replaceAll { _observableValue, pair -> Pair(permutation[pair.first], pair.second) } + indexMap.replaceAll { _, pair -> Pair(permutation[pair.first], pair.second) } nextPermutation(from, to, permutation) } else if (c.wasUpdated()) { throw UnsupportedOperationException("FlattenedList doesn't support Update changes") diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt index aa5187aa3e..aefd494aff 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt @@ -67,7 +67,7 @@ fun Observable.recordInSequence(): ObservableList { * @param toKey Function retrieving the key to associate with. * @param merge The function to be called if there is an existing element at the key. */ -fun Observable.recordAsAssociation(toKey: (A) -> K, merge: (K, oldValue: A, newValue: A) -> A = { _key, _oldValue, newValue -> newValue }): ObservableMap { +fun Observable.recordAsAssociation(toKey: (A) -> K, merge: (K, oldValue: A, newValue: A) -> A = { _, _, newValue -> newValue }): ObservableMap { return fold(FXCollections.observableHashMap()) { map, item -> val key = toKey(item) map[key] = map[key]?.let { merge(key, it, item) } ?: item diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt index b39cc8a8d0..6b7b3f3e71 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt @@ -158,7 +158,7 @@ fun ObservableList.associateBy(toKey: (A) -> K, assemble: (K, A * val nameToPerson: ObservableMap = people.associateBy(Person::name) */ fun ObservableList.associateBy(toKey: (A) -> K): ObservableMap { - return associateBy(toKey) { key, value -> value } + return associateBy(toKey) { _, value -> value } } /** @@ -176,7 +176,7 @@ fun ObservableList.associateByAggregation(toKey: (A * val heightToPeople: ObservableMap> = people.associateByAggregation(Person::height) */ fun ObservableList.associateByAggregation(toKey: (A) -> K): ObservableMap> { - return associateByAggregation(toKey) { key, value -> value } + return associateByAggregation(toKey) { _, value -> value } } /** @@ -260,7 +260,7 @@ fun ObservableList.leftOuterJoin( val leftTableMap = associateByAggregation(leftToJoinKey) val rightTableMap = rightTable.associateByAggregation(rightToJoinKey) val joinedMap: ObservableMap, ObservableList>> = - LeftOuterJoinedMap(leftTableMap, rightTableMap) { _key, left, rightValue -> + LeftOuterJoinedMap(leftTableMap, rightTableMap) { _, left, rightValue -> Pair(left, ChosenList(rightValue.map { it ?: FXCollections.emptyObservableList() })) } return joinedMap @@ -285,7 +285,7 @@ fun ObservableList.last(): ObservableValue { } fun ObservableList.unique(): ObservableList { - return AggregatedList(this, { it }, { key, _list -> key }) + return AggregatedList(this, { it }, { key, _ -> key }) } fun ObservableValue<*>.isNotNull(): BooleanBinding { diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AssociatedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AssociatedListTest.kt index 052b422c01..139d8a7b20 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AssociatedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AssociatedListTest.kt @@ -16,7 +16,7 @@ class AssociatedListTest { @Before fun setup() { sourceList = FXCollections.observableArrayList(0) - associatedList = AssociatedList(sourceList, { it % 3 }) { mod3, number -> number } + associatedList = AssociatedList(sourceList, { it % 3 }) { _, number -> number } replayedMap = ReplayedMap(associatedList) } diff --git a/client/mock/src/main/kotlin/net/corda/client/mock/EventGenerator.kt b/client/mock/src/main/kotlin/net/corda/client/mock/EventGenerator.kt index bb3af8db6d..a8ac13ae89 100644 --- a/client/mock/src/main/kotlin/net/corda/client/mock/EventGenerator.kt +++ b/client/mock/src/main/kotlin/net/corda/client/mock/EventGenerator.kt @@ -81,7 +81,7 @@ class EventGenerator( } val exitCashGenerator = - amountToIssueGenerator.combine(partyGenerator, issueRefGenerator) { amount, to, issueRef -> + amountToIssueGenerator.combine(partyGenerator, issueRefGenerator) { amount, _, issueRef -> CashFlowCommand.ExitCash( amount, issueRef diff --git a/core/src/main/kotlin/net/corda/core/Utils.kt b/core/src/main/kotlin/net/corda/core/Utils.kt index f3c1a01899..2d2b19befc 100644 --- a/core/src/main/kotlin/net/corda/core/Utils.kt +++ b/core/src/main/kotlin/net/corda/core/Utils.kt @@ -75,7 +75,7 @@ fun future(block: () -> T): ListenableFuture = CompletableToListenable(Co private class CompletableToListenable(private val base: CompletableFuture) : Future by base, ListenableFuture { override fun addListener(listener: Runnable, executor: Executor) { - base.whenCompleteAsync(BiConsumer { result, exception -> listener.run() }, executor) + base.whenCompleteAsync(BiConsumer { _, _ -> listener.run() }, executor) } } @@ -104,6 +104,7 @@ infix fun ListenableFuture.success(body: (T) -> Unit): ListenableFuture ListenableFuture.failure(body: (Throwable) -> Unit): ListenableFuture = apply { failure(RunOnCallerThread, body) } @Suppress("UNCHECKED_CAST") // We need the awkward cast because otherwise F cannot be nullable, even though it's safe. infix fun ListenableFuture.map(mapper: (F) -> T): ListenableFuture = Futures.transform(this, Function { (mapper as (F?) -> T)(it) }) + infix fun ListenableFuture.flatMap(mapper: (F) -> ListenableFuture): ListenableFuture = Futures.transformAsync(this) { mapper(it!!) } /** Executes the given block and sets the future to either the result, or any exception that was thrown. */ inline fun SettableFuture.catch(block: () -> T) { diff --git a/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt b/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt index 02e0199411..2d42d958b7 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/Crypto.kt @@ -107,11 +107,11 @@ object Crypto { * Do not forget to add the DEFAULT_SIGNATURE_SCHEME as well. */ private val supportedSignatureSchemes = mapOf( - RSA_SHA256.schemeCodeName to RSA_SHA256, - ECDSA_SECP256K1_SHA256.schemeCodeName to ECDSA_SECP256K1_SHA256, - ECDSA_SECP256R1_SHA256.schemeCodeName to ECDSA_SECP256R1_SHA256, - EDDSA_ED25519_SHA512.schemeCodeName to EDDSA_ED25519_SHA512, - SPHINCS256_SHA256.schemeCodeName to SPHINCS256_SHA256 + RSA_SHA256.schemeCodeName to RSA_SHA256, + ECDSA_SECP256K1_SHA256.schemeCodeName to ECDSA_SECP256K1_SHA256, + ECDSA_SECP256R1_SHA256.schemeCodeName to ECDSA_SECP256R1_SHA256, + EDDSA_ED25519_SHA512.schemeCodeName to EDDSA_ED25519_SHA512, + SPHINCS256_SHA256.schemeCodeName to SPHINCS256_SHA256 ) /** @@ -181,9 +181,9 @@ object Crypto { */ @Throws(IllegalArgumentException::class) fun decodePrivateKey(encodedKey: ByteArray): PrivateKey { - for (sig in supportedSignatureSchemes.values) { + for ((_, _, _, _, keyFactory) in supportedSignatureSchemes.values) { try { - return sig.keyFactory.generatePrivate(PKCS8EncodedKeySpec(encodedKey)) + return keyFactory.generatePrivate(PKCS8EncodedKeySpec(encodedKey)) } catch (ikse: InvalidKeySpecException) { // ignore it - only used to bypass the scheme that causes an exception. } @@ -218,9 +218,9 @@ object Crypto { */ @Throws(IllegalArgumentException::class) fun decodePublicKey(encodedKey: ByteArray): PublicKey { - for (sig in supportedSignatureSchemes.values) { + for ((_, _, _, _, keyFactory) in supportedSignatureSchemes.values) { try { - return sig.keyFactory.generatePublic(X509EncodedKeySpec(encodedKey)) + return keyFactory.generatePublic(X509EncodedKeySpec(encodedKey)) } catch (ikse: InvalidKeySpecException) { // ignore it - only used to bypass the scheme that causes an exception. } diff --git a/core/src/main/kotlin/net/corda/core/serialization/DefaultKryoCustomizer.kt b/core/src/main/kotlin/net/corda/core/serialization/DefaultKryoCustomizer.kt index 42d9f4719c..a165c5acc2 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/DefaultKryoCustomizer.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/DefaultKryoCustomizer.kt @@ -66,7 +66,7 @@ object DefaultKryoCustomizer { register(CompositeKey.Leaf::class.java, CompositeKeyLeafSerializer) // Exceptions. We don't bother sending the stack traces as the client will fill in its own anyway. - register(Array::class, read = { kryo, input -> emptyArray() }, write = { kryo, output, obj -> }) + register(Array::class, read = { _, _ -> emptyArray() }, write = { _, _, _ -> }) // This ensures a NonEmptySetSerializer is constructed with an initial value. register(NonEmptySet::class.java, NonEmptySetSerializer) diff --git a/core/src/main/kotlin/net/corda/flows/ResolveTransactionsFlow.kt b/core/src/main/kotlin/net/corda/flows/ResolveTransactionsFlow.kt index 81cdbb1902..209cdec5b4 100644 --- a/core/src/main/kotlin/net/corda/flows/ResolveTransactionsFlow.kt +++ b/core/src/main/kotlin/net/corda/flows/ResolveTransactionsFlow.kt @@ -6,7 +6,6 @@ import net.corda.core.crypto.Party import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.getOrThrow -import net.corda.core.node.recordTransactions import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.SignedTransaction @@ -43,9 +42,9 @@ class ResolveTransactionsFlow(private val txHashes: Set, // Construct txhash -> dependent-txs map val forwardGraph = HashMap>() transactions.forEach { stx -> - stx.tx.inputs.forEach { input -> + stx.tx.inputs.forEach { (txhash) -> // Note that we use a LinkedHashSet here to make the traversal deterministic (as long as the input list is) - forwardGraph.getOrPut(input.txhash) { LinkedHashSet() }.add(stx) + forwardGraph.getOrPut(txhash) { LinkedHashSet() }.add(stx) } } diff --git a/core/src/test/kotlin/net/corda/core/contracts/DummyContractV2Tests.kt b/core/src/test/kotlin/net/corda/core/contracts/DummyContractV2Tests.kt index 7a99210def..1e5034b681 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/DummyContractV2Tests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/DummyContractV2Tests.kt @@ -17,7 +17,7 @@ class DummyContractV2Tests { val v1State = TransactionState(DummyContract.SingleOwnerState(0, ALICE_PUBKEY), DUMMY_NOTARY) val v1Ref = StateRef(SecureHash.randomSHA256(), 0) val v1StateAndRef = StateAndRef(v1State, v1Ref) - val (tx, signers) = DummyContractV2().generateUpgradeFromV1(v1StateAndRef) + val (tx, _) = DummyContractV2().generateUpgradeFromV1(v1StateAndRef) assertEquals(v1Ref, tx.inputs.single()) diff --git a/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt b/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt index e89c2e7467..1eaa7cbea9 100644 --- a/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt +++ b/finance/src/main/kotlin/net/corda/contracts/asset/Obligation.kt @@ -531,7 +531,7 @@ class Obligation

: Contract { // Produce a new set of states val groups = statesAndRefs.groupBy { it.state.data.amount.token } - for ((aggregateState, stateAndRefs) in groups) { + for ((_, stateAndRefs) in groups) { val partiesUsed = ArrayList() stateAndRefs.forEach { stateAndRef -> val outState = stateAndRef.state.data.copy(lifecycle = lifecycle) diff --git a/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt b/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt index 0d22d6c5fe..52657aa6dd 100644 --- a/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt +++ b/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt @@ -14,7 +14,10 @@ import net.corda.core.serialization.OpaqueBytes import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.DUMMY_NOTARY import net.corda.flows.IssuerFlow.IssuanceRequester -import net.corda.testing.* +import net.corda.testing.BOC +import net.corda.testing.MEGA_CORP +import net.corda.testing.initiateSingleShotFlow +import net.corda.testing.ledger import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetwork.MockNode import org.junit.Test @@ -86,7 +89,7 @@ class IssuerFlowTest { runIssuerAndIssueRequester(bankOfCordaNode, bankClientNode, Amount(pennies, amount.token), issueToPartyAndRef) } handles.forEach { - require (it.issueRequestResult.get() is SignedTransaction) + require(it.issueRequestResult.get() is SignedTransaction) } bankOfCordaNode.stop() @@ -95,10 +98,10 @@ class IssuerFlowTest { } private fun runIssuerAndIssueRequester(issuerNode: MockNode, issueToNode: MockNode, - amount: Amount, issueToPartyAndRef: PartyAndReference) : RunResult { + amount: Amount, issueToPartyAndRef: PartyAndReference): RunResult { val resolvedIssuerParty = issuerNode.services.identityService.partyFromAnonymous(issueToPartyAndRef) ?: throw IllegalStateException() - val issuerFuture = issuerNode.initiateSingleShotFlow(IssuerFlow.IssuanceRequester::class) { - otherParty -> IssuerFlow.Issuer(resolvedIssuerParty) + val issuerFuture = issuerNode.initiateSingleShotFlow(IssuerFlow.IssuanceRequester::class) { _ -> + IssuerFlow.Issuer(resolvedIssuerParty) }.map { it.stateMachine } val issueRequest = IssuanceRequester(amount, resolvedIssuerParty, issueToPartyAndRef.reference, issuerNode.info.legalIdentity) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt index 9fe2594ba9..be6b3db136 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/DistributedServiceTests.kt @@ -3,7 +3,6 @@ package net.corda.node.services import net.corda.core.bufferUntilSubscribed import net.corda.core.contracts.Amount import net.corda.core.contracts.POUNDS -import net.corda.core.contracts.issuedBy import net.corda.core.crypto.Party import net.corda.core.getOrThrow import net.corda.core.messaging.CordaRPCOps @@ -89,7 +88,7 @@ class DistributedServiceTests : DriverBasedTest() { expect(match = { it.second is StateMachineUpdate.Added }) { val (notary, update) = it update as StateMachineUpdate.Added - notarisationsPerNotary.compute(notary.legalIdentity) { _key, number -> number?.plus(1) ?: 1 } + notarisationsPerNotary.compute(notary.legalIdentity) { _, number -> number?.plus(1) ?: 1 } } } } @@ -128,7 +127,7 @@ class DistributedServiceTests : DriverBasedTest() { expect(match = { it.second is StateMachineUpdate.Added }) { val (notary, update) = it update as StateMachineUpdate.Added - notarisationsPerNotary.compute(notary.legalIdentity) { _key, number -> number?.plus(1) ?: 1 } + notarisationsPerNotary.compute(notary.legalIdentity) { _, number -> number?.plus(1) ?: 1 } } } } diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt index fdb1667b3e..43617eafba 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt @@ -107,7 +107,7 @@ class P2PMessagingTest : NodeBasedTest() { } private fun Node.respondWith(message: Any) { - net.addMessageHandler(javaClass.name, DEFAULT_SESSION_ID) { netMessage, reg -> + net.addMessageHandler(javaClass.name, DEFAULT_SESSION_ID) { netMessage, _ -> val request = netMessage.data.deserialize() val response = net.createMessage(javaClass.name, request.sessionID, message.serialize().bytes) net.send(response, request.replyTo) diff --git a/node/src/main/kotlin/net/corda/node/internal/Node.kt b/node/src/main/kotlin/net/corda/node/internal/Node.kt index d1cb5fa479..dd83d96628 100644 --- a/node/src/main/kotlin/net/corda/node/internal/Node.kt +++ b/node/src/main/kotlin/net/corda/node/internal/Node.kt @@ -243,7 +243,7 @@ class Node(override val configuration: FullNodeConfiguration, JmxReporter. forRegistry(services.monitoringService.metrics). inDomain("net.corda"). - createsObjectNamesWith { type, domain, name -> + createsObjectNamesWith { _, domain, name -> // Make the JMX hierarchy a bit better organised. val category = name.substringBefore('.') val subName = name.substringAfter('.', "") diff --git a/node/src/main/kotlin/net/corda/node/services/api/AbstractNodeService.kt b/node/src/main/kotlin/net/corda/node/services/api/AbstractNodeService.kt index 1640567e64..2ce4a2a2f7 100644 --- a/node/src/main/kotlin/net/corda/node/services/api/AbstractNodeService.kt +++ b/node/src/main/kotlin/net/corda/node/services/api/AbstractNodeService.kt @@ -31,7 +31,7 @@ abstract class AbstractNodeService(val services: ServiceHubInternal) : Singleton addMessageHandler(topic: String, crossinline handler: (Q) -> R, crossinline exceptionConsumer: (Message, Exception) -> Unit): MessageHandlerRegistration { - return net.addMessageHandler(topic, DEFAULT_SESSION_ID) { message, r -> + return net.addMessageHandler(topic, DEFAULT_SESSION_ID) { message, _ -> try { val request = message.data.deserialize() val response = handler(request) @@ -57,7 +57,7 @@ abstract class AbstractNodeService(val services: ServiceHubInternal) : Singleton protected inline fun addMessageHandler(topic: String, crossinline handler: (Q) -> R): MessageHandlerRegistration { - return addMessageHandler(topic, handler, { message: Message, exception: Exception -> throw exception }) + return addMessageHandler(topic, handler, { _: Message, exception: Exception -> throw exception }) } } diff --git a/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt b/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt index a14361ef88..f6e1beb8aa 100644 --- a/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt +++ b/node/src/main/kotlin/net/corda/node/services/events/NodeSchedulerService.kt @@ -2,7 +2,6 @@ package net.corda.node.services.events import co.paralleluniverse.fibers.Suspendable import com.google.common.util.concurrent.SettableFuture -import kotlinx.support.jdk8.collections.compute import net.corda.core.ThreadBox import net.corda.core.contracts.SchedulableState import net.corda.core.contracts.ScheduledActivity @@ -200,7 +199,7 @@ class NodeSchedulerService(private val database: Database, var scheduledLogic: FlowLogic<*>? = null scheduler.mutex.locked { // need to remove us from those scheduled, but only if we are still next - scheduledStates.compute(scheduledState.ref) { ref, value -> + scheduledStates.compute(scheduledState.ref) { _, value -> if (value === scheduledState) { if (scheduledActivity == null) { logger.info("Scheduled state $scheduledState has rescheduled to never.") diff --git a/node/src/main/kotlin/net/corda/node/services/network/InMemoryNetworkMapCache.kt b/node/src/main/kotlin/net/corda/node/services/network/InMemoryNetworkMapCache.kt index b539414fe6..995dbff480 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/InMemoryNetworkMapCache.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/InMemoryNetworkMapCache.kt @@ -81,7 +81,7 @@ open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCach ifChangedSinceVer: Int?): ListenableFuture { if (subscribe && !registeredForPush) { // Add handler to the network, for updates received from the remote network map service. - net.addMessageHandler(NetworkMapService.PUSH_TOPIC, DEFAULT_SESSION_ID) { message, r -> + net.addMessageHandler(NetworkMapService.PUSH_TOPIC, DEFAULT_SESSION_ID) { message, _ -> try { val req = message.data.deserialize() val ackMessage = net.createMessage(NetworkMapService.PUSH_ACK_TOPIC, DEFAULT_SESSION_ID, @@ -99,9 +99,9 @@ open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCach // Fetch the network map and register for updates at the same time val req = NetworkMapService.FetchMapRequest(subscribe, ifChangedSinceVer, net.myAddress) - val future = net.sendRequest(NetworkMapService.FETCH_TOPIC, req, networkMapAddress).map { resp -> + val future = net.sendRequest(NetworkMapService.FETCH_TOPIC, req, networkMapAddress).map { (nodes) -> // We may not receive any nodes back, if the map hasn't changed since the version specified - resp.nodes?.forEach { processRegistration(it) } + nodes?.forEach { processRegistration(it) } Unit } _registrationFuture.setFuture(future) diff --git a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt index 5d3ea8c9dc..8b9027fa4f 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapService.kt @@ -1,8 +1,6 @@ package net.corda.node.services.network import com.google.common.annotations.VisibleForTesting -import kotlinx.support.jdk8.collections.compute -import kotlinx.support.jdk8.collections.removeIf import net.corda.core.ThreadBox import net.corda.core.crypto.DigitalSignature import net.corda.core.crypto.Party @@ -108,6 +106,7 @@ interface NetworkMapService { @CordaSerializable data class Update(val wireReg: WireNodeRegistration, val mapVersion: Int, val replyTo: MessageRecipients) + @CordaSerializable data class UpdateAcknowledge(val mapVersion: Int, val replyTo: MessageRecipients) } @@ -162,7 +161,7 @@ abstract class AbstractNetworkMapService(services: ServiceHubInternal) : Network handlers += addMessageHandler(QUERY_TOPIC) { req: QueryIdentityRequest -> processQueryRequest(req) } handlers += addMessageHandler(REGISTER_TOPIC) { req: RegistrationRequest -> processRegistrationRequest(req) } handlers += addMessageHandler(SUBSCRIPTION_TOPIC) { req: SubscribeRequest -> processSubscriptionRequest(req) } - handlers += net.addMessageHandler(PUSH_ACK_TOPIC, DEFAULT_SESSION_ID) { message, r -> + handlers += net.addMessageHandler(PUSH_ACK_TOPIC, DEFAULT_SESSION_ID) { message, _ -> val req = message.data.deserialize() processAcknowledge(req) } @@ -237,7 +236,7 @@ abstract class AbstractNetworkMapService(services: ServiceHubInternal) : Network // in on different threads, there is no risk of a race condition while checking // sequence numbers. val registrationInfo = try { - nodeRegistrations.compute(node.legalIdentity) { mapKey: Party, existing: NodeRegistrationInfo? -> + nodeRegistrations.compute(node.legalIdentity) { _: Party, existing: NodeRegistrationInfo? -> require(!((existing == null || existing.reg.type == REMOVE) && change.type == REMOVE)) { "Attempting to de-register unknown node" } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt index 993797b6a0..1b36e82b6c 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowStateMachineImpl.kt @@ -62,8 +62,7 @@ class FlowStateMachineImpl(override val id: StateMachineRunId, Strand.sleep(millis) StrandLocalTransactionManager.database = db TransactionManager.manager.newTransaction(Connection.TRANSACTION_REPEATABLE_READ) - } - else Strand.sleep(millis) + } else Strand.sleep(millis) } } @@ -358,7 +357,7 @@ class FlowStateMachineImpl(override val id: StateMachineRunId, waitingForResponse = ioRequest var exceptionDuringSuspend: Throwable? = null - parkAndSerialize { f, s -> + parkAndSerialize { _, _ -> logger.trace { "Suspended on $ioRequest" } // restore the Tx onto the ThreadLocal so that we can commit the ensuing checkpoint to the DB try { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt index 79d2cffd92..1f04e0a332 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt @@ -232,7 +232,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal, started = true stateMachines.keys.forEach { resumeRestoredFiber(it) } } - serviceHub.networkService.addMessageHandler(sessionTopic) { message, reg -> + serviceHub.networkService.addMessageHandler(sessionTopic) { message, _ -> executor.checkOnThread() onSessionMessage(message) } diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt index 7581506578..c63e2b50ca 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRt.kt @@ -102,7 +102,7 @@ object BFTSMaRt { /** An extractor to build the final response message for the client application from all received replica replies. */ private fun buildExtractor(): Extractor { - return Extractor { replies, sameContent, lastReceived -> + return Extractor { replies, _, lastReceived -> val responses = replies.mapNotNull { it?.content?.deserialize() } val accepted = responses.filterIsInstance() val rejected = responses.filterIsInstance() @@ -156,7 +156,7 @@ object BFTSMaRt { } override fun appExecuteBatch(command: Array, mcs: Array): Array { - val replies = command.zip(mcs) { c, m -> + val replies = command.zip(mcs) { c, _ -> executeCommand(c) } return replies.toTypedArray() diff --git a/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt b/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt index b6e05fdf17..9360e8613a 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/CashBalanceAsMetricsObserver.kt @@ -13,7 +13,7 @@ import java.util.* class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal, val database: Database) { init { // TODO: Need to consider failure scenarios. This needs to run if the TX is successfully recorded - serviceHubInternal.vaultService.updates.subscribe { update -> + serviceHubInternal.vaultService.updates.subscribe { _ -> exportCashBalancesViaMetrics(serviceHubInternal.vaultService) } } diff --git a/node/src/main/kotlin/net/corda/node/utilities/ClockUtils.kt b/node/src/main/kotlin/net/corda/node/utilities/ClockUtils.kt index 5de3578a9f..9c678af89c 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/ClockUtils.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/ClockUtils.kt @@ -120,7 +120,7 @@ private fun makeStrandFriendlySettableFuture(future: Future): Setta settable } else if (future is CompletableFuture) { val settable = SettableFuture() - future.whenComplete(BiConsumer { value, throwable -> settable.set(true) }) + future.whenComplete(BiConsumer { _, _ -> settable.set(true) }) settable } else { throw IllegalArgumentException("Cannot make future $future Fiber friendly.") diff --git a/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt b/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt index 93be612b3d..8979ea6fc9 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/JDBCHashMap.kt @@ -26,7 +26,7 @@ import kotlin.system.measureTimeMillis * TODO: make this value configurable * TODO: tune this value, as it's currently mostly a guess */ -val DEFAULT_MAX_BUCKETS = (256 * (1 + Math.max(0, (Runtime.getRuntime().maxMemory()/1000000 - 128) / 64))).toInt() +val DEFAULT_MAX_BUCKETS = (256 * (1 + Math.max(0, (Runtime.getRuntime().maxMemory() / 1000000 - 128) / 64))).toInt() /** * A convenient JDBC table backed hash map with iteration order based on insertion order. @@ -255,7 +255,7 @@ abstract class AbstractJDBCHashMap(va override fun remove(key: K): V? { val bucket = getBucket(key) var removed: V? = null - buckets.computeIfPresent(key.hashCode()) { hashCode, value -> + buckets.computeIfPresent(key.hashCode()) { _, value -> for (entry in value) { if (entry.key == key) { removed = entry.value @@ -369,7 +369,7 @@ abstract class AbstractJDBCHashMap(va var oldValue: V? = null var oldSeqNo: Int? = null getBucket(key) - buckets.compute(key.hashCode()) { hashCode, list -> + buckets.compute(key.hashCode()) { _, list -> val newList = list ?: newBucket() val iterator = newList.listIterator() while (iterator.hasNext()) { @@ -424,7 +424,7 @@ abstract class AbstractJDBCHashMap(va } private fun getBucket(key: Any): MutableList> { - return buckets.computeIfAbsent(key.hashCode()) { hashCode -> + return buckets.computeIfAbsent(key.hashCode()) { _ -> if (!loadOnInit) { loadBucket(key.hashCode()) } else { diff --git a/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt b/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt index a5ee0e1445..187e4c4cd7 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/InMemoryMessagingTests.kt @@ -41,13 +41,13 @@ class InMemoryMessagingTests { var finalDelivery: Message? = null with(node2) { - node2.net.addMessageHandler { msg, registration -> + node2.net.addMessageHandler { msg, _ -> node2.net.send(msg, node3.info.address) } } with(node3) { - node2.net.addMessageHandler { msg, registration -> + node2.net.addMessageHandler { msg, _ -> finalDelivery = msg } } @@ -69,7 +69,7 @@ class InMemoryMessagingTests { val bits = "test-content".toByteArray() var counter = 0 - listOf(node1, node2, node3).forEach { it.net.addMessageHandler { msg, registration -> counter++ } } + listOf(node1, node2, node3).forEach { it.net.addMessageHandler { _, _ -> counter++ } } node1.net.send(node2.net.createMessage("test.topic", DEFAULT_SESSION_ID, bits), network.messagingNetwork.everyoneOnline) network.runNetwork(rounds = 1) assertEquals(3, counter) @@ -85,7 +85,7 @@ class InMemoryMessagingTests { val node2 = network.createNode(networkMapAddress = node1.info.address) var received: Int = 0 - node1.net.addMessageHandler("valid_message") { msg, reg -> + node1.net.addMessageHandler("valid_message") { _, _ -> received++ } diff --git a/node/src/test/kotlin/net/corda/node/services/AbstractNetworkMapServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/AbstractNetworkMapServiceTest.kt index 1e827068bb..766e1a5dd4 100644 --- a/node/src/test/kotlin/net/corda/node/services/AbstractNetworkMapServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/AbstractNetworkMapServiceTest.kt @@ -219,7 +219,7 @@ abstract class AbstractNetworkMapServiceTest private fun MockNode.subscribe(): List { val request = SubscribeRequest(true, info.address) val updates = BlockingArrayQueue() - services.networkService.addMessageHandler(PUSH_TOPIC, DEFAULT_SESSION_ID) { message, r -> + services.networkService.addMessageHandler(PUSH_TOPIC, DEFAULT_SESSION_ID) { message, _ -> updates += message.data.deserialize() } val response = services.networkService.sendRequest(SUBSCRIPTION_TOPIC, request, mapServiceNode.info.address) @@ -260,6 +260,7 @@ abstract class AbstractNetworkMapServiceTest class Added(node: NodeInfo) : Changed(node) { constructor(node: MockNode) : this(node.info) } + class Removed(node: NodeInfo) : Changed(node) { constructor(node: MockNode) : this(node.info) } diff --git a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt index 4006143a71..2c887923f6 100644 --- a/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/messaging/ArtemisMessagingTests.kt @@ -208,10 +208,10 @@ class ArtemisMessagingTests { val messagingClient = createMessagingClient() startNodeMessagingClient() - messagingClient.addMessageHandler(topic) { message, r -> + messagingClient.addMessageHandler(topic) { message, _ -> receivedMessages.add(message) } - messagingClient.addMessageHandler(NetworkMapService.FETCH_TOPIC) { message, r -> + messagingClient.addMessageHandler(NetworkMapService.FETCH_TOPIC) { message, _ -> receivedMessages.add(message) } // Run after the handlers are added, otherwise (some of) the messages get delivered and discarded / dead-lettered. diff --git a/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt b/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt index 72e0cddbf8..f87a2ccd77 100644 --- a/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt +++ b/samples/irs-demo/src/main/kotlin/net/corda/simulation/Simulation.kt @@ -75,7 +75,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, } fun createAll(): List { - return bankLocations.mapIndexed { i, location -> + return bankLocations.mapIndexed { i, _ -> // Use deterministic seeds so the simulation is stable. Needed so that party owning keys are stable. network.createNode(networkMap.info.address, start = false, nodeFactory = this, entropyRoot = BigInteger.valueOf(i.toLong())) as SimulatedNode } @@ -258,7 +258,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, } private fun linkConsensus(nodes: Collection, flow: FlowLogic<*>) { - flow.progressTracker?.changes?.subscribe { change: ProgressTracker.Change -> + flow.progressTracker?.changes?.subscribe { _: ProgressTracker.Change -> // Runs on node thread. if (flow.progressTracker!!.currentStep == ProgressTracker.DONE) { _doneSteps.onNext(nodes) diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt index 1982774a92..17cf419142 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/NetworkMapVisualiser.kt @@ -157,7 +157,7 @@ class NetworkMapVisualiser : Application() { reloadStylesheet(stage) - stage.focusedProperty().addListener { value, old, new -> + stage.focusedProperty().addListener { _, _, new -> if (new) { reloadStylesheet(stage) } @@ -209,7 +209,7 @@ class NetworkMapVisualiser : Application() { viewModel.runningPausedState = newRunningPausedState } view.styleChoice.selectionModel.selectedItemProperty() - .addListener { ov, value, newValue -> viewModel.displayStyle = newValue } + .addListener { _, _, newValue -> viewModel.displayStyle = newValue } viewModel.simulation.dateChanges.observeOn(uiThread).subscribe { view.dateLabel.text = it.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) } } @@ -239,7 +239,7 @@ class NetworkMapVisualiser : Application() { val extraLabel = viewModel.simulation.extraNodeLabels[node] val label = if (extraLabel != null) "${node.info.legalIdentity.name}: $extraLabel" else node.info.legalIdentity.name val widget = view.buildProgressTrackerWidget(label, tracker.topLevelTracker) - println("Added: ${tracker}, ${widget}") + println("Added: $tracker, $widget") viewModel.trackerBoxes[tracker] = widget view.sidebar.children += widget.vbox } else { @@ -256,7 +256,7 @@ class NetworkMapVisualiser : Application() { val pane = viewModel.trackerBoxes[tracker]!!.vbox // Slide the other tracker widgets up and over this one. val slideProp = SimpleDoubleProperty(0.0) - slideProp.addListener { obv -> pane.padding = Insets(0.0, 0.0, slideProp.value, 0.0) } + slideProp.addListener { _ -> pane.padding = Insets(0.0, 0.0, slideProp.value, 0.0) } val timeline = Timeline( KeyFrame(Duration(250.0), KeyValue(pane.opacityProperty(), 0.0), diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt index 5117ac0784..85e1c967ae 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/VisualiserViewModel.kt @@ -62,14 +62,14 @@ class VisualiserViewModel { fun repositionNodes() { for ((index, bank) in simulation.banks.withIndex()) { nodesToWidgets[bank]!!.position(index, when (displayStyle) { - Style.MAP -> { node, index -> nodeMapCoords(node) } - Style.CIRCLE -> { node, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.BANK, index) } + Style.MAP -> { node, _ -> nodeMapCoords(node) } + Style.CIRCLE -> { _, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.BANK, index) } }) } for ((index, serviceProvider) in (simulation.serviceProviders + simulation.regulators).withIndex()) { nodesToWidgets[serviceProvider]!!.position(index, when (displayStyle) { - Style.MAP -> { node, index -> nodeMapCoords(node) } - Style.CIRCLE -> { node, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.SERVICE, index) } + Style.MAP -> { node, _ -> nodeMapCoords(node) } + Style.CIRCLE -> { _, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.SERVICE, index) } }) } } @@ -170,8 +170,8 @@ class VisualiserViewModel { val widget = NodeWidget(forNode, innerDot, outerDot, longPulseOuterDot, pulseAnim, longPulseAnim, nameLabel, statusLabel) when (displayStyle) { - Style.CIRCLE -> widget.position(index, { node, index -> nodeCircleCoords(nodeType, index) }) - Style.MAP -> widget.position(index, { node, index -> nodeMapCoords(node) }) + Style.CIRCLE -> widget.position(index, { _, index -> nodeCircleCoords(nodeType, index) }) + Style.MAP -> widget.position(index, { node, _ -> nodeMapCoords(node) }) } return widget } diff --git a/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt b/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt index fb30e57eea..4a70526e33 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/TestDSL.kt @@ -3,7 +3,6 @@ package net.corda.testing import net.corda.core.contracts.* import net.corda.core.crypto.* import net.corda.core.node.ServiceHub -import net.corda.core.node.recordTransactions import net.corda.core.serialization.serialize import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.TransactionBuilder @@ -75,7 +74,7 @@ fun LedgerDSLInterpreter.ledger( * the triggered diagnostic. */ sealed class EnforceVerifyOrFail { - internal object Token: EnforceVerifyOrFail() + internal object Token : EnforceVerifyOrFail() } class DuplicateOutputLabel(label: String) : Exception("Output label '$label' already used") @@ -154,7 +153,7 @@ data class TestTransactionDSLInterpreter private constructor( ) = dsl(TransactionDSL(copy())) } -data class TestLedgerDSLInterpreter private constructor ( +data class TestLedgerDSLInterpreter private constructor( val services: ServiceHub, internal val labelToOutputStateAndRefs: HashMap> = HashMap(), private val transactionWithLocations: HashMap = LinkedHashMap(), @@ -233,7 +232,7 @@ data class TestLedgerDSLInterpreter private constructor ( } fun outputToLabel(state: ContractState): String? = - labelToOutputStateAndRefs.filter { it.value.state.data == state }.keys.firstOrNull() + labelToOutputStateAndRefs.filter { it.value.state.data == state }.keys.firstOrNull() private fun recordTransactionWithTransactionMap( transactionLabel: String?, @@ -283,7 +282,7 @@ data class TestLedgerDSLInterpreter private constructor ( try { val usedInputs = mutableSetOf() services.recordTransactions(transactionsUnverified.map { SignedTransaction(it.serialized, listOf(NullSignature)) }) - for ((key, value) in transactionWithLocations) { + for ((_, value) in transactionWithLocations) { val wtx = value.transaction val ltx = wtx.toLedgerTransaction(services) ltx.verify() diff --git a/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt b/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt index bee1c16cbe..bde29f0ebc 100644 --- a/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt +++ b/test-utils/src/main/kotlin/net/corda/testing/node/InMemoryMessagingNetwork.kt @@ -66,7 +66,7 @@ class InMemoryMessagingNetwork( private val messageSendQueue = LinkedBlockingQueue() private val _sentMessages = PublishSubject.create() @Suppress("unused") // Used by the visualiser tool. - /** A stream of (sender, message, recipients) triples */ + /** A stream of (sender, message, recipients) triples */ val sentMessages: Observable get() = _sentMessages @@ -82,7 +82,7 @@ class InMemoryMessagingNetwork( private val serviceToPeersMapping = HashMap>() @Suppress("unused") // Used by the visualiser tool. - /** A stream of (sender, message, recipients) triples */ + /** A stream of (sender, message, recipients) triples */ val receivedMessages: Observable get() = _receivedMessages @@ -217,10 +217,11 @@ class InMemoryMessagingNetwork( return pickFrom[random.nextInt(pickFrom.size)] } } + class RoundRobin : ServicePeerAllocationStrategy() { val previousPicks = HashMap() override fun pickNext(service: ServiceHandle, pickFrom: List): A { - val nextIndex = previousPicks.compute(service) { _key, previous -> + val nextIndex = previousPicks.compute(service) { _, previous -> (previous?.plus(1) ?: 0) % pickFrom.size }!! return pickFrom[nextIndex] diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt index 93c4ca0670..840f985a86 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt @@ -35,9 +35,7 @@ import net.corda.node.services.transactions.SimpleNotaryService import net.corda.nodeapi.User import org.apache.commons.lang.SystemUtils import org.controlsfx.dialog.ExceptionDialog -import tornadofx.App -import tornadofx.addStageIcon -import tornadofx.find +import tornadofx.* import java.util.* import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.ExecutionException @@ -99,7 +97,7 @@ class Main : App(MainView::class) { init { // Shows any uncaught exception in exception dialog. - Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> + Thread.setDefaultUncaughtExceptionHandler { _, throwable -> throwable.printStackTrace() // Show exceptions in exception dialog. Ensure this runs in application thread. runInFxApplicationThread { @@ -156,19 +154,19 @@ fun main(args: Array) { ) // TODO : Supported flow should be exposed somehow from the node instead of set of ServiceInfo. val notary = startNode("Notary", advertisedServices = setOf(ServiceInfo(SimpleNotaryService.type)), - customOverrides = mapOf("nearestCity" to "Zurich")) + customOverrides = mapOf("nearestCity" to "Zurich")) val alice = startNode("Alice", rpcUsers = arrayListOf(user), - advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("cash"))), - customOverrides = mapOf("nearestCity" to "Milan")) + advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("cash"))), + customOverrides = mapOf("nearestCity" to "Milan")) val bob = startNode("Bob", rpcUsers = arrayListOf(user), - advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("cash"))), - customOverrides = mapOf("nearestCity" to "Madrid")) + advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("cash"))), + customOverrides = mapOf("nearestCity" to "Madrid")) val issuerGBP = startNode("UK Bank Plc", rpcUsers = arrayListOf(manager), - advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("issuer.GBP"))), - customOverrides = mapOf("nearestCity" to "London")) + advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("issuer.GBP"))), + customOverrides = mapOf("nearestCity" to "London")) val issuerUSD = startNode("USA Bank Corp", rpcUsers = arrayListOf(manager), - advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("issuer.USD"))), - customOverrides = mapOf("nearestCity" to "New York")) + advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("issuer.USD"))), + customOverrides = mapOf("nearestCity" to "New York")) val notaryNode = notary.get() val aliceNode = alice.get() @@ -220,12 +218,12 @@ fun main(args: Array) { val maxIterations = 100000 val flowHandles = mapOf( - "GBPIssuer" to ArrayBlockingQueue>(maxIterations+1), - "USDIssuer" to ArrayBlockingQueue>(maxIterations+1), - "Alice" to ArrayBlockingQueue>(maxIterations+1), - "Bob" to ArrayBlockingQueue>(maxIterations+1), - "GBPExit" to ArrayBlockingQueue>(maxIterations+1), - "USDExit" to ArrayBlockingQueue>(maxIterations+1) + "GBPIssuer" to ArrayBlockingQueue>(maxIterations + 1), + "USDIssuer" to ArrayBlockingQueue>(maxIterations + 1), + "Alice" to ArrayBlockingQueue>(maxIterations + 1), + "Bob" to ArrayBlockingQueue>(maxIterations + 1), + "GBPExit" to ArrayBlockingQueue>(maxIterations + 1), + "USDExit" to ArrayBlockingQueue>(maxIterations + 1) ) flowHandles.forEach { @@ -252,14 +250,14 @@ fun main(args: Array) { println("[$i] ISSUING ${command.amount} with ref ${command.issueRef} to ${command.recipient}") val cmd = command.startFlow(issuerRPCGBP) flowHandles["GBPIssuer"]?.add(cmd) - cmd?.progress?.subscribe({},{})?.unsubscribe() + cmd.progress.subscribe({}, {})?.unsubscribe() Unit }.generate(SplittableRandom()) issuerUSDEventGenerator.bankOfCordaIssueGenerator.map { command -> println("[$i] ISSUING ${command.amount} with ref ${command.issueRef} to ${command.recipient}") val cmd = command.startFlow(issuerRPCUSD) flowHandles["USDIssuer"]?.add(cmd) - cmd?.progress?.subscribe({},{})?.unsubscribe() + cmd.progress.subscribe({}, {})?.unsubscribe() Unit }.generate(SplittableRandom()) } @@ -270,14 +268,14 @@ fun main(args: Array) { println("[$i] EXITING ${command.amount} with ref ${command.issueRef}") val cmd = command.startFlow(issuerRPCGBP) flowHandles["GBPExit"]?.add(cmd) - cmd?.progress?.subscribe({},{})?.unsubscribe() + cmd.progress.subscribe({}, {})?.unsubscribe() Unit }.generate(SplittableRandom()) issuerUSDEventGenerator.bankOfCordaExitGenerator.map { command -> println("[$i] EXITING ${command.amount} with ref ${command.issueRef}") val cmd = command.startFlow(issuerRPCUSD) flowHandles["USDExit"]?.add(cmd) - cmd?.progress?.subscribe({},{})?.unsubscribe() + cmd.progress.subscribe({}, {})?.unsubscribe() Unit }.generate(SplittableRandom()) } @@ -289,7 +287,7 @@ fun main(args: Array) { println("[$i] SENDING ${command.amount} from ${aliceRPC.nodeIdentity().legalIdentity} to ${command.recipient}") val cmd = command.startFlow(aliceRPC) flowHandles["Alice"]?.add(cmd) - cmd?.progress?.subscribe({},{})?.unsubscribe() + cmd.progress.subscribe({}, {})?.unsubscribe() Unit }.generate(SplittableRandom()) @@ -298,7 +296,7 @@ fun main(args: Array) { println("[$i] SENDING ${command.amount} from ${bobRPC.nodeIdentity().legalIdentity} to ${command.recipient}") val cmd = command.startFlow(bobRPC) flowHandles["Bob"]?.add(cmd) - cmd?.progress?.subscribe({},{})?.unsubscribe() + cmd.progress.subscribe({}, {})?.unsubscribe() Unit }.generate(SplittableRandom()) } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt index eabdc07875..c5fc9ce711 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt @@ -29,7 +29,7 @@ class Dashboard : CordaView() { init { Bindings.bindContent(tilePane.children, widgetPanes) // Dynamically change column count and width according to the window size. - tilePane.widthProperty().addListener { e -> + tilePane.widthProperty().addListener { _ -> val prefWidth = 350 val columns: Int = ((tilePane.width - 10) / prefWidth).toInt() tilePane.children.forEach { (it as? TitledPane)?.prefWidth = (tilePane.width - 10) / columns } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt index 2ed45d90ec..fa941e7688 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt @@ -118,7 +118,7 @@ class Network : CordaView() { Bindings.bindContent(mapPane.children, mapLabels) // Run once when the screen is ready. // TODO : Find a better way to do this. - mapPane.heightProperty().addListener { _o, old, _new -> + mapPane.heightProperty().addListener { _, old, _ -> if (old == 0.0) myMapLabel.value?.let { mapScrollPane.centerLabel(it) } } // Listen on zooming gesture, if device has gesture support. @@ -128,7 +128,7 @@ class Network : CordaView() { zoomInButton.setOnAction { zoom(1.2) } zoomOutButton.setOnAction { zoom(0.8) } - lastTransactions.addListener { observableValue, old, new -> + lastTransactions.addListener { _, _, new -> new?.forEach { it.first.value?.let { a -> it.second.value?.let { b -> diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/CashViewer.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/CashViewer.kt index bc132c9527..064c86cf7f 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/CashViewer.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/CashViewer.kt @@ -17,8 +17,8 @@ import javafx.scene.layout.BorderPane import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.VBox -import net.corda.client.jfx.utils.* import net.corda.client.jfx.model.* +import net.corda.client.jfx.utils.* import net.corda.contracts.asset.Cash import net.corda.core.contracts.Amount import net.corda.core.contracts.StateAndRef @@ -220,7 +220,7 @@ class CashViewer : CordaView("Cash") { root.isExpanded = true isShowRoot = false // TODO use smart resize - setColumnPrefWidthPolicy { tableWidthWithoutPaddingAndBorder, column -> + setColumnPrefWidthPolicy { tableWidthWithoutPaddingAndBorder, _ -> Math.floor(tableWidthWithoutPaddingAndBorder.toDouble() / columns.size).toInt() } } @@ -229,7 +229,7 @@ class CashViewer : CordaView("Cash") { cashViewerTableIssuerCurrency.setCellValueFactory { val node = it.value.value when (node) { - // TODO: Anonymous should probably be italicised or similar + // TODO: Anonymous should probably be italicised or similar is ViewerNode.IssuerNode -> SimpleStringProperty(node.issuer.nameOrNull() ?: "Anonymous") is ViewerNode.CurrencyNode -> node.amount.map { it.token.toString() } } @@ -308,7 +308,7 @@ class CashViewer : CordaView("Cash") { } linechart(null, xAxis, yAxis) { series("USD") { - sumAmount.addListener { observableValue, old, new -> + sumAmount.addListener { _, _, _ -> val lastTimeStamp = data.last().value?.xValue if (lastTimeStamp == null || System.currentTimeMillis() - lastTimeStamp.toLong() > 1.seconds.toMillis()) { data(System.currentTimeMillis(), sumAmount.value.quantity) diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt index fdecd598c5..74a221b9e4 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt @@ -52,23 +52,23 @@ fun hang(hangIntervalRange: LongRange) = Disruption("Hang randomly") { node, ran node.doWhileSigStopped { Thread.sleep(hangIntervalMs) } } -val restart = Disruption("Restart randomly") { node, random -> - node.connection.runShellCommandGetOutput("sudo systemctl restart ${node.configuration.remoteSystemdServiceName}").getResultOrThrow() +val restart = Disruption("Restart randomly") { (configuration, connection), _ -> + connection.runShellCommandGetOutput("sudo systemctl restart ${configuration.remoteSystemdServiceName}").getResultOrThrow() } -val kill = Disruption("Kill randomly") { node, random -> +val kill = Disruption("Kill randomly") { node, _ -> val pid = node.getNodePid() node.connection.runShellCommandGetOutput("sudo kill $pid") } -val deleteDb = Disruption("Delete persistence database without restart") { node, random -> - node.connection.runShellCommandGetOutput("sudo rm ${node.configuration.remoteNodeDirectory}/persistence.mv.db").getResultOrThrow() +val deleteDb = Disruption("Delete persistence database without restart") { (configuration, connection), _ -> + connection.runShellCommandGetOutput("sudo rm ${configuration.remoteNodeDirectory}/persistence.mv.db").getResultOrThrow() } // DOCS START 2 -fun strainCpu(parallelism: Int, durationSeconds: Int) = Disruption("Put strain on cpu") { node, random -> +fun strainCpu(parallelism: Int, durationSeconds: Int) = Disruption("Put strain on cpu") { (_, connection), _ -> val shell = "for c in {1..$parallelism} ; do openssl enc -aes-128-cbc -in /dev/urandom -pass pass: -e > /dev/null & done && JOBS=\$(jobs -p) && (sleep $durationSeconds && kill \$JOBS) & wait" - node.connection.runShellCommandGetOutput(shell).getResultOrThrow() + connection.runShellCommandGetOutput(shell).getResultOrThrow() } // DOCS END 2 diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt index 1f35026409..89de5aab27 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt @@ -7,12 +7,8 @@ import net.corda.client.mock.replicatePoisson import net.corda.contracts.asset.Cash import net.corda.core.contracts.USD import net.corda.core.crypto.AbstractParty -import net.corda.core.crypto.Party import net.corda.core.flows.FlowException import net.corda.core.getOrThrow -import net.corda.core.messaging.startFlow -import net.corda.core.toFuture -import net.corda.flows.CashException import net.corda.flows.CashFlowCommand import net.corda.loadtest.LoadTest import net.corda.loadtest.NodeHandle @@ -39,7 +35,7 @@ val selfIssueTest = LoadTest( // DOCS END 1 "Self issuing cash randomly", - generate = { state, parallelism -> + generate = { _, parallelism -> val generateIssue = Generator.pickOne(simpleNodes).bind { node: NodeHandle -> generateIssue(1000, USD, notary.info.notaryIdentity, listOf(node.info.legalIdentity)).map { SelfIssueCommand(it, node) @@ -73,13 +69,13 @@ val selfIssueTest = LoadTest( gatherRemoteState = { previousState -> val selfIssueVaults = HashMap() - simpleNodes.forEach { node -> - val vault = node.connection.proxy.vaultAndUpdates().first + simpleNodes.forEach { (_, connection, info) -> + val vault = connection.proxy.vaultAndUpdates().first vault.forEach { val state = it.state.data if (state is Cash.State) { val issuer = state.amount.token.issuer.party - if (issuer == node.info.legalIdentity as AbstractParty) { + if (issuer == info.legalIdentity as AbstractParty) { selfIssueVaults.put(issuer, (selfIssueVaults[issuer] ?: 0L) + state.amount.quantity) } } @@ -91,7 +87,7 @@ val selfIssueTest = LoadTest( if (!diff.isUntouched) { var diffString = "" - diff.visit { node, visit -> + diff.visit { node, _ -> if (node.isChanged && node.children.all { !it.isChanged }) { diffString += "${node.propertyPath}: simulated[${node.canonicalGet(previousState.vaultsSelfIssued)}], actual[${node.canonicalGet(selfIssueVaults)}]\n" }