diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt index 31cb4bf3e6..26387c1663 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt @@ -23,13 +23,14 @@ object AmountBindings { ) { sum -> Amount(sum.toLong(), token) } fun exchange( - currency: ObservableValue, - exchangeRate: ObservableValue + observableCurrency: ObservableValue, + observableExchangeRate: ObservableValue ): ObservableValue) -> Long>> { - return EasyBind.combine(currency, exchangeRate) { currency, exchangeRate -> - Pair(currency) { amount: Amount -> - (exchangeRate.rate(amount.token, currency) * amount.quantity).toLong() - } + return EasyBind.combine(observableCurrency, observableExchangeRate) { currency, exchangeRate -> + Pair) -> Long>( + currency, + { (quantity, _, token) -> (exchangeRate.rate(token, currency) * quantity).toLong() } + ) } } diff --git a/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt b/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt index 9748e2a2ca..9aec5f1b84 100644 --- a/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt +++ b/client/mock/src/main/kotlin/net/corda/client/mock/Generator.kt @@ -172,7 +172,7 @@ fun Generator.Companion.replicatePoisson(meanSize: Double, generator: Genera val result = mutableListOf() var finish = false while (!finish) { - val result = Generator.doubleRange(0.0, 1.0).generate(it).flatMap { value -> + val res = Generator.doubleRange(0.0, 1.0).generate(it).flatMap { value -> if (value < chance) { generator.generate(it).map { result.add(it) } } else { @@ -180,8 +180,8 @@ fun Generator.Companion.replicatePoisson(meanSize: Double, generator: Genera Try.Success(Unit) } } - if (result is Try.Failure) { - return@Generator result + if (res is Try.Failure) { + return@Generator res } } Try.Success(result) diff --git a/core/src/main/kotlin/net/corda/core/serialization/amqp/ArraySerializer.kt b/core/src/main/kotlin/net/corda/core/serialization/amqp/ArraySerializer.kt index 5d8c09df1c..0890fd2e9b 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/amqp/ArraySerializer.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/amqp/ArraySerializer.kt @@ -10,7 +10,7 @@ import java.lang.reflect.Type open class ArraySerializer(override val type: Type, factory: SerializerFactory) : AMQPSerializer { companion object { fun make(type: Type, factory: SerializerFactory) = when (type) { - Array::class.java -> CharArraySerializer(factory) + Array::class.java -> CharArraySerializer(factory) else -> ArraySerializer(type, factory) } } @@ -73,7 +73,7 @@ open class ArraySerializer(override val type: Type, factory: SerializerFactory) // Boxed Character arrays required a specialisation to handle the type conversion properly when populating // the array since Kotlin won't allow an implicit cast from Int (as they're stored as 16bit ints) to Char -class CharArraySerializer(factory: SerializerFactory) : ArraySerializer(Array::class.java, factory) { +class CharArraySerializer(factory: SerializerFactory) : ArraySerializer(Array::class.java, factory) { override fun List.toArrayOfType(type: Type): Any { val elementType = type.asClass() ?: throw NotSerializableException("Unexpected array element type $type") val list = this diff --git a/core/src/main/kotlin/net/corda/core/serialization/amqp/DeserializationInput.kt b/core/src/main/kotlin/net/corda/core/serialization/amqp/DeserializationInput.kt index 931f876c1c..765c979ebe 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/amqp/DeserializationInput.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/amqp/DeserializationInput.kt @@ -11,7 +11,7 @@ import java.lang.reflect.Type import java.nio.ByteBuffer import java.util.* -data class objectAndEnvelope(val obj: T, val envelope: Envelope) +data class ObjectAndEnvelope(val obj: T, val envelope: Envelope) /** * Main entry point for deserializing an AMQP encoded object. @@ -64,7 +64,7 @@ class DeserializationInput(internal val serializerFactory: SerializerFactory = S @Throws(NotSerializableException::class) - inline internal fun deserializeAndReturnEnvelope(bytes: SerializedBytes): objectAndEnvelope = + inline internal fun deserializeAndReturnEnvelope(bytes: SerializedBytes): ObjectAndEnvelope = deserializeAndReturnEnvelope(bytes, T::class.java) @@ -84,11 +84,10 @@ class DeserializationInput(internal val serializerFactory: SerializerFactory = S return Envelope.get(data) } - @Throws(NotSerializableException::class) - private fun des(bytes: SerializedBytes, clazz: Class, generator: (SerializedBytes, Class) -> R): R { + private fun des(generator: () -> R): R { try { - return generator(bytes, clazz) + return generator() } catch(nse: NotSerializableException) { throw nse } catch(t: Throwable) { @@ -105,27 +104,23 @@ class DeserializationInput(internal val serializerFactory: SerializerFactory = S */ @Throws(NotSerializableException::class) fun deserialize(bytes: SerializedBytes, clazz: Class): T { - return des(bytes, clazz) { bytes, clazz -> - var envelope = getEnvelope(bytes) + return des { + val envelope = getEnvelope(bytes) clazz.cast(readObjectOrNull(envelope.obj, envelope.schema, clazz)) } } @Throws(NotSerializableException::class) - internal fun deserializeAndReturnEnvelope(bytes: SerializedBytes, clazz: Class): objectAndEnvelope { - return des>(bytes, clazz) { bytes, clazz -> + internal fun deserializeAndReturnEnvelope(bytes: SerializedBytes, clazz: Class): ObjectAndEnvelope { + return des { val envelope = getEnvelope(bytes) // Now pick out the obj and schema from the envelope. - objectAndEnvelope(clazz.cast(readObjectOrNull(envelope.obj, envelope.schema, clazz)), envelope) + ObjectAndEnvelope(clazz.cast(readObjectOrNull(envelope.obj, envelope.schema, clazz)), envelope) } } internal fun readObjectOrNull(obj: Any?, schema: Schema, type: Type): Any? { - if (obj == null) { - return null - } else { - return readObject(obj, schema, type) - } + return if (obj == null) null else readObject(obj, schema, type) } internal fun readObject(obj: Any, schema: Schema, type: Type): Any { diff --git a/core/src/main/kotlin/net/corda/core/serialization/amqp/SerializationHelper.kt b/core/src/main/kotlin/net/corda/core/serialization/amqp/SerializationHelper.kt index c77faa5119..4867741062 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/amqp/SerializationHelper.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/amqp/SerializationHelper.kt @@ -112,7 +112,7 @@ internal fun interfacesForSerialization(type: Type): List { private fun exploreType(type: Type?, interfaces: MutableSet) { val clazz = type?.asClass() if (clazz != null) { - if (clazz.isInterface) interfaces += type!! + if (clazz.isInterface) interfaces += type for (newInterface in clazz.genericInterfaces) { if (newInterface !in interfaces) { exploreType(resolveTypeVariables(newInterface, type), interfaces) diff --git a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt index 85415adae5..e3549e762f 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt @@ -121,7 +121,7 @@ data class WireTransaction( } } - fun filterAndNoncesUpdate(filtering: Predicate, t: T, index: Int): Boolean { + fun filterAndNoncesUpdate(t: T, index: Int): Boolean { return if (filtering.test(t)) { nonces.add(computeNonce(privacySalt, index)) true @@ -129,14 +129,15 @@ data class WireTransaction( false } } + // TODO: We should have a warning (require) if all leaves (excluding salt) are visible after filtering. // Consider the above after refactoring FilteredTransaction to implement TraversableTransaction, // so that a WireTransaction can be used when required to send a full tx (e.g. RatesFixFlow in Oracles). return FilteredLeaves( - inputs.filterIndexed { index, it -> filterAndNoncesUpdate(filtering, it, index) }, - attachments.filterIndexed { index, it -> filterAndNoncesUpdate(filtering, it, index + offsets[0]) }, - outputs.filterIndexed { index, it -> filterAndNoncesUpdate(filtering, it, index + offsets[1]) }, - commands.filterIndexed { index, it -> filterAndNoncesUpdate(filtering, it, index + offsets[2]) }, + inputs.filterIndexed { index, it -> filterAndNoncesUpdate(it, index) }, + attachments.filterIndexed { index, it -> filterAndNoncesUpdate(it, index + offsets[0]) }, + outputs.filterIndexed { index, it -> filterAndNoncesUpdate(it, index + offsets[1]) }, + commands.filterIndexed { index, it -> filterAndNoncesUpdate(it, index + offsets[2]) }, notNullFalseAndNoncesUpdate(notary, offsets[3]) as Party?, notNullFalseAndNoncesUpdate(timeWindow, offsets[4]) as TimeWindow?, nonces diff --git a/core/src/test/kotlin/net/corda/core/serialization/SerializationTokenTest.kt b/core/src/test/kotlin/net/corda/core/serialization/SerializationTokenTest.kt index 0f48a5fb8c..de58754b5c 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/SerializationTokenTest.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/SerializationTokenTest.kt @@ -110,11 +110,10 @@ class SerializationTokenTest { } private class WrongTypeSerializeAsToken : SerializeAsToken { - override fun toToken(context: SerializeAsTokenContext): SerializationToken { - return object : SerializationToken { - override fun fromToken(context: SerializeAsTokenContext): Any = UnitSerializeAsToken() - } + object UnitSerializationToken : SerializationToken { + override fun fromToken(context: SerializeAsTokenContext): Any = UnitSerializeAsToken() } + override fun toToken(context: SerializeAsTokenContext): SerializationToken = UnitSerializationToken } @Test(expected = KryoException::class) diff --git a/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeAndReturnEnvelopeTests.kt b/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeAndReturnEnvelopeTests.kt index ca172680cf..310b828b3d 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeAndReturnEnvelopeTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeAndReturnEnvelopeTests.kt @@ -1,11 +1,14 @@ package net.corda.core.serialization.amqp import org.junit.Test -import kotlin.test.* +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue class DeserializeAndReturnEnvelopeTests { - fun testName() = Thread.currentThread().stackTrace[2].methodName + fun testName(): String = Thread.currentThread().stackTrace[2].methodName + @Suppress("NOTHING_TO_INLINE") inline fun classTestName(clazz: String) = "${this.javaClass.name}\$${testName()}\$$clazz" @Test @@ -14,7 +17,7 @@ class DeserializeAndReturnEnvelopeTests { val a = A(10, "20") - var factory = SerializerFactory() + val factory = SerializerFactory() fun serialise(clazz: Any) = SerializationOutput(factory).serialize(clazz) val obj = DeserializationInput(factory).deserializeAndReturnEnvelope(serialise(a)) @@ -30,7 +33,7 @@ class DeserializeAndReturnEnvelopeTests { val b = B(A(10, "20"), 30.0F) - var factory = SerializerFactory() + val factory = SerializerFactory() fun serialise(clazz: Any) = SerializationOutput(factory).serialize(clazz) val obj = DeserializationInput(factory).deserializeAndReturnEnvelope(serialise(b)) diff --git a/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeSimpleTypesTests.kt b/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeSimpleTypesTests.kt index 97361ca92b..6f35766c29 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeSimpleTypesTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/amqp/DeserializeSimpleTypesTests.kt @@ -1,8 +1,8 @@ package net.corda.core.serialization.amqp +import org.apache.qpid.proton.codec.Data import org.junit.Test import kotlin.test.assertEquals -import org.apache.qpid.proton.codec.Data // Prior to certain fixes being made within the [PropertySerializaer] classes these simple // deserialization operations would've blown up with type mismatch errors where the deserlized @@ -52,6 +52,7 @@ class DeserializeSimpleTypesTests { assertEquals('আ', deserializedC.c) } + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") @Test fun testCharacter() { data class C(val c: Character) @@ -92,6 +93,7 @@ class DeserializeSimpleTypesTests { assertEquals(ia.ia[2], deserializedIA.ia[2]) } + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") @Test fun testArrayOfInteger() { class IA(val ia: Array) diff --git a/core/src/test/kotlin/net/corda/core/serialization/carpenter/ClassCarpenterTestUtils.kt b/core/src/test/kotlin/net/corda/core/serialization/carpenter/ClassCarpenterTestUtils.kt index 508c3aeabc..40180e1de7 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/carpenter/ClassCarpenterTestUtils.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/carpenter/ClassCarpenterTestUtils.kt @@ -1,11 +1,8 @@ -package net.corda.core.serialization.carpenter.test +package net.corda.core.serialization.carpenter -import net.corda.core.serialization.amqp.CompositeType +import net.corda.core.serialization.amqp.* import net.corda.core.serialization.amqp.Field import net.corda.core.serialization.amqp.Schema -import net.corda.core.serialization.amqp.TypeNotation -import net.corda.core.serialization.amqp.SerializerFactory -import net.corda.core.serialization.amqp.SerializationOutput fun mangleName(name: String) = "${name}__carpenter" @@ -18,7 +15,7 @@ fun Schema.mangleNames(names: List): Schema { for (type in types) { val newName = if (type.name in names) mangleName(type.name) else type.name - val newProvides = type.provides.map { it -> if (it in names) mangleName(it) else it } + val newProvides = type.provides.map { if (it in names) mangleName(it) else it } val newFields = mutableListOf() (type as CompositeType).fields.forEach { @@ -40,6 +37,7 @@ open class AmqpCarpenterBase { var factory = SerializerFactory() fun serialise(clazz: Any) = SerializationOutput(factory).serialize(clazz) - fun testName() = Thread.currentThread().stackTrace[2].methodName + fun testName(): String = Thread.currentThread().stackTrace[2].methodName + @Suppress("NOTHING_TO_INLINE") inline fun classTestName(clazz: String) = "${this.javaClass.name}\$${testName()}\$$clazz" } diff --git a/core/src/test/kotlin/net/corda/core/serialization/carpenter/CompositeMemberCompositeSchemaToClassCarpenterTests.kt b/core/src/test/kotlin/net/corda/core/serialization/carpenter/CompositeMemberCompositeSchemaToClassCarpenterTests.kt index 13deba5c5f..f3bbbe52e2 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/carpenter/CompositeMemberCompositeSchemaToClassCarpenterTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/carpenter/CompositeMemberCompositeSchemaToClassCarpenterTests.kt @@ -1,6 +1,5 @@ package net.corda.core.serialization.carpenter -import net.corda.core.serialization.carpenter.test.* import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.amqp.* diff --git a/core/src/test/kotlin/net/corda/core/serialization/carpenter/InheritanceSchemaToClassCarpenterTests.kt b/core/src/test/kotlin/net/corda/core/serialization/carpenter/InheritanceSchemaToClassCarpenterTests.kt index 59051e919c..ac8db1a992 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/carpenter/InheritanceSchemaToClassCarpenterTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/carpenter/InheritanceSchemaToClassCarpenterTests.kt @@ -1,7 +1,6 @@ package net.corda.core.serialization.carpenter import net.corda.core.serialization.CordaSerializable -import net.corda.core.serialization.carpenter.test.* import net.corda.core.serialization.amqp.* import org.junit.Test diff --git a/core/src/test/kotlin/net/corda/core/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt b/core/src/test/kotlin/net/corda/core/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt index 462b3d8559..24855be12d 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt @@ -1,6 +1,5 @@ package net.corda.core.serialization.carpenter -import net.corda.core.serialization.carpenter.test.AmqpCarpenterBase import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.amqp.* diff --git a/core/src/test/kotlin/net/corda/core/serialization/carpenter/SingleMemberCompositeSchemaToClassCarpenterTests.kt b/core/src/test/kotlin/net/corda/core/serialization/carpenter/SingleMemberCompositeSchemaToClassCarpenterTests.kt index ef88298dd0..99617f32f0 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/carpenter/SingleMemberCompositeSchemaToClassCarpenterTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/carpenter/SingleMemberCompositeSchemaToClassCarpenterTests.kt @@ -1,6 +1,5 @@ package net.corda.core.serialization.carpenter -import net.corda.core.serialization.carpenter.test.AmqpCarpenterBase import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.amqp.* diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt index c319603392..aa8cd79c95 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt @@ -1,3 +1,5 @@ +@file:Suppress("UNUSED_VARIABLE", "unused") + package net.corda.docs import co.paralleluniverse.fibers.Suspendable @@ -83,6 +85,7 @@ object FlowCookbook { override val progressTracker: ProgressTracker = tracker() + @Suppress("RemoveExplicitTypeArguments") @Suspendable override fun call() { // We'll be using a dummy public key for demonstration purposes. diff --git a/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java b/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java index 56da1049fa..ddc54b3379 100644 --- a/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java +++ b/finance/src/main/java/net/corda/contracts/JavaCommercialPaper.java @@ -32,7 +32,6 @@ import java.util.stream.Collectors; import static net.corda.core.contracts.ContractsDSL.requireSingleCommand; import static net.corda.core.contracts.ContractsDSL.requireThat; - /** * This is a Java version of the CommercialPaper contract (chosen because it's simple). This demonstrates how the * use of Kotlin for implementation of the framework does not impose the same language choice on contract developers. @@ -105,16 +104,17 @@ public class JavaCommercialPaper implements Contract { } @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object that) { + if (this == that) return true; + if (that == null || getClass() != that.getClass()) return false; - State state = (State) o; + State state = (State) that; if (issuance != null ? !issuance.equals(state.issuance) : state.issuance != null) return false; if (owner != null ? !owner.equals(state.owner) : state.owner != null) return false; if (faceValue != null ? !faceValue.equals(state.faceValue) : state.faceValue != null) return false; - return !(maturityDate != null ? !maturityDate.equals(state.maturityDate) : state.maturityDate != null); + if (maturityDate != null ? !maturityDate.equals(state.maturityDate) : state.maturityDate != null) return false; + return true; } @Override @@ -316,7 +316,7 @@ public class JavaCommercialPaper implements Contract { public TransactionBuilder generateIssue(@NotNull PartyAndReference issuance, @NotNull Amount> faceValue, @Nullable Instant maturityDate, @NotNull Party notary, Integer encumbrance) { State state = new State(issuance, issuance.getParty(), faceValue, maturityDate); TransactionState output = new TransactionState<>(state, notary, encumbrance); - return new TransactionBuilder(notary).withItems(output, new Command(new Commands.Issue(), issuance.getParty().getOwningKey())); + return new TransactionBuilder(notary).withItems(output, new Command<>(new Commands.Issue(), issuance.getParty().getOwningKey())); } public TransactionBuilder generateIssue(@NotNull PartyAndReference issuance, @NotNull Amount> faceValue, @Nullable Instant maturityDate, @NotNull Party notary) { @@ -327,12 +327,12 @@ public class JavaCommercialPaper implements Contract { public void generateRedeem(TransactionBuilder tx, StateAndRef paper, VaultService vault) throws InsufficientBalanceException { vault.generateSpend(tx, StructuresKt.withoutIssuer(paper.getState().getData().getFaceValue()), paper.getState().getData().getOwner(), null); tx.addInputState(paper); - tx.addCommand(new Command(new Commands.Redeem(), paper.getState().getData().getOwner().getOwningKey())); + tx.addCommand(new Command<>(new Commands.Redeem(), paper.getState().getData().getOwner().getOwningKey())); } public void generateMove(TransactionBuilder tx, StateAndRef paper, AbstractParty newOwner) { tx.addInputState(paper); tx.addOutputState(new TransactionState<>(new State(paper.getState().getData().getIssuance(), newOwner, paper.getState().getData().getFaceValue(), paper.getState().getData().getMaturityDate()), paper.getState().getNotary(), paper.getState().getEncumbrance())); - tx.addCommand(new Command(new Commands.Move(), paper.getState().getData().getOwner().getOwningKey())); + tx.addCommand(new Command<>(new Commands.Move(), paper.getState().getData().getOwner().getOwningKey())); } } diff --git a/finance/src/main/kotlin/net/corda/contracts/FinanceTypes.kt b/finance/src/main/kotlin/net/corda/contracts/FinanceTypes.kt index 82b1ff1a41..82a9dda144 100644 --- a/finance/src/main/kotlin/net/corda/contracts/FinanceTypes.kt +++ b/finance/src/main/kotlin/net/corda/contracts/FinanceTypes.kt @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonSerialize +import net.corda.contracts.asset.CommodityContract import net.corda.core.contracts.CommandData import net.corda.core.contracts.LinearState import net.corda.core.contracts.StateAndRef @@ -25,7 +26,6 @@ import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Interest rate fixes @@ -83,7 +83,6 @@ data class Tenor(val name: String) { TimeUnit.Week -> startDate.plusWeeks(amount.toLong()) TimeUnit.Month -> startDate.plusMonths(amount.toLong()) TimeUnit.Year -> startDate.plusYears(amount.toLong()) - else -> throw IllegalStateException("Invalid tenor time unit: $unit") } // Move date to the closest business day when it falls on a weekend/holiday val adjustedMaturityDate = calendar.applyRollConvention(maturityDate, DateRollConvention.ModifiedFollowing) diff --git a/finance/src/test/kotlin/net/corda/flows/CashPaymentFlowTests.kt b/finance/src/test/kotlin/net/corda/flows/CashPaymentFlowTests.kt index 8dee2c15b8..dc08932846 100644 --- a/finance/src/test/kotlin/net/corda/flows/CashPaymentFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/flows/CashPaymentFlowTests.kt @@ -72,17 +72,17 @@ class CashPaymentFlowTests { expect { update -> require(update.consumed.size == 1) { "Expected 1 consumed states, actual: $update" } require(update.produced.size == 1) { "Expected 1 produced states, actual: $update" } - val changeState = update.produced.single().state.data as Cash.State + val changeState = update.produced.single().state.data assertEquals(expectedChange.`issued by`(bankOfCorda.ref(ref)), changeState.amount) } } // Check notary node vault updates vaultUpdatesBankClient.expectEvents { - expect { update -> - require(update.consumed.isEmpty()) { update.consumed.size } - require(update.produced.size == 1) { update.produced.size } - val paymentState = update.produced.single().state.data as Cash.State + expect { (consumed, produced) -> + require(consumed.isEmpty()) { consumed.size } + require(produced.size == 1) { produced.size } + val paymentState = produced.single().state.data assertEquals(expectedPayment.`issued by`(bankOfCorda.ref(ref)), paymentState.amount) } } diff --git a/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt b/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt index f16fc7703b..7e21ef1f3e 100644 --- a/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt +++ b/finance/src/test/kotlin/net/corda/flows/IssuerFlowTest.kt @@ -14,10 +14,12 @@ import net.corda.core.node.services.vault.QueryCriteria import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.OpaqueBytes import net.corda.flows.IssuerFlow.IssuanceRequester -import net.corda.testing.* import net.corda.testing.contracts.calculateRandomlySizedAmounts +import net.corda.testing.expect +import net.corda.testing.expectEvents import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNetwork.MockNode +import net.corda.testing.sequence import org.junit.After import org.junit.Before import org.junit.Test @@ -79,7 +81,7 @@ class IssuerFlowTest(val anonymous: Boolean) { expect { update -> require(update.consumed.isEmpty()) { "Expected 0 consumed states, actual: $update" } require(update.produced.size == 1) { "Expected 1 produced states, actual: $update" } - val issued = update.produced.single().state.data as Cash.State + val issued = update.produced.single().state.data require(issued.owner.owningKey in bankOfCordaNode.services.keyManagementService.keys) }, // MOVE @@ -93,10 +95,10 @@ class IssuerFlowTest(val anonymous: Boolean) { // Check Bank Client Vault Updates vaultUpdatesBankClient.expectEvents { // MOVE - expect { update -> - require(update.consumed.isEmpty()) { update.consumed.size } - require(update.produced.size == 1) { update.produced.size } - val paidState = update.produced.single().state.data as Cash.State + expect { (consumed, produced) -> + require(consumed.isEmpty()) { consumed.size } + require(produced.size == 1) { produced.size } + val paidState = produced.single().state.data require(paidState.owner.owningKey in bankClientNode.services.keyManagementService.keys) } } diff --git a/node-schemas/src/test/kotlin/net/corda/node/services/vault/schemas/VaultSchemaTest.kt b/node-schemas/src/test/kotlin/net/corda/node/services/vault/schemas/VaultSchemaTest.kt index 7f5e92aadb..c6a6cfb9dd 100644 --- a/node-schemas/src/test/kotlin/net/corda/node/services/vault/schemas/VaultSchemaTest.kt +++ b/node-schemas/src/test/kotlin/net/corda/node/services/vault/schemas/VaultSchemaTest.kt @@ -464,12 +464,12 @@ class VaultSchemaTest : TestDependencyInjectionBase() { fun testInsert() { val stateEntity = createStateEntity(transaction!!.inputs[0]) val latch = CountDownLatch(1) - odata.insert(stateEntity).subscribe { stateEntity -> - Assert.assertNotNull(stateEntity.txId) - Assert.assertTrue(stateEntity.txId.isNotEmpty()) + odata.insert(stateEntity).subscribe { + Assert.assertNotNull(it.txId) + Assert.assertTrue(it.txId.isNotEmpty()) val cached = data.select(VaultSchema.VaultStates::class) - .where(VaultSchema.VaultStates::txId.eq(stateEntity.txId)).get().first() - Assert.assertSame(cached, stateEntity) + .where(VaultSchema.VaultStates::txId.eq(it.txId)).get().first() + Assert.assertSame(cached, it) latch.countDown() } latch.await() diff --git a/node/src/integration-test/kotlin/net/corda/node/services/AdvertisedServiceTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/AdvertisedServiceTests.kt index f64850c8e0..9f422f7e16 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/AdvertisedServiceTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/AdvertisedServiceTests.kt @@ -21,10 +21,9 @@ class AdvertisedServiceTests { @StartableByRPC class ServiceTypeCheckingFlow : FlowLogic() { - @Suspendable override fun call(): Boolean { - return serviceHub.networkMapCache.getAnyServiceOfType(ServiceType.corda.getSubType("custom")) != null; + return serviceHub.networkMapCache.getAnyServiceOfType(ServiceType.corda.getSubType("custom")) != null } } @@ -32,7 +31,7 @@ class AdvertisedServiceTests { fun `service is accessible through getAnyServiceOfType`() { driver(startNodesInProcess = true) { val bankA = startNode(rpcUsers = listOf(User(user, pass, setOf(startFlowPermission())))).get() - val bankB = startNode(advertisedServices = setOf(ServiceInfo(serviceType, serviceName))).get() + startNode(advertisedServices = setOf(ServiceInfo(serviceType, serviceName))).get() bankA.rpcClientToNode().use(user, pass) { connection -> val result = connection.proxy.startFlow(::ServiceTypeCheckingFlow).returnValue.get() assertTrue(result) diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt b/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt index f1d9c823e7..6367346bbc 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/DistributedImmutableMap.kt @@ -54,7 +54,7 @@ class DistributedImmutableMap(val db: CordaPersistence, tableN * @return map containing conflicting entries */ fun put(commit: Commit>): Map { - commit.use { commit -> + commit.use { val conflicts = LinkedHashMap() db.transaction { val entries = commit.operation().entries diff --git a/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt b/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt index 510420e753..8a84d9a354 100644 --- a/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt +++ b/node/src/main/kotlin/net/corda/node/shell/InteractiveShell.kt @@ -9,13 +9,12 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.google.common.io.Closeables import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.SettableFuture -import net.corda.core.* import net.corda.core.flows.FlowInitiator import net.corda.core.flows.FlowLogic import net.corda.core.internal.* import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.StateMachineUpdate -import net.corda.core.internal.Emoji +import net.corda.core.then import net.corda.core.utilities.loggerFor import net.corda.jackson.JacksonSupport import net.corda.jackson.StringToMethodCallParser @@ -48,7 +47,6 @@ import org.crsh.vfs.spi.url.ClassPathMountFactory import rx.Observable import rx.Subscriber import java.io.* -import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException import java.nio.file.Files import java.nio.file.Path @@ -274,25 +272,25 @@ object InteractiveShell { val errors = ArrayList() for (ctor in clazz.constructors) { var paramNamesFromConstructor: List? = null - fun getPrototype(ctor: Constructor<*>): List { + fun getPrototype(): List { val argTypes = ctor.parameterTypes.map { it.simpleName } - val prototype = paramNamesFromConstructor!!.zip(argTypes).map { (name, type) -> "$name: $type" } - return prototype + return paramNamesFromConstructor!!.zip(argTypes).map { (name, type) -> "$name: $type" } } + try { // Attempt construction with the given arguments. paramNamesFromConstructor = parser.paramNamesFromConstructor(ctor) val args = parser.parseArguments(clazz.name, paramNamesFromConstructor.zip(ctor.parameterTypes), inputData) if (args.size != ctor.parameterTypes.size) { - errors.add("${getPrototype(ctor)}: Wrong number of arguments (${args.size} provided, ${ctor.parameterTypes.size} needed)") + errors.add("${getPrototype()}: Wrong number of arguments (${args.size} provided, ${ctor.parameterTypes.size} needed)") continue } val flow = ctor.newInstance(*args) as FlowLogic<*> return invoke(flow) } catch(e: StringToMethodCallParser.UnparseableCallException.MissingParameter) { - errors.add("${getPrototype(ctor)}: missing parameter ${e.paramName}") + errors.add("${getPrototype()}: missing parameter ${e.paramName}") } catch(e: StringToMethodCallParser.UnparseableCallException.TooManyParameters) { - errors.add("${getPrototype(ctor)}: too many parameters") + errors.add("${getPrototype()}: too many parameters") } catch(e: StringToMethodCallParser.UnparseableCallException.ReflectionDataMissing) { val argTypes = ctor.parameterTypes.map { it.simpleName } errors.add("$argTypes: ") diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index 9f3a4b91ad..2a99e2fe18 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -173,7 +173,7 @@ class CordaRPCOpsImplTest { ) } - val tx = result.returnValue.getOrThrow() + result.returnValue.getOrThrow() transactions.expectEvents { sequence( // ISSUE diff --git a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt index 47dea9e954..d9b395ffda 100644 --- a/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt +++ b/node/src/test/kotlin/net/corda/node/messaging/TwoPartyTradeFlowTests.kt @@ -203,7 +203,7 @@ class TwoPartyTradeFlowTests { bobNode.disableDBCloseOnStop() val bobAddr = bobNode.network.myAddress as InMemoryMessagingNetwork.PeerHandle - val networkMapAddr = notaryNode.network.myAddress + val networkMapAddress = notaryNode.network.myAddress mockNet.runNetwork() // Clear network map registration messages @@ -249,7 +249,7 @@ class TwoPartyTradeFlowTests { // ... bring the node back up ... the act of constructing the SMM will re-register the message handlers // that Bob was waiting on before the reboot occurred. - bobNode = mockNet.createNode(networkMapAddr, bobAddr.id, object : MockNetwork.Factory { + bobNode = mockNet.createNode(networkMapAddress, bobAddr.id, object : MockNetwork.Factory { override fun create(config: NodeConfiguration, network: MockNetwork, networkMapAddr: SingleMessageRecipient?, advertisedServices: Set, id: Int, overrideServices: Map?, entropyRoot: BigInteger): MockNetwork.MockNode { @@ -289,11 +289,11 @@ class TwoPartyTradeFlowTests { // Creates a mock node with an overridden storage service that uses a RecordingMap, that lets us test the order // of gets and puts. private fun makeNodeWithTracking( - networkMapAddr: SingleMessageRecipient?, + networkMapAddress: SingleMessageRecipient?, name: X500Name, - overrideServices: Map? = null): MockNetwork.MockNode { + overridenServices: Map? = null): MockNetwork.MockNode { // Create a node in the mock network ... - return mockNet.createNode(networkMapAddr, -1, object : MockNetwork.Factory { + return mockNet.createNode(networkMapAddress, -1, object : MockNetwork.Factory { override fun create(config: NodeConfiguration, network: MockNetwork, networkMapAddr: SingleMessageRecipient?, @@ -307,7 +307,7 @@ class TwoPartyTradeFlowTests { } } } - }, true, name, overrideServices) + }, true, name, overridenServices) } @Test diff --git a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt index ed44a63309..eda775af3f 100644 --- a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt +++ b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/BankOfCordaDriver.kt @@ -7,15 +7,15 @@ import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceType import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.NetworkHostAndPort -import net.corda.testing.DUMMY_NOTARY import net.corda.flows.CashExitFlow import net.corda.flows.CashPaymentFlow import net.corda.flows.IssuerFlow -import net.corda.testing.driver.driver import net.corda.node.services.startFlowPermission import net.corda.node.services.transactions.SimpleNotaryService import net.corda.nodeapi.User import net.corda.testing.BOC +import net.corda.testing.DUMMY_NOTARY +import net.corda.testing.driver.driver import org.bouncycastle.asn1.x500.X500Name import kotlin.system.exitProcess @@ -55,38 +55,48 @@ private class BankOfCordaDriver { // The ISSUER will launch a Bank of Corda node // The ISSUE_CASH will request some Cash from the ISSUER on behalf of Big Corporation node val role = options.valueOf(roleArg)!! - if (role == Role.ISSUER) { - driver(dsl = { - val bankUser = User(BANK_USERNAME, "test", permissions = setOf(startFlowPermission(), startFlowPermission(), startFlowPermission())) - val bigCorpUser = User(BIGCORP_USERNAME, "test", permissions = setOf(startFlowPermission())) - startNode(DUMMY_NOTARY.name, setOf(ServiceInfo(SimpleNotaryService.type))) - val bankOfCorda = startNode(BOC.name, rpcUsers = listOf(bankUser), advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("issuer.USD")))) - startNode(BIGCORP_LEGAL_NAME, rpcUsers = listOf(bigCorpUser)) - startWebserver(bankOfCorda.get()) - waitForAllNodesToFinish() - }, isDebug = true) - } else { - try { - val anonymous = true - val requestParams = IssueRequestParams(options.valueOf(quantity), options.valueOf(currency), BIGCORP_LEGAL_NAME, "1", BOC.name, DUMMY_NOTARY.name, anonymous) - when (role) { - Role.ISSUE_CASH_RPC -> { - println("Requesting Cash via RPC ...") - val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10006)).requestRPCIssue(requestParams) - if (result is SignedTransaction) - println("Success!! You transaction receipt is ${result.tx.id}") - } - Role.ISSUE_CASH_WEB -> { - println("Requesting Cash via Web ...") - val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10007)).requestWebIssue(requestParams) - if (result) - println("Successfully processed Cash Issue request") - } + + val anonymous = true + val requestParams = IssueRequestParams(options.valueOf(quantity), options.valueOf(currency), BIGCORP_LEGAL_NAME, "1", BOC.name, DUMMY_NOTARY.name, anonymous) + + try { + when (role) { + Role.ISSUER -> { + driver(dsl = { + val bankUser = User( + BANK_USERNAME, + "test", + permissions = setOf( + startFlowPermission(), + startFlowPermission(), + startFlowPermission())) + val bigCorpUser = User(BIGCORP_USERNAME, "test", permissions = setOf(startFlowPermission())) + startNode(DUMMY_NOTARY.name, setOf(ServiceInfo(SimpleNotaryService.type))) + val bankOfCorda = startNode( + BOC.name, + rpcUsers = listOf(bankUser), + advertisedServices = setOf(ServiceInfo(ServiceType.corda.getSubType("issuer.USD")))) + startNode(BIGCORP_LEGAL_NAME, rpcUsers = listOf(bigCorpUser)) + startWebserver(bankOfCorda.get()) + waitForAllNodesToFinish() + }, isDebug = true) + } + Role.ISSUE_CASH_RPC -> { + println("Requesting Cash via RPC ...") + val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10006)).requestRPCIssue(requestParams) + if (result is SignedTransaction) + println("Success!! You transaction receipt is ${result.tx.id}") + } + Role.ISSUE_CASH_WEB -> { + println("Requesting Cash via Web ...") + val result = BankOfCordaClientApi(NetworkHostAndPort("localhost", 10007)).requestWebIssue(requestParams) + if (result) + println("Successfully processed Cash Issue request") } - } catch (e: Exception) { - println("Exception occurred: $e \n ${e.printStackTrace()}") - exitProcess(1) } + } catch (e: Exception) { + println("Exception occurred: $e \n ${e.printStackTrace()}") + exitProcess(1) } } 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 afcfac1f43..0b34998c98 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 @@ -26,8 +26,8 @@ class VisualiserViewModel { inner class NodeWidget(val node: MockNetwork.MockNode, val innerDot: Circle, val outerDot: Circle, val longPulseDot: Circle, val pulseAnim: Animation, val longPulseAnim: Animation, val nameLabel: Label, val statusLabel: Label) { - fun position(index: Int, nodeCoords: (node: MockNetwork.MockNode, index: Int) -> Pair) { - val (x, y) = nodeCoords(node, index) + fun position(nodeCoords: (node: MockNetwork.MockNode) -> Pair) { + val (x, y) = nodeCoords(node) innerDot.centerX = x innerDot.centerY = y outerDot.centerX = x @@ -63,15 +63,15 @@ class VisualiserViewModel { fun repositionNodes() { for ((index, bank) in simulation.banks.withIndex()) { - nodesToWidgets[bank]!!.position(index, when (displayStyle) { - Style.MAP -> { node, _ -> nodeMapCoords(node) } - Style.CIRCLE -> { _, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.BANK, index) } + nodesToWidgets[bank]!!.position(when (displayStyle) { + Style.MAP -> { node -> nodeMapCoords(node) } + Style.CIRCLE -> { _ -> nodeCircleCoords(NetworkMapVisualiser.NodeType.BANK, index) } }) } for ((index, serviceProvider) in (simulation.serviceProviders + simulation.regulators).withIndex()) { - nodesToWidgets[serviceProvider]!!.position(index, when (displayStyle) { - Style.MAP -> { node, _ -> nodeMapCoords(node) } - Style.CIRCLE -> { _, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.SERVICE, index) } + nodesToWidgets[serviceProvider]!!.position(when (displayStyle) { + Style.MAP -> { node -> nodeMapCoords(node) } + Style.CIRCLE -> { _ -> nodeCircleCoords(NetworkMapVisualiser.NodeType.SERVICE, index) } }) } } @@ -172,8 +172,8 @@ class VisualiserViewModel { val widget = NodeWidget(forNode, innerDot, outerDot, longPulseOuterDot, pulseAnim, longPulseAnim, nameLabel, statusLabel) when (displayStyle) { - Style.CIRCLE -> widget.position(index, { _, index -> nodeCircleCoords(nodeType, index) }) - Style.MAP -> widget.position(index, { node, _ -> nodeMapCoords(node) }) + Style.CIRCLE -> widget.position { _ -> nodeCircleCoords(nodeType, index) } + Style.MAP -> widget.position { node -> nodeMapCoords(node) } } return widget } diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt index 50f51bc9e1..cc0155fcda 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt @@ -1,11 +1,11 @@ package net.corda.notarydemo.flows import co.paralleluniverse.fibers.Suspendable -import net.corda.testing.contracts.DummyContract import net.corda.core.flows.FlowLogic import net.corda.core.flows.StartableByRPC import net.corda.core.identity.Party import net.corda.core.transactions.SignedTransaction +import net.corda.testing.contracts.DummyContract import java.util.* @StartableByRPC @@ -18,7 +18,6 @@ class DummyIssueAndMove(private val notary: Party, private val counterpartyNode: val issueTx = serviceHub.signInitialTransaction(issueTxBuilder) serviceHub.recordTransactions(issueTx) // Move ownership of the asset to the counterparty - val counterPartyKey = counterpartyNode.owningKey val asset = issueTx.tx.outRef(0) val moveTxBuilder = DummyContract.move(asset, counterpartyNode) val moveTx = serviceHub.signInitialTransaction(moveTxBuilder) diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt index a30bc3f7fe..ca6271ed98 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt @@ -56,12 +56,12 @@ fun InitialMarginTriple.toCordaCompatible() = InitialMarginTriple(twoDecimalPlac * Utility function to ensure that [CurrencyParameterSensitivities] can be sent over corda and compared */ fun CurrencyParameterSensitivities.toCordaCompatible(): CurrencyParameterSensitivities { - return CurrencyParameterSensitivities.of(this.sensitivities.map { - it.metaBean().builder() - .set("marketDataName", it.marketDataName) - .set("parameterMetadata", it.parameterMetadata) - .set("currency", Currency.of(it.currency.code).serialize().deserialize()) - .set("sensitivity", it.sensitivity.map { it -> twoDecimalPlaces(it) }) + return CurrencyParameterSensitivities.of(this.sensitivities.map { sensitivity -> + sensitivity.metaBean().builder() + .set("marketDataName", sensitivity.marketDataName) + .set("parameterMetadata", sensitivity.parameterMetadata) + .set("currency", Currency.of(sensitivity.currency.code).serialize().deserialize()) + .set("sensitivity", sensitivity.sensitivity.map { twoDecimalPlaces(it) }) .build() }) } 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 b3d07e6363..02cf2bd93b 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 @@ -211,45 +211,43 @@ class Network : CordaView() { private fun List.getParties() = map { it.participants.map { getModel().lookup(it.owningKey) } }.flatten() private fun fireBulletBetweenNodes(senderNode: Party, destNode: Party, startType: String, endType: String) { - allComponentMap[senderNode]?.let { senderNode -> - allComponentMap[destNode]?.let { destNode -> - val sender = senderNode.label.boundsInParentProperty().map { Point2D(it.width / 2 + it.minX, it.height / 4 - 2.5 + it.minY) } - val receiver = destNode.label.boundsInParentProperty().map { Point2D(it.width / 2 + it.minX, it.height / 4 - 2.5 + it.minY) } - val bullet = Circle(3.0) - bullet.styleClass += "bullet" - bullet.styleClass += "connection-$startType-to-$endType" - with(TranslateTransition(stepDuration, bullet)) { - fromXProperty().bind(sender.map { it.x }) - fromYProperty().bind(sender.map { it.y }) - toXProperty().bind(receiver.map { it.x }) - toYProperty().bind(receiver.map { it.y }) - setOnFinished { mapPane.children.remove(bullet) } + val senderNodeComp = allComponentMap[senderNode] ?: return + val destNodeComp = allComponentMap[destNode] ?: return + val sender = senderNodeComp.label.boundsInParentProperty().map { Point2D(it.width / 2 + it.minX, it.height / 4 - 2.5 + it.minY) } + val receiver = destNodeComp.label.boundsInParentProperty().map { Point2D(it.width / 2 + it.minX, it.height / 4 - 2.5 + it.minY) } + val bullet = Circle(3.0) + bullet.styleClass += "bullet" + bullet.styleClass += "connection-$startType-to-$endType" + with(TranslateTransition(stepDuration, bullet)) { + fromXProperty().bind(sender.map { it.x }) + fromYProperty().bind(sender.map { it.y }) + toXProperty().bind(receiver.map { it.x }) + toYProperty().bind(receiver.map { it.y }) + setOnFinished { mapPane.children.remove(bullet) } + play() + } + val line = Line().apply { + styleClass += "message-line" + startXProperty().bind(sender.map { it.x }) + startYProperty().bind(sender.map { it.y }) + endXProperty().bind(receiver.map { it.x }) + endYProperty().bind(receiver.map { it.y }) + } + // Fade in quick, then fade out slow. + with(FadeTransition(stepDuration.divide(5.0), line)) { + fromValue = 0.0 + toValue = 1.0 + play() + setOnFinished { + with(FadeTransition(stepDuration.multiply(6.0), line)) { + fromValue = 1.0 + toValue = 0.0 play() + setOnFinished { mapPane.children.remove(line) } } - val line = Line().apply { - styleClass += "message-line" - startXProperty().bind(sender.map { it.x }) - startYProperty().bind(sender.map { it.y }) - endXProperty().bind(receiver.map { it.x }) - endYProperty().bind(receiver.map { it.y }) - } - // Fade in quick, then fade out slow. - with(FadeTransition(stepDuration.divide(5.0), line)) { - fromValue = 0.0 - toValue = 1.0 - play() - setOnFinished { - with(FadeTransition(stepDuration.multiply(6.0), line)) { - fromValue = 1.0 - toValue = 0.0 - play() - setOnFinished { mapPane.children.remove(line) } - } - } - } - mapPane.children.add(1, line) - mapPane.children.add(bullet) } } + mapPane.children.add(1, line) + mapPane.children.add(bullet) } } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt index d2a59c1cea..11adadf9dc 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/cordapps/cash/NewTransaction.kt @@ -22,13 +22,12 @@ import net.corda.core.contracts.sumOrNull import net.corda.core.contracts.withoutIssuer import net.corda.core.flows.FlowException import net.corda.core.getOrThrow -import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party import net.corda.core.messaging.FlowHandle import net.corda.core.messaging.startFlow import net.corda.core.node.NodeInfo -import net.corda.core.utilities.OpaqueBytes import net.corda.core.transactions.SignedTransaction +import net.corda.core.utilities.OpaqueBytes import net.corda.explorer.formatters.PartyNameFormatter import net.corda.explorer.model.CashTransaction import net.corda.explorer.model.IssuerModel @@ -111,7 +110,7 @@ class NewTransaction : Fragment() { } finally { dialog.dialogPane.isDisable = false } - }.ui { it -> + }.ui { val stx: SignedTransaction = it.stx val type = when (command) { is CashFlowCommand.IssueCash -> "Cash Issued" @@ -193,7 +192,7 @@ class NewTransaction : Fragment() { // Issuer issuerLabel.visibleProperty().bind(transactionTypeCB.valueProperty().isNotNull) issuerChoiceBox.apply { - items = issuers.map { it.legalIdentity as Party }.unique().sorted() + items = issuers.map { it.legalIdentity }.unique().sorted() converter = stringConverter { PartyNameFormatter.short.format(it.name) } visibleProperty().bind(transactionTypeCB.valueProperty().map { it == CashTransaction.Pay }) } @@ -220,7 +219,7 @@ class NewTransaction : Fragment() { ) availableAmount.textProperty() .bind(Bindings.createStringBinding({ - val filteredCash = cash.filtered { it.token.issuer.party as AbstractParty == issuer.value && it.token.product == currencyChoiceBox.value } + val filteredCash = cash.filtered { it.token.issuer.party == issuer.value && it.token.product == currencyChoiceBox.value } .map { it.withoutIssuer() }.sumOrNull() "${filteredCash ?: "None"} Available" }, arrayOf(currencyChoiceBox.valueProperty(), issuerChoiceBox.valueProperty()))) diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt index 80167f0416..5b4f0f57ba 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt @@ -40,13 +40,12 @@ fun setupJSchWithSshAgent(): JSch { override fun getName() = connector.name override fun getIdentities(): Vector = Vector(listOf( object : Identity { - override fun clear() { - } - + override fun clear() {} override fun getAlgName() = String(Buffer(identity.blob).string) override fun getName() = String(identity.comment) override fun isEncrypted() = false override fun getSignature(data: ByteArray?) = agentProxy.sign(identity.blob, data) + @Suppress("OverridingDeprecatedMember") override fun decrypt() = true override fun getPublicKeyBlob() = identity.blob override fun setPassphrase(passphrase: ByteArray?) = true @@ -55,7 +54,7 @@ fun setupJSchWithSshAgent(): JSch { override fun remove(blob: ByteArray?) = throw UnsupportedOperationException() override fun removeAll() = throw UnsupportedOperationException() - override fun add(identity: ByteArray?) = throw UnsupportedOperationException() + override fun add(bytes: ByteArray?) = throw UnsupportedOperationException() } } } @@ -85,9 +84,6 @@ class ConnectionManager(private val jSch: JSch) { * Connects to a list of nodes and executes the passed in action with the connections as parameter. The connections are * safely cleaned up if an exception is thrown. * - * @param username The UNIX username to use for SSH authentication. - * @param nodeHosts The list of hosts. - * @param remoteMessagingPort The Artemis messaging port nodes are listening on. * @param tunnelPortAllocation A local port allocation strategy for creating SSH tunnels. * @param withConnections An action to run once we're connected to the nodes. * @return The return value of [withConnections] diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt index f2d90594ab..55f71c9177 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt @@ -257,9 +257,7 @@ val crossCashTest = LoadTest( if (minimum == null) { HashMap(next) } else { - next.forEach { entry -> - minimum.merge(entry.key, entry.value, Math::min) - } + next.forEach { minimum.merge(it.key, it.value, Math::min) } minimum } }!! diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/NotaryTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/NotaryTest.kt index 21a17d16bb..57f2005282 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/NotaryTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/NotaryTest.kt @@ -43,7 +43,7 @@ val dummyNotarisationTest = LoadTest( val proxy = node.proxy val issueFlow = proxy.startFlow(::FinalityFlow, issueTx) issueFlow.returnValue.thenMatch({ - val moveFlow = proxy.startFlow(::FinalityFlow, moveTx) + proxy.startFlow(::FinalityFlow, moveTx) }, {}) } catch (e: FlowException) { log.error("Failure", e)